The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): keep a reminder for an unrestarted unit dashboard; review folds
kshitijk4poorb65ad0c11573
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex a7744a0a6c7..6b2eb9b2670 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -5446,12 +5446,11 @@ def _refuse_restart_of_service_managed_gateway(pid: int | None) -> None:returnfrom hermes_cli import main_dashboard as _dash- unit = _dash._get_systemd_service_for_pid(pid)- if unit is None:+ owner = _dash._systemd_owner_for_pid(pid)+ if owner is None:return- scope = _dash._extract_scope_from_cgroup(_dash._get_pid_cgroup_path(pid) or "")- user_cmd, system_cmd = f"systemctl --user restart {unit}", f"sudo systemctl restart {unit}"- cmds = {"user": [user_cmd], "system": [system_cmd]}.get(scope, [user_cmd, system_cmd])+ unit, scope = owner+ cmds = _dash._systemd_restart_commands(unit, scope)_print_lines("",f"✗ Gateway (PID {pid}) is managed by systemd unit {unit}.",diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex 4c28a906cf4..c53daa3388c 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -231,6 +231,22 @@ def _get_pid_cgroup_path(pid: int) -> str | None:return next(_pid_unified_cgroup_entries(pid), None)+def _systemd_owner_for_pid(pid: int) -> tuple[str, str | None] | None:+ """``(unit, scope)`` of the systemd unit whose live ``MainPID`` is *pid*; ``None`` when no unit+ provably owns it (see :func:`_get_systemd_service_for_pid`). Scope is ``user``/``system`` or+ ``None`` when the cgroup path does not say."""+ unit = _get_systemd_service_for_pid(pid)+ if unit is None:+ return None+ return unit, _extract_scope_from_cgroup(_get_pid_cgroup_path(pid) or "")+++def _systemd_restart_commands(unit: str, scope: str | None) -> list[str]:+ """The command(s) that restart *unit* in its scope; both forms when the scope is unknown."""+ user_cmd, system_cmd = f"systemctl --user restart {unit}", f"sudo systemctl restart {unit}"+ return {"user": [user_cmd], "system": [system_cmd]}.get(scope or "", [user_cmd, system_cmd])++def _try_restart_systemd_service(svc_name: str, cgroup_path: str | None = None) -> bool:"""Restart *svc_name* via systemctl (``--user`` for user-scope units). True on success.diff --git a/hermes_cli/update_abort_recovery.py b/hermes_cli/update_abort_recovery.pyindex 7a3ffd6b528..462b6b40514 100644--- a/hermes_cli/update_abort_recovery.py+++ b/hermes_cli/update_abort_recovery.py@@ -244,11 +244,11 @@ def _warn_stale_serve_runtimes(rows) -> None:print(" Ask their owner to relaunch `hermes serve` / `hermes dashboard`, or reconnect Desktop for an SSH backend.")# A unit-managed backend restarts through its own unit and scope — never "ask the owner to# relaunch", and never a hardcoded user-scope hermes-serve (#141021).+ from hermes_cli.main_dashboard import _systemd_restart_commands+for row in unit_rows:- unit = row.get("systemd_unit") or "<unit>"- command = {"user": "systemctl --user", "system": "sudo systemctl"}.get(- row.get("systemd_scope"), "systemctl [--user]")- print(f" pid {row.get('pid')} is managed by systemd: `{command} restart {unit}`")+ commands = _systemd_restart_commands(row.get("systemd_unit") or "<unit>", row.get("systemd_scope"))+ print(f" pid {row.get('pid')} is managed by systemd: {' or '.join(f'`{c}`' for c in commands)}")if sys.platform == "darwin" and any(row.get("supervisor") == "launchd" for row in rows):print(" For launchd-managed backends: `launchctl kickstart -k gui/$UID/<label>`.")diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex d22ffc8a08f..22bee8db8e7 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -1012,9 +1012,10 @@ _DESKTOP_SERVE_SKIP_REASON = ("desktop app owns and respawns this serve backend;"" the recovery pass must not restart it out from under its supervisor")-# NOT a claim that no supervisor exists: a systemd-launched serve sets neither HERMES_SPAWN-# nor HERMES_PARENT_PID ("manual-serve"). Unit-backed serves are recovered by the fresh-# child's systemd pass; survivors reported by _surviving_pre_update_serve_runtimes.+# NOT a claim that no supervisor exists: a unit's MainPID row is classified "systemd" (#141021),+# and "manual-serve" still covers a process inside some unit's cgroup it is not MainPID of, or+# unreadable ownership. Unit-backed serves are recovered by the fresh child's systemd pass;+# survivors reported by _surviving_pre_update_serve_runtimes._SERVE_SKIP_REASON = ("no per-profile relaunch command reaches a serve/dashboard runtime; recovered by the fresh"" systemd unit pass when it owns a hermes-serve* unit, else left running for explicit"diff --git a/hermes_cli/update_cmd_fleet_verify.py b/hermes_cli/update_cmd_fleet_verify.pyindex e1b792a177b..86db6cd98da 100644--- a/hermes_cli/update_cmd_fleet_verify.py+++ b/hermes_cli/update_cmd_fleet_verify.py@@ -183,29 +183,34 @@ def _named_gateways_still_owed() -> bool:def _is_serve_unit(name: object) -> bool:- """A ``hermes-serve*``/``hermes-dashboard*`` unit name (bare or ``.service``) — the restart phase's- serve family. Anything else it lists (gateway units, launchd labels, listing-failure markers) is- gateway evidence."""- from hermes_cli.update_restart_recovery import _UNIT_RE+ """A serve/dashboard unit by the fleet loop's OWN name gate (``hermes-serve*``/``hermes-dashboard*``,+ bare or ``.service``). Anything else it records as failed (gateway units, launchd labels,+ listing-failure markers) is gateway evidence."""+ from hermes_cli.update_cmd_fleet import _is_hermes_gateway_unit, _service_unit_supports_graceful_sigusr1_restart- return bool(_UNIT_RE.fullmatch(f"{str(name).removesuffix('.service')}.service"))+ base = str(name).removesuffix(".service")+ return _is_hermes_gateway_unit(f"{base}.service") and not _service_unit_supports_graceful_sigusr1_restart(base)def _restart_phase_owes_gateway(restart) -> bool:"""Did the restart phase itself leave a gateway owed? Its incompleteness counts against thegateways unless every failure it recorded is a serve/dashboard unit (#141021)."""+ if not restart.incomplete:+ return Falsefailed = list(restart.failed_or_stale_units)- return bool(restart.incomplete) and (bool(restart.phase_errors) or not failed or not all(map(_is_serve_unit, failed)))+ return bool(restart.phase_errors) or not failed or not all(map(_is_serve_unit, failed))++def _split_unaccounted(outcomes) -> tuple[bool, set]:+ """``(gateway missed, serve/dashboard PIDs missed)`` among the unaccounted runtime outcomes."""+ from hermes_cli.update_inventory import _SERVE_KINDS-def _note_unaccounted(outcomes, stale_serves: set) -> bool:- """Record unaccounted serve PIDs into *stale_serves*; True when an unaccounted gateway remains."""missed = [o for o in outcomes if o.get("outcome") == "unaccounted"]- stale_serves.update(o["pid"] for o in missed if o.get("kind") != "gateway" and isinstance(o.get("pid"), int))- return any(o.get("kind") == "gateway" for o in missed)+ serve_pids = {o["pid"] for o in missed if o.get("kind") in _SERVE_KINDS and isinstance(o.get("pid"), int)}+ return any(o.get("kind") not in _SERVE_KINDS for o in missed), serve_pids-def _owed_restart_reason(restart, stopped, *, gateway_owed: bool, stale_serves: set) -> str:+def _owed_restart_reason(restart, stopped, *, gateway_owed: bool, stale_serves: set, down_serves: set) -> str:"""The ``gateway_restart`` follow-up's reason, naming what is actually owed (#141021).The step id stays ``gateway_restart`` (Desktop hand-offs parse it); only the text changes. A run@@ -220,12 +225,16 @@ def _owed_restart_reason(restart, stopped, *, gateway_owed: bool, stale_serves:units = sorted({str(u).removesuffix(".service") for u in restart.failed_or_stale_units if _is_serve_unit(u)})if units:parts.append(- f"serve/dashboard unit(s) {', '.join(units)} still run pre-update code; restart them with the"- " systemctl command printed above (`sudo systemctl restart <unit>` for a system unit)")- if stale_serves:+ f"serve/dashboard unit(s) {', '.join(units)} were not restarted onto the new code;"+ " see the systemctl advice above")+ if down_serves:parts.append(- f"serve/dashboard process(es) {', '.join(map(str, sorted(stale_serves)))} still run pre-update"- " code; relaunch `hermes serve` / `hermes dashboard`")+ f"serve/dashboard process(es) {', '.join(map(str, sorted(down_serves)))} were stopped during the"+ " update and not brought back; relaunch `hermes serve` / `hermes dashboard`")+ if stale_serves - down_serves:+ parts.append(+ f"serve/dashboard process(es) {', '.join(map(str, sorted(stale_serves - down_serves)))} still run"+ " pre-update code; restart them as advised above")# Nothing classified (an unknown incompleteness): keep the historical, conservative wording.return "; ".join(parts) or ("gateways may still run pre-update code or were stopped without a successor; recover with `hermes gateway restart`")@@ -252,15 +261,15 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_re# Which family is owed decides what the follow-up tells the user to run (#141021). Read before the# dashboard pass can flip ``incomplete``._gateway_owed = _restart_phase_owes_gateway(restart)- # Units the fleet loop already handled aren't redone — restarted ones, and failed ones too: those- # already printed their manual restart command, and a retry here (no root either) only adds a- # polkit error under the same advice (#141021).+ # Units the fleet loop already attempted aren't redone — restarted ones, and failed ones too: the+ # loop already reported each failure (with its systemctl advice), and a second attempt only+ # duplicates it or, for a system unit without root, adds a polkit/tty error (#141021).# A dashboard it stopped and could not bring back is a promised restart that did not happen._dashboards_down = _refresh_dashboard_after_update(already_restarted_units=set(restart.restarted_services) | set(restart.failed_or_stale_units))if _dashboards_down:restart.incomplete = True- _stale_serves_owed: set = set(_dashboards_down or ())+ _stale_serves_owed: set = set()# Success-path twin of the abort-recovery probe: the restart phase only touches# units, so a unit-less `hermes serve` keeps stale sys.modules. Runs AFTER@@ -356,25 +365,34 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_relive_gateway_pids=_live_gateway_pids,)from dataclasses import asdict- from hermes_cli.update_serve_obligations import defer_manual_serve+ from hermes_cli.update_serve_obligations import defer_manual_serve, remind_unit_serve+ _stale_pids = {row.get("pid") for row in _stale_serve_rows or ()}for runtime, outcome in zip(_pre_update_plan.runtimes, _runtime_outcomes):if outcome["outcome"] == "unaccounted" and defer_manual_serve(asdict(runtime), require_alive=True):outcome["outcome"] = "deferred"+ elif runtime.pid in _stale_pids and runtime.supervisor == "systemd":+ # A unit the update could not restart keeps a startup reminder with its exact+ # command; the gateway obligation never names it (#141021).+ remind_unit_serve(asdict(runtime))if report_unaccounted_runtimes(_runtime_outcomes):restart.incomplete = True- _gateway_owed = _note_unaccounted(_runtime_outcomes, _stale_serves_owed) or _gateway_owed+ _missed_gateway, _missed_serves = _split_unaccounted(_runtime_outcomes)+ _gateway_owed |= _missed_gateway+ _stale_serves_owed |= _missed_serveswith suppress(Exception):import hermes_cli.update_receipt as _ur_active = _ur._current.get()if _active is not None:_active.data["runtime_outcomes"] = _runtime_outcomes- if not restart.incomplete:+ if not _gateway_owed:with _best_effort('Owed-gateway check failed: %s'):if _named_gateways_still_owed():# A gateway a previous run could not restart is still not serving HEAD (nothing# live to restart this time): keep owing it rather than clearing the obligation.+ # Checked even when a serve unit already made the run incomplete, so the follow-up+ # still names the gateway (#141021).print(" ⚠ A gateway owed a restart by a previous update is still not serving this checkout.")restart.incomplete = _gateway_owed = Trueif getattr(restart, "stopped_unmapped_pids", None):@@ -388,7 +406,8 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_refrom hermes_cli.update_receipt import record_followupstopped = sorted(getattr(restart, "stopped_unmapped_pids", None) or ())record_followup("gateway_restart", _owed_restart_reason(- restart, stopped, gateway_owed=_gateway_owed, stale_serves=_stale_serves_owed))+ restart, stopped, gateway_owed=_gateway_owed, stale_serves=_stale_serves_owed,+ down_serves=set(_dashboards_down or ())))with _best_effort('Fleet restart inventory not recorded: %s'):_record_owed_gateway_inventory(_pre_update_plan, stopped)with _best_effort('Update receipt finalize failed: %s'):diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.pyindex d029278a2fe..9046209cd2a 100644--- a/hermes_cli/update_inventory.py+++ b/hermes_cli/update_inventory.py@@ -270,10 +270,7 @@ def _systemd_owner_for_ledger_pid(pid: int) -> tuple[str, str | None] | None:with suppress(Exception):from hermes_cli import main_dashboard as _dash- unit = _dash._get_systemd_service_for_pid(pid)- if unit:- cgroup = _dash._get_pid_cgroup_path(pid)- return unit, _dash._extract_scope_from_cgroup(cgroup) if cgroup else None+ return _dash._systemd_owner_for_pid(pid)return None@@ -557,7 +554,8 @@ def match_runtime_outcomes(for r in plan.runtimes:if isinstance(r, RuntimeRecord):outcomes.append(- {"kind": r.kind, "profile": r.profile, "pid": r.pid, "mechanism": r.restart_via, "outcome": _outcome(r)}+ {"kind": r.kind, "profile": r.profile, "pid": r.pid, "mechanism": r.restart_via, "outcome": _outcome(r),+ **{k: r.detail[k] for k in ("systemd_unit", "systemd_scope") if k in (r.detail or {})}})except Exception as exc:logger.debug("Runtime-outcome reconciliation failed: %s", exc)@@ -608,9 +606,17 @@ def report_unaccounted_runtimes(outcomes: list[dict[str, Any]]) -> bool:if any(o.get("kind") in _SERVE_KINDS for o in missed):# A serve/dashboard is not reachable by any `gateway restart` command: name the process, not the wrong verb.# See #100479.- if sys.platform == "linux":- print(" systemctl --user restart hermes-serve.service # unit-managed serve")- print(" relaunch `hermes serve` / `hermes dashboard`")+ from hermes_cli.main_dashboard import _systemd_restart_commands++ for o in missed:+ if o.get("kind") in _SERVE_KINDS and o.get("systemd_unit"):+ # The owning unit and scope are known: name its exact command (#141021).+ for command in _systemd_restart_commands(o["systemd_unit"], o.get("systemd_scope")):+ print(f" {command} # pid {o['pid']}")+ if any(o.get("kind") in _SERVE_KINDS and not o.get("systemd_unit") for o in missed):+ if sys.platform == "linux":+ print(" systemctl --user restart hermes-serve.service # unit-managed serve")+ print(" relaunch `hermes serve` / `hermes dashboard`")return Truediff --git a/hermes_cli/update_serve_obligations.py b/hermes_cli/update_serve_obligations.pyindex e27cb8e9da6..cefee338338 100644--- a/hermes_cli/update_serve_obligations.py+++ b/hermes_cli/update_serve_obligations.py@@ -1,4 +1,5 @@-"""Durable manual-serve handoffs, independent of gateway restart receipts."""+"""Durable serve/dashboard restart reminders (manual serves, and unit-owned ones the update could not+restart), independent of gateway restart receipts."""import jsonimport logging@@ -37,28 +38,57 @@ def defer_manual_serve(runtime: dict, *, require_alive: bool = False) -> bool:return Falseif alive is False:return True- directory = get_hermes_home() / "serve_restart_pending"- directory.mkdir(parents=True, exist_ok=True)- row = {"kind": runtime["kind"], "profile": runtime.get("profile", "unknown"), "pid": pid, "create_time": created}- target = directory / f"{pid}-{float(created).hex()}.json"- # One immutable file per incarnation avoids read/merge/write races between CLI startups.- temporary = None- try:- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=directory, delete=False) as handle:- temporary = Path(handle.name)- json.dump(row, handle)- handle.flush()- os.fsync(handle.fileno())- os.replace(temporary, target)- finally:- if temporary is not None:- temporary.unlink(missing_ok=True)+ _write_reminder({"kind": runtime["kind"], "profile": runtime.get("profile", "unknown"), "pid": pid, "create_time": created})return Trueexcept (OSError, ValueError, TypeError) as exc:logger.debug("Could not preserve manual serve obligation: %s", exc)return False+def _write_reminder(row: dict) -> None:+ """Persist one reminder row, one immutable file per incarnation (no read/merge/write races+ between CLI startups). Raises OSError/ValueError/TypeError to the caller."""+ directory = get_hermes_home() / "serve_restart_pending"+ directory.mkdir(parents=True, exist_ok=True)+ target = directory / f"{row['pid']}-{float(row['create_time']).hex()}.json"+ temporary = None+ try:+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=directory, delete=False) as handle:+ temporary = Path(handle.name)+ json.dump(row, handle)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary, target)+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+++def remind_unit_serve(runtime: dict) -> bool:+ """File the same durable reminder for a stale serve/dashboard whose systemd unit this update could+ not restart (no root, #141021). The fleet obligation only names gateways, so without this the+ stale unit is never mentioned again after the update run. Carries the unit's restart command;+ cleared like a manual reminder once that incarnation exits. False when nothing was filed."""+ from hermes_cli.main_dashboard import _systemd_restart_commands+ from hermes_cli.process_identity import _pid_alive_matches++ detail = runtime.get("detail") if isinstance(runtime.get("detail"), dict) else {}+ pid, created, unit = runtime.get("pid"), detail.get("create_time"), detail.get("systemd_unit")+ if (runtime.get("kind") not in ("serve", "dashboard") or runtime.get("supervisor") != "systemd" or not unit+ or type(pid) is not int or pid <= 0 or type(created) not in (int, float) or not math.isfinite(created)):+ return False+ try:+ if _pid_alive_matches(pid, created) is not True:+ return False+ _write_reminder({"kind": runtime["kind"], "profile": runtime.get("profile", "unknown"), "pid": pid,+ "create_time": created,+ "restart": _systemd_restart_commands(str(unit), detail.get("systemd_scope"))})+ return True+ except (OSError, ValueError, TypeError) as exc:+ logger.debug("Could not preserve unit serve obligation: %s", exc)+ return False++def retain_receipt_manual_serves(receipt: dict) -> list[dict]:"""Return transfers still owed so receipt rotation cannot discard failed writes.@@ -101,6 +131,11 @@ def warn_pending_manual_serves(*, startup: bool = False, pending_manual: list[diif _pid_alive_matches(row["pid"], row["create_time"]) is False:path.unlink(missing_ok=True)continue+ restart = row.get("restart")+ if isinstance(restart, list) and restart:+ print(f" ⚠ {row['kind']} [{row['profile']}] pid {row['pid']}: unit restart still pending; this process may still serve pre-update code.", file=stream)+ print(f" Restart its unit: {' or '.join(f'`{c}`' for c in restart)}", file=stream)+ continueprint(f" ⚠ {row['kind']} [{row['profile']}] pid {row['pid']}: manual restart still pending; this process may still serve pre-update code.", file=stream)print(" Ask its owner to relaunch `hermes serve` / `hermes dashboard` (reconnect Desktop for an SSH backend).", file=stream)except (OSError, ValueError, KeyError, TypeError) as exc:diff --git a/tests/hermes_cli/test_update_system_dashboard_unit.py b/tests/hermes_cli/test_update_system_dashboard_unit.pyindex 611511a24d4..2e2d4160f8a 100644--- a/tests/hermes_cli/test_update_system_dashboard_unit.py+++ b/tests/hermes_cli/test_update_system_dashboard_unit.py@@ -50,6 +50,8 @@ def _systemd_owned_dashboard(monkeypatch, systemctl_calls: list):return SimpleNamespace(returncode=0, stdout="active\n", stderr="")if "is-enabled" in cmd:return SimpleNamespace(returncode=0, stdout="enabled\n", stderr="")+ if cmd[0] == "sudo":+ return SimpleNamespace(returncode=1, stdout="", stderr="sudo: a password is required")return SimpleNamespace(returncode=1, stdout="", stderr="Interactive authentication required.")monkeypatch.setattr(main_dashboard, "_run_probe", run_probe)@@ -66,9 +68,10 @@ def test_dashboard_pass_skips_a_unit_the_fleet_loop_already_declined(monkeypatchrestart_managed=True, already_restarted_units={"hermes-gateway", "hermes-dashboard"})assert not [c for c in calls if "restart" in c], "the declined unit was retried"- assert kills == [] and not result.get("unrecovered")+ assert not result.get("unrecovered")out = capsys.readouterr().out- assert "polkit" not in out and "failed to restart" not in out and "Restarting managed dashboard" not in out+ assert "Interactive authentication required" not in out and "a password is required" not in out+ assert "failed to restart" not in out and "Restarting managed dashboard" not in outdef test_dashboard_pass_still_restarts_the_unit_when_the_fleet_loop_never_saw_it(monkeypatch, capsys):@@ -94,8 +97,11 @@ def test_systemd_owned_ledger_dashboard_is_classified_systemd(monkeypatch):def test_hand_started_dashboard_in_a_foreign_cgroup_stays_manual(monkeypatch):- """No unit owns the PID as MainPID → still manual-serve (its respawn reminder still applies)."""- monkeypatch.setattr(main_dashboard, "_get_systemd_service_for_pid", lambda pid: None)+ """Started from a shell inside cron.service: the cgroup names a unit, but its MainPID is another+ process, so the real ownership rule keeps the row manual-serve (its respawn reminder applies)."""+ monkeypatch.setattr(main_dashboard, "_pid_unified_cgroup_entries", lambda pid: iter(["/system.slice/cron.service"]))+ monkeypatch.setattr(main_dashboard, "_run_probe",+ lambda cmd, *, timeout: SimpleNamespace(returncode=0, stdout="991\n", stderr=""))entry = {"pid": 4321, "create_time": 1.0, "purpose": "dashboard", "argv": "hermes dashboard"}monkeypatch.setitem(sys.modules, "hermes_cli.process_identity",SimpleNamespace(ledger_entries=lambda **k: [entry], spawner_is_dead=lambda e: None))@@ -117,14 +123,15 @@ def test_stale_unit_dashboard_hint_names_its_unit_and_scope(monkeypatch, capsys)assert "Ask their owner" not in out and "hermes-serve.service" not in out-def _verify(monkeypatch, restart, *, fleet_state="current", plan=None):+def _verify(monkeypatch, restart, *, fleet_state="current", plan=None, dashboards_down=frozenset(), survivors=()):refreshed: list = []monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)- monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])+ monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: list(survivors))monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update",- lambda **k: refreshed.append(k) or set())+ lambda **k: refreshed.append(k) or set(dashboards_down))monkeypatch.setattr(update_receipt, "_code_identity", lambda **k: {})monkeypatch.setattr("hermes_cli.gateway_migrate.maybe_auto_migrate_after_update", lambda: None)+ monkeypatch.setattr("hermes_cli.update_cmd_stale_survivors.signal_stale_fleet_survivors", lambda *a: None)monkeypatch.setattr(fleet_verify, "_collect_fleet_snapshot",lambda outcome, expected: [{"profile": "default", "pid": 1563620, "state": fleet_state}])update_cmd_fleet._write_fleet_restart_pending_marker()@@ -149,7 +156,7 @@ def test_field_case_forwards_the_declined_unit_and_blames_only_the_dashboard(monassert refreshed == [{"already_restarted_units": {"hermes-gateway", "hermes-dashboard"}}](followup,) = receipt["followups"]assert followup["step"] == "gateway_restart" # Desktop hand-offs parse the step id- assert "hermes-dashboard" in followup["reason"]+ assert "hermes-dashboard were not restarted onto the new code" in followup["reason"]assert "hermes gateway restart" not in followup["reason"]assert "gateways may still run" not in capsys.readouterr().out# The obligation stays armed: a stale dashboard unit is still owed (contract unchanged).@@ -171,8 +178,63 @@ def test_gateway_debt_still_names_gateway_restart(monkeypatch, case):assert "hermes gateway restart" in reason and "hermes-dashboard" in reason-def test_is_serve_unit_is_exact():+def test_is_serve_unit_matches_the_fleet_loop_gate():assert fleet_verify._is_serve_unit("hermes-dashboard")assert fleet_verify._is_serve_unit("hermes-serve-work.service")- for name in ("hermes-gateway", "hermes-dashboardd", "ai.hermes.gateway", "systemd-user (listing failed)"):+ assert fleet_verify._is_serve_unit("hermes-dashboard-Work.Two") # the loop admits any suffix+ for name in ("hermes-gateway", "hermes-gateway-work", "hermes-dashboardd", "ai.hermes.gateway",+ "systemd-user (listing failed)"):assert not fleet_verify._is_serve_unit(name)+++def test_dashboard_stopped_and_not_brought_back_is_not_called_still_running(monkeypatch):+ _refreshed, receipt = _verify(monkeypatch, _restart(incomplete=False, failed_or_stale_units=[]),+ dashboards_down={4242})+ reason = receipt["followups"][0]["reason"]+ assert "4242 were stopped during the update and not brought back" in reason+ assert "still run pre-update code" not in reason and "hermes gateway restart" not in reason+++def test_previously_owed_gateway_is_still_named_beside_a_failed_dashboard_unit(monkeypatch):+ monkeypatch.setattr(fleet_verify, "_named_gateways_still_owed", lambda: True)+ _refreshed, receipt = _verify(monkeypatch, _restart())+ reason = receipt["followups"][0]["reason"]+ assert "hermes gateway restart" in reason and "hermes-dashboard" in reason+++def _unit_dashboard_plan():+ return UpdatePlan(runtimes=[RuntimeRecord(+ kind="dashboard", profile="default", pid=DASH_PID, supervisor="systemd", restart_via="systemd",+ detail={"create_time": 1000.0, "systemd_unit": UNIT, "systemd_scope": "system"})])+++def test_unrestarted_unit_dashboard_keeps_a_startup_reminder_until_it_exits(monkeypatch, capsys):+ """The fleet obligation names only gateways, so once they are current the stale dashboard unit+ would never be mentioned again; it keeps its own reminder with the unit's command instead."""+ from hermes_cli import process_identity+ from hermes_cli.update_serve_obligations import warn_pending_manual_serves++ monkeypatch.setattr(process_identity, "_pid_alive_matches", lambda *a: True)+ survivor = {"pid": DASH_PID, "kind": "dashboard", "profile": "default", "supervisor": "systemd",+ "systemd_unit": UNIT, "systemd_scope": "system"}+ _verify(monkeypatch, _restart(), plan=_unit_dashboard_plan(), survivors=[survivor])+ capsys.readouterr()+ warn_pending_manual_serves(startup=True, pending_manual=[])+ err = capsys.readouterr().err+ assert f"dashboard [default] pid {DASH_PID}: unit restart still pending" in err+ assert f"`sudo systemctl restart {UNIT}`" in err and "Ask its owner" not in err+ monkeypatch.setattr(process_identity, "_pid_alive_matches", lambda *a: False)+ warn_pending_manual_serves(startup=True, pending_manual=[])+ assert str(DASH_PID) not in capsys.readouterr().err+++def test_unaccounted_unit_dashboard_hint_names_its_unit(capsys):+ plan = UpdatePlan(runtimes=[RuntimeRecord(+ kind="dashboard", profile="work", pid=DASH_PID, supervisor="systemd", restart_via="systemd",+ detail={"create_time": 1000.0, "systemd_unit": UNIT, "systemd_scope": "system"})])+ outcomes = update_inventory.match_runtime_outcomes(+ plan, restarted_services=[], relaunched_profiles=[], externally_supervised_profiles=[],+ killed_pids=set(), failed_units=[], stale_serve_pids={DASH_PID})+ assert update_inventory.report_unaccounted_runtimes(outcomes) is True+ out = capsys.readouterr().out+ assert f"sudo systemctl restart {UNIT}" in out and "hermes-serve.service" not in out