Skip to content

The agent that grows with you

feat(update): the plan is now the restart worklist — every planned runtime must be accounted for (#91277 Phase 2)

Teknium18b7fc82b66f
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index b470a9a1e10..43c845ef705 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -5744,6 +5744,10 @@ def _cmd_update_impl(args, gateway_mode: bool):
# running Hermes runtime, its supervisor, and its running code version —
# into the receipt, so a post-mortem can compare what the update SAW
# against what it did. Read-only; a probe failure records nothing.
+ # ``_pre_update_plan`` is read again AFTER the restart phase to reconcile
+ # every planned runtime against the phase's bookkeeping (restart via
+ # declared mechanism — the plan is the worklist, not just a printout).
+ _pre_update_plan = None
try:
from hermes_cli.update_inventory import (
collect_runtime_inventory,
@@ -8235,6 +8239,40 @@ def _cmd_update_impl(args, gateway_mode: bool):
except Exception as _fleet_exc:
logger.debug("Fleet version verification failed: %s", _fleet_exc)
+ # Plan-vs-execution reconciliation (#91277 Phase 2, restart via
+ # declared mechanism): every runtime the PLAN saw must be accounted
+ # for by the restart phase's bookkeeping. An unaccounted runtime is
+ # the silent-miss class (a platform branch re-discovered its own
+ # targets and skipped one the inventory knew about) — escalate it
+ # exactly like a STALE/DOWN fleet row.
+ _runtime_outcomes: list = []
+ try:
+ if _pre_update_plan is not None and _pre_update_plan.runtimes:
+ from hermes_cli.update_inventory import (
+ match_runtime_outcomes,
+ report_unaccounted_runtimes,
+ )
+
+ _runtime_outcomes = match_runtime_outcomes(
+ _pre_update_plan,
+ restarted_services=restarted_services,
+ relaunched_profiles=relaunched_profiles,
+ externally_supervised_profiles=externally_supervised_profiles,
+ killed_pids=killed_pids,
+ failed_units=failed_or_stale_units,
+ )
+ if report_unaccounted_runtimes(_runtime_outcomes):
+ gateway_fleet_restart_incomplete = True
+ try:
+ import hermes_cli.update_receipt as _ur
+
+ if _ur._current is not None:
+ _ur._current.data["runtime_outcomes"] = _runtime_outcomes
+ except Exception:
+ pass
+ except Exception as _outcome_exc:
+ logger.debug("Runtime-outcome reconciliation failed: %s", _outcome_exc)
+
try:
from hermes_cli.update_receipt import finalize_update_receipt
diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.py
index f978bfbf3de..c9e2bdc6d2e 100644
--- a/hermes_cli/update_inventory.py
+++ b/hermes_cli/update_inventory.py
@@ -95,11 +95,30 @@ def _detect_supervisor_for_pid(pid: int, service_pids: set) -> str:
def _restart_mechanism(supervisor: str, profile: str) -> str:
+ """Machine-readable restart mechanism id for a runtime.
+
+ THE policy table (#91277 Phase 2): restart execution consumes these ids
+ via :func:`match_runtime_outcomes` / the update's restart phase, and the
+ receipt records per-runtime outcomes against them. Display strings are
+ derived by :func:`describe_restart_mechanism` — never the other way
+ around.
+ """
if supervisor == "systemd":
- return "systemctl restart (drain-first SIGUSR1 when supported)"
+ return "systemd"
if supervisor == "launchd":
- return "launchctl kickstart -k (drain-first, per-label domain)"
+ return "launchd"
if supervisor == "desktop":
+ return "desktop"
+ return "manual"
+
+
+def describe_restart_mechanism(mechanism: str, profile: str) -> str:
+ """Human-readable description of a restart mechanism id."""
+ if mechanism == "systemd":
+ return "systemctl restart (drain-first SIGUSR1 when supported)"
+ if mechanism == "launchd":
+ return "launchctl kickstart -k (drain-first, per-label domain)"
+ if mechanism == "desktop":
return "Desktop app respawns its serve backend"
if profile != "default":
return f"hermes -p {profile} gateway restart"
@@ -301,7 +320,101 @@ def print_update_plan(plan: UpdatePlan) -> None:
f" • {runtime.kind} [{runtime.profile}] pid {runtime.pid}"
f" — {runtime.supervisor}{sha}"
)
- print(f" restart: {runtime.restart_via}")
+ print(
+ " restart: "
+ f"{describe_restart_mechanism(runtime.restart_via, runtime.profile)}"
+ )
+
+
+def match_runtime_outcomes(
+ plan: "UpdatePlan",
+ *,
+ restarted_services: list,
+ relaunched_profiles: list,
+ externally_supervised_profiles: list,
+ killed_pids: set,
+ failed_units: list,
+) -> list[dict[str, Any]]:
+ """Reconcile the plan's runtimes against what the restart phase DID.
+
+ #91277 Phase 2 (restart via declared mechanism): the platform restart
+ branches each re-discover their own targets, so a runtime the plan saw
+ can be missed entirely with no signal. This cross-checks every planned
+ runtime against the phase's bookkeeping and returns one outcome row per
+ runtime::
+
+ {"kind", "profile", "pid", "mechanism", "outcome"}
+
+ outcome: ``restarted`` (service restarted / profile relaunched /
+ handed to external supervisor), ``stopped`` (pid killed, watcher or
+ operator relaunches), ``failed`` (in the phase's failed/stale list) or
+ ``unaccounted`` — the plan saw it and NO bookkeeping mentions it: the
+ blind-spot tripwire (same philosophy as the fleet matrix's DOWN row).
+ Never raises; on any probe error returns what it has.
+ """
+ outcomes: list[dict[str, Any]] = []
+ try:
+ failed_set = {str(u) for u in (failed_units or [])}
+ restarted_set = {str(s) for s in (restarted_services or [])}
+ relaunched = set(relaunched_profiles or [])
+ external = set(externally_supervised_profiles or [])
+ killed = {int(p) for p in (killed_pids or set())}
+
+ for runtime in plan.runtimes:
+ r = runtime if isinstance(runtime, RuntimeRecord) else None
+ if r is None:
+ continue
+ outcome = "unaccounted"
+ if r.profile in relaunched or r.profile in external:
+ outcome = "restarted"
+ elif r.pid is not None and r.pid in killed:
+ outcome = "stopped"
+ elif any(
+ r.profile in unit or (r.profile == "default" and "hermes-gateway" in unit)
+ for unit in failed_set
+ ):
+ outcome = "failed"
+ elif any(
+ r.profile in svc or (r.profile == "default" and "hermes-gateway" in svc)
+ for svc in restarted_set
+ ):
+ outcome = "restarted"
+ outcomes.append(
+ {
+ "kind": r.kind,
+ "profile": r.profile,
+ "pid": r.pid,
+ "mechanism": r.restart_via,
+ "outcome": outcome,
+ }
+ )
+ except Exception as exc:
+ logger.debug("Runtime-outcome reconciliation failed: %s", exc)
+ return outcomes
+
+
+def report_unaccounted_runtimes(outcomes: list[dict[str, Any]]) -> bool:
+ """Print a loud warning for runtimes the restart phase never touched.
+
+ Returns True when at least one planned runtime is unaccounted — the
+ caller escalates exactly like a STALE/DOWN fleet row (exit 1): a runtime
+ the plan promised to restart, silently missed, is the class this phase
+ exists to kill.
+ """
+ missed = [o for o in outcomes if o.get("outcome") == "unaccounted"]
+ if not missed:
+ return False
+ print()
+ print(" ⚠ Planned runtimes the restart phase never touched:")
+ for o in missed:
+ print(
+ f" ✗ {o['kind']} [{o['profile']}] pid {o['pid']}"
+ f" — planned mechanism: {o['mechanism']}"
+ )
+ print(" Restart them manually, then verify:")
+ print(" hermes gateway restart # active profile")
+ print(" hermes -p <profile> gateway restart # named profile")
+ return True
def record_plan_in_receipt(plan: UpdatePlan) -> None:
diff --git a/tests/hermes_cli/test_restart_plan_reconciliation.py b/tests/hermes_cli/test_restart_plan_reconciliation.py
new file mode 100644
index 00000000000..7c0ecfb1fdf
--- /dev/null
+++ b/tests/hermes_cli/test_restart_plan_reconciliation.py
@@ -0,0 +1,137 @@
+"""Plan-vs-execution reconciliation (#91277 Phase 2: restart via declared mechanism).
+
+Pins:
+- _restart_mechanism returns machine-readable ids; describe_restart_mechanism
+ derives display strings (policy table is data, not prose).
+- match_runtime_outcomes classifies every planned runtime against the restart
+ phase's bookkeeping: restarted / stopped / failed / unaccounted.
+- report_unaccounted_runtimes escalates (returns True) ONLY on unaccounted
+ rows — the silent-miss tripwire.
+"""
+
+from hermes_cli.update_inventory import (
+ RuntimeRecord,
+ UpdatePlan,
+ _restart_mechanism,
+ describe_restart_mechanism,
+ match_runtime_outcomes,
+ report_unaccounted_runtimes,
+)
+
+
+def _plan(*runtimes: RuntimeRecord) -> UpdatePlan:
+ plan = UpdatePlan()
+ plan.runtimes = list(runtimes)
+ return plan
+
+
+def _rt(profile: str, pid: int, supervisor: str = "manual") -> RuntimeRecord:
+ return RuntimeRecord(
+ kind="gateway",
+ profile=profile,
+ pid=pid,
+ supervisor=supervisor,
+ restart_via=_restart_mechanism(supervisor, profile),
+ )
+
+
+def test_mechanism_ids_are_machine_readable_and_described():
+ assert _restart_mechanism("systemd", "default") == "systemd"
+ assert _restart_mechanism("launchd", "work") == "launchd"
+ assert _restart_mechanism("desktop", "default") == "desktop"
+ assert _restart_mechanism("manual", "work") == "manual"
+ # display derives FROM the id
+ assert "systemctl" in describe_restart_mechanism("systemd", "default")
+ assert "kickstart" in describe_restart_mechanism("launchd", "work")
+ assert "-p work" in describe_restart_mechanism("manual", "work")
+ assert describe_restart_mechanism("manual", "default") == "hermes gateway restart"
+
+
+def test_relaunched_profile_is_restarted():
+ outcomes = match_runtime_outcomes(
+ _plan(_rt("default", 100)),
+ restarted_services=[], relaunched_profiles=["default"],
+ externally_supervised_profiles=[], killed_pids=set(), failed_units=[],
+ )
+ assert outcomes == [
+ {"kind": "gateway", "profile": "default", "pid": 100,
+ "mechanism": "manual", "outcome": "restarted"}
+ ]
+ assert report_unaccounted_runtimes(outcomes) is False
+
+
+def test_killed_pid_is_stopped():
+ outcomes = match_runtime_outcomes(
+ _plan(_rt("work", 200)),
+ restarted_services=[], relaunched_profiles=[],
+ externally_supervised_profiles=[], killed_pids={200}, failed_units=[],
+ )
+ assert outcomes[0]["outcome"] == "stopped"
+
+
+def test_failed_unit_is_failed():
+ outcomes = match_runtime_outcomes(
+ _plan(_rt("work", 300, supervisor="systemd")),
+ restarted_services=[], relaunched_profiles=[],
+ externally_supervised_profiles=[], killed_pids=set(),
+ failed_units=["hermes-gateway-work.service"],
+ )
+ assert outcomes[0]["outcome"] == "failed"
+
+
+def test_restarted_service_unit_matches_profile():
+ outcomes = match_runtime_outcomes(
+ _plan(_rt("default", 400, supervisor="systemd")),
+ restarted_services=["hermes-gateway.service"], relaunched_profiles=[],
+ externally_supervised_profiles=[], killed_pids=set(), failed_units=[],
+ )
+ assert outcomes[0]["outcome"] == "restarted"
+
+
+def test_untouched_runtime_is_unaccounted_and_escalates(capsys):
+ """The tripwire: plan saw it, NO bookkeeping mentions it."""
+ outcomes = match_runtime_outcomes(
+ _plan(_rt("coder", 500)),
+ restarted_services=["hermes-gateway.service"],
+ relaunched_profiles=["default"],
+ externally_supervised_profiles=[], killed_pids={123}, failed_units=[],
+ )
+ assert outcomes[0]["outcome"] == "unaccounted"
+ assert report_unaccounted_runtimes(outcomes) is True
+ out = capsys.readouterr().out
+ assert "never touched" in out
+ assert "coder" in out and "500" in out
+ assert "hermes -p <profile> gateway restart" in out
+
+
+def test_external_supervisor_counts_as_restarted():
+ outcomes = match_runtime_outcomes(
+ _plan(_rt("default", 600, supervisor="desktop")),
+ restarted_services=[], relaunched_profiles=[],
+ externally_supervised_profiles=["default"], killed_pids=set(),
+ failed_units=[],
+ )
+ assert outcomes[0]["outcome"] == "restarted"
+
+
+def test_mixed_fleet_only_the_missed_one_escalates(capsys):
+ outcomes = match_runtime_outcomes(
+ _plan(
+ _rt("default", 700, supervisor="systemd"),
+ _rt("work", 701),
+ _rt("ghost", 702),
+ ),
+ restarted_services=["hermes-gateway.service"],
+ relaunched_profiles=["work"],
+ externally_supervised_profiles=[], killed_pids=set(), failed_units=[],
+ )
+ by_profile = {o["profile"]: o["outcome"] for o in outcomes}
+ assert by_profile == {
+ "default": "restarted", "work": "restarted", "ghost": "unaccounted"
+ }
+ assert report_unaccounted_runtimes(outcomes) is True
+ out = capsys.readouterr().out
+ missed_block = out.split("never touched")[1]
+ assert "ghost" in missed_block
+ assert "[default]" not in missed_block
+ assert "[work]" not in missed_block
diff --git a/tests/hermes_cli/test_update_inventory.py b/tests/hermes_cli/test_update_inventory.py
index ad0929ddc92..6550c0c5afb 100644
--- a/tests/hermes_cli/test_update_inventory.py
+++ b/tests/hermes_cli/test_update_inventory.py
@@ -58,7 +58,12 @@ class TestCollectInventory:
assert by_profile["work"].pid == 200
assert by_profile["work"].supervisor == "manual"
assert by_profile["work"].code_sha is None # pre-stamp gateway
- assert "hermes -p work gateway restart" in by_profile["work"].restart_via
+ assert by_profile["work"].restart_via == "manual"
+ from hermes_cli.update_inventory import describe_restart_mechanism
+
+ assert "hermes -p work gateway restart" in describe_restart_mechanism(
+ by_profile["work"].restart_via, "work"
+ )
def test_docker_install_not_updatable_in_place(self, fleet, monkeypatch):
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda *a, **k: "docker")