The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): repair interrupted update fleet restart
Cursor Agent8246c4f92ad5
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex b5774fa13fd..778181c2eb4 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -5053,11 +5053,13 @@ _LAZY_COMMAND_EXPORTS = {"hermes_cli.update_cmd": ("_abort_dependency_sync_if_self_locked","_add_upstream_remote",+ "_apply_pending_fleet_restart_catchup","_atomic_replace_dir","_capture_active_lazy_features","_capture_active_tool_dependencies","_capture_head_sha","_classify_concurrent_instance",+ "_clear_fleet_restart_pending_marker","_assess_parked_branch_switch","_branch_head_label","_branch_head_suffix",@@ -5078,6 +5080,7 @@ _LAZY_COMMAND_EXPORTS = {"_ensure_uv_for_termux","_finish_dashboard_update_cleanup","_fleet_probe_expected_runtimes",+ "_fleet_restart_pending_marker_path","_filter_non_gateway_concurrent_instances","_for_each_systemd_gateway_unit","_format_concurrent_instances_message",@@ -5107,6 +5110,7 @@ _LAZY_COMMAND_EXPORTS = {"_npm_manifest_paths","_npm_manifests_digest","_orphaned_desktop_backend_pids",+ "_pending_fleet_restart_needed","_pause_windows_gateways_for_update","_print_curator_first_run_notice","_print_curator_recent_run_notice",@@ -5128,6 +5132,7 @@ _LAZY_COMMAND_EXPORTS = {"_restore_active_tool_dependencies","_restore_stashed_changes","_resume_windows_gateways_after_update",+ "_run_pending_fleet_restart","_run_logged_subprocess","_run_pre_update_backup","_service_unit_supports_graceful_sigusr1_restart",@@ -5148,8 +5153,10 @@ _LAZY_COMMAND_EXPORTS = {"_wait_for_windows_update_gateway_exit","_warn_gateway_restart_phase_aborted","_warn_incomplete_gateway_fleet_restart",+ "_warn_pending_fleet_restart_on_startup","_web_build_toolchain_ready","_web_toolchain_roots",+ "_write_fleet_restart_pending_marker","_write_lazy_refresh_incomplete_marker","_write_marker_file","_write_update_incomplete_marker",@@ -13130,6 +13137,15 @@ def main():except Exception:pass+ # Cheap hint only (#95294): an interrupted update that pulled code but+ # never restarted the fleet. Do NOT restart here — that is ``hermes+ # update`` catch-up work. Skip when the user is already running update.+ try:+ if "update" not in sys.argv[1:]:+ _warn_pending_fleet_restart_on_startup()+ except Exception:+ pass+if _try_termux_fast_tui_launch():returnif _try_termux_fast_cli_launch():diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex a83bd8cc5a6..1b2633d0ba7 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -2834,6 +2834,309 @@ def _write_lazy_refresh_incomplete_marker() -> None:"""Drop the interrupted lazy-refresh breadcrumb. Never raises."""_write_marker_file(_m()._lazy_refresh_marker_path(), label="lazy-refresh-incomplete")++# ``fleet_restart_pending`` lives under HERMES_HOME (not next to the venv).+# The existing ``.update-incomplete`` / ``.lazy-refresh-incomplete`` markers+# gate dependency/venv repair; this one is the fleet-restart obligation after+# a git pull that advanced HEAD (#95294). Cleared only when the restart phase+# completes or there were no running services to restart.+_FLEET_RESTART_PENDING_NAME = "fleet_restart_pending"+++def _fleet_restart_pending_marker_path() -> Path:+ """HERMES_HOME breadcrumb for a pull that has not yet restarted the fleet."""+ return get_hermes_home() / _FLEET_RESTART_PENDING_NAME+++def _write_fleet_restart_pending_marker(*, expected_sha: str = "") -> None:+ """Drop the pull→restart obligation breadcrumb. Never raises."""+ path = _fleet_restart_pending_marker_path()+ if _m()._pytest_owns_live_checkout(path.parent):+ logger.debug("Skipping fleet-restart-pending marker under pytest (live checkout)")+ return+ try:+ lines = [f"started={_time.time()}", f"pid={os.getpid()}"]+ if expected_sha:+ lines.append(f"expected_sha={expected_sha}")+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")+ except OSError as exc:+ logger.debug("Could not write fleet-restart-pending marker: %s", exc)+++def _clear_fleet_restart_pending_marker() -> None:+ """Remove the pull→restart obligation breadcrumb. Never raises."""+ _m()._clear_marker_file(+ _fleet_restart_pending_marker_path(), label="fleet-restart-pending"+ )+++def _current_checkout_sha() -> str | None:+ """Current on-disk checkout HEAD, or None if it cannot be resolved."""+ try:+ from hermes_cli.build_info import get_code_identity++ sha = (get_code_identity(refresh=True) or {}).get("sha")+ return str(sha) if sha else None+ except Exception:+ return _capture_head_sha(["git"], _m().PROJECT_ROOT)+++def _receipt_looks_unfinished(receipt: dict) -> bool:+ """True when *receipt* is from an update that did not finish cleanly."""+ if receipt.get("stop_reason"):+ return True+ exit_code = receipt.get("exit_code")+ if exit_code not in (0, None):+ return True+ outcome = receipt.get("outcome")+ if outcome in ("failed", "partial", "running"):+ return True+ gateway_restart = receipt.get("gateway_restart")+ if isinstance(gateway_restart, dict) and gateway_restart.get("incomplete"):+ return True+ return False+++def _receipt_reports_stale_runtime(expected_sha: str | None = None) -> bool:+ """True when ``update_receipts/latest.json`` records a runtime SHA skew.++ ``plan.runtimes[].code_sha`` is captured *before* the pull of that run,+ so a successful update's receipt always shows pre-update runtime SHAs.+ Those must not retrigger a restart on the next invocation. Use the+ post-restart ``fleet`` matrix when present; fall back to the plan only+ for an unfinished receipt (interrupt / failed / incomplete restart) —+ the #95294 smoking-gun shape.+ """+ try:+ from hermes_cli.update_receipt import read_latest_receipt++ receipt = read_latest_receipt()+ except Exception:+ receipt = None+ if not isinstance(receipt, dict):+ return False+ if not expected_sha:+ expected_sha = _current_checkout_sha()+ if not expected_sha:+ return False++ def _sha_mismatch(code_sha) -> bool:+ return bool(code_sha) and str(code_sha) != str(expected_sha)++ fleet = receipt.get("fleet")+ if isinstance(fleet, list) and fleet:+ for entry in fleet:+ if not isinstance(entry, dict):+ continue+ if entry.get("state") == "stale":+ return True+ if _sha_mismatch(entry.get("code_sha")):+ return True+ return False++ if not _receipt_looks_unfinished(receipt):+ return False+ plan = receipt.get("plan")+ if not isinstance(plan, dict):+ return False+ for runtime in plan.get("runtimes") or []:+ if isinstance(runtime, dict) and _sha_mismatch(runtime.get("code_sha")):+ return True+ return False+++def _pending_fleet_restart_needed() -> bool:+ """True when a prior pull still owes the fleet a restart (#95294)."""+ try:+ if _fleet_restart_pending_marker_path().is_file():+ return True+ except OSError:+ pass+ return _receipt_reports_stale_runtime()+++def _warn_pending_fleet_restart(*, startup: bool = False) -> None:+ """Print the specific interrupted-update fleet-restart warning."""+ stream = sys.stderr if startup else sys.stdout+ print(+ "⚠ A previous `hermes update` pulled new code but did not "+ "restart running gateways.",+ file=stream,+ )+ print(+ " Gateways may still be serving pre-update modules (mixed sys.modules).",+ file=stream,+ )+ if startup:+ print(+ " Run `hermes update` or `hermes gateway restart`.",+ file=stream,+ )+++def _warn_pending_fleet_restart_on_startup() -> None:+ """Cheap CLI-startup hint. Never restarts; never raises."""+ try:+ if not _pending_fleet_restart_needed():+ return+ _warn_pending_fleet_restart(startup=True)+ except Exception:+ pass+++def _restart_systemd_gateway_units_best_effort(failed: list) -> None:+ """Best-effort ``systemctl restart`` of every hermes-gateway/serve unit."""+ for scope, scope_cmd in (+ ("user", ["systemctl", "--user"]),+ ("system", ["systemctl"]),+ ):+ try:+ result = subprocess.run(+ scope_cmd+ + [+ "list-units",+ "hermes-gateway*",+ "hermes-serve*",+ "--plain",+ "--no-legend",+ "--no-pager",+ ],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=10,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired):+ continue+ if result.returncode != 0:+ continue++ def process_unit(svc_name: str, _scope=scope, _cmd=scope_cmd) -> None:+ restart_cmd = list(_cmd) + ["--no-ask-password", "restart", svc_name]+ if (+ _scope == "system"+ and hasattr(os, "geteuid")+ and os.geteuid() != 0 # windows-footgun: ok — systemd path, Linux-only+ ):+ restart_cmd = ["sudo", "-n"] + restart_cmd+ subprocess.run(+ restart_cmd,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=30,+ )++ def on_timeout(svc_name: str, exc: subprocess.TimeoutExpired) -> None:+ failed.append(svc_name)++ _for_each_systemd_gateway_unit(+ result.stdout,+ process_unit=process_unit,+ on_unit_timeout=on_timeout,+ )+++def _run_pending_fleet_restart() -> bool:+ """Catch-up restart for gateways left on pre-update code (#95294).++ Returns True when restart completed or no services were running.+ Returns False if restart was incomplete. Never raises.+ """+ print("→ Restarting gateways left on pre-update code...")+ try:+ _m()._purge_stale_hermes_modules()+ except Exception:+ pass+ try:+ from hermes_cli.gateway import (+ find_gateway_pids,+ is_macos,+ is_windows,+ kill_gateway_processes,+ supports_systemd_services,+ _wait_for_gateway_exit,+ )+ except Exception as exc:+ _warn_gateway_restart_phase_aborted(exc, None)+ return False++ try:+ pids = list(find_gateway_pids(all_profiles=True))+ except Exception as exc:+ logger.debug("Pending fleet restart: gateway probe failed: %s", exc)+ pids = None++ if pids == []:+ print(" ✓ No running gateways — nothing to restart.")+ return True++ failed: list = []+ try:+ if supports_systemd_services():+ _restart_systemd_gateway_units_best_effort(failed)+ if is_macos():+ restarted: list = []+ try:+ _restart_macos_launchd_gateways(restarted, failed, 45.0)+ except Exception as exc:+ logger.debug("Pending fleet restart: launchd failed: %s", exc)+ failed.append("launchd")+ if is_windows():+ try:+ from hermes_cli import gateway_windows++ if gateway_windows.is_installed():+ gateway_windows.restart()+ except Exception as exc:+ logger.debug("Pending fleet restart: Windows failed: %s", exc)+ failed.append("windows-gateway")+ leftover: list = []+ try:+ leftover = list(find_gateway_pids(all_profiles=True))+ except Exception:+ leftover = list(pids or [])+ if leftover:+ try:+ kill_gateway_processes(all_profiles=True)+ _wait_for_gateway_exit(timeout=5.0, force_after=None)+ except Exception as exc:+ logger.debug("Pending fleet restart: PID stop failed: %s", exc)+ if failed:+ _warn_incomplete_gateway_fleet_restart(failed)+ return False+ print(" ✓ Pending fleet restart completed.")+ return True+ except Exception as exc:+ surviving = None+ try:+ surviving = list(find_gateway_pids(all_profiles=True))+ except Exception:+ surviving = pids+ _warn_gateway_restart_phase_aborted(exc, surviving)+ return False+++def _apply_pending_fleet_restart_catchup() -> None:+ """On an already-up-to-date ``hermes update``, finish a skipped restart.++ No-op when nothing is pending. Exits 1 when the catch-up restart is+ incomplete so automation does not treat the fleet as healthy.+ """+ if not _pending_fleet_restart_needed():+ return+ print()+ _warn_pending_fleet_restart()+ print("→ Running the pending fleet restart...")+ if _run_pending_fleet_restart():+ _clear_fleet_restart_pending_marker()+ return+ print(" ⚠ Fleet restart incomplete. Recover with: hermes gateway restart")+ sys.exit(1)++def _format_concurrent_instances_message(matches: list[tuple[int, str]], scripts_dir: Path) -> str:@@ -7664,6 +7967,11 @@ def _cmd_update_impl(args, gateway_mode: bool):)print(" Restart each of them to pick up the repaired runtime.")_m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ # Git is current, but a prior pull may still owe the fleet a+ # restart (#95294). Catch up even on the "Already up to date"+ # path — that early return is what left the gateway on stale+ # code for two days.+ _apply_pending_fleet_restart_catchup()returnif commit_count > 0:@@ -7904,6 +8212,13 @@ def _cmd_update_impl(args, gateway_mode: bool):_m()._resume_windows_gateways_after_update(_windows_gateway_resume)sys.exit(1)+ # #95294: HEAD advanced; running gateways still serve pre-pull+ # modules until the restart phase below. Any interrupt between here+ # and a completed (or no-op) restart leaves this marker so the next+ # ``hermes update`` can catch up even when git is already up to date.+ # Distinct from ``.update-incomplete`` (venv/install repair).+ _write_fleet_restart_pending_marker(expected_sha=post_pull_sha or "")+# Clear stale .pyc bytecode cache — prevents ImportError on gateway# restart when updated source references names that didn't exist in# the old bytecode (e.g. get_hermes_home added to hermes_constants).@@ -9569,7 +9884,10 @@ def _cmd_update_impl(args, gateway_mode: bool):# Code update itself succeeded, but at least one gateway still# runs pre-update modules — surface that as a failed update so# automation / operators do not treat the fleet as healthy.+ # Leave ``fleet_restart_pending`` in place so the next+ # ``hermes update`` still runs the catch-up restart.sys.exit(1)+ _clear_fleet_restart_pending_marker()except _shim_quarantine_error_type() as e:# Fail-closed shim contention (#87331): strict quarantine refuseddiff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.pynew file mode 100644index 00000000000..f8390047a25--- /dev/null+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py@@ -0,0 +1,424 @@+"""Interrupted-update fleet-restart obligation (#95294 parts 1+2).++A ``hermes update`` killed after git pull advanced HEAD but before the+fleet restart left running gateways on stale code. The next update said+"Already up to date" and skipped restart. These tests cover:++- ``fleet_restart_pending`` marker written after HEAD advances, cleared+ after a successful (or no-op) fleet restart+- interrupt between pull and restart leaves the marker+- next ``hermes update`` with git already up to date still runs the+ pending restart when the marker OR a skewed unfinished latest.json is+ present++No live gateway, no network. Git and restart are mocked.+"""++from __future__ import annotations++import json+from types import SimpleNamespace++import pytest++from hermes_cli import main as hermes_main+from hermes_cli import update_cmd+from hermes_constants import get_hermes_home+++def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):+ """Simulate git commands where HEAD advances from pre_sha to post_sha."""+ calls = {"n": 0}++ def side_effect(cmd, **kwargs):+ joined = " ".join(str(c) for c in cmd)++ if "rev-parse" in joined and "--abbrev-ref" in joined:+ return SimpleNamespace(returncode=0, stdout="main\n", stderr="")++ if "rev-list" in joined:+ return SimpleNamespace(returncode=0, stdout="3\n", stderr="")++ if joined.endswith("rev-parse HEAD"):+ if calls["n"] == 0:+ calls["n"] += 1+ return SimpleNamespace(returncode=0, stdout=f"{pre_sha}\n", stderr="")+ return SimpleNamespace(returncode=0, stdout=f"{post_sha}\n", stderr="")++ return SimpleNamespace(returncode=0, stdout="", stderr="")++ return side_effect+++def _make_up_to_date_side_effect(sha="abc123"):+ """Simulate git commands where origin is already at HEAD."""++ def side_effect(cmd, **kwargs):+ joined = " ".join(str(c) for c in cmd)++ if "rev-parse" in joined and "--abbrev-ref" in joined:+ return SimpleNamespace(returncode=0, stdout="main\n", stderr="")++ if "rev-list" in joined:+ return SimpleNamespace(returncode=0, stdout="0\n", stderr="")++ if joined.endswith("rev-parse HEAD"):+ return SimpleNamespace(returncode=0, stdout=f"{sha}\n", stderr="")++ return SimpleNamespace(returncode=0, stdout="", stderr="")++ return side_effect+++def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):+ """Patch ``_cmd_update_impl`` helpers. Mirrors test_update_head_moved_gate."""+ monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect)+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)+ (tmp_path / ".git").mkdir()+ monkeypatch.setattr(hermes_main, "_resolve_update_branch", lambda args: "main")+ monkeypatch.setattr(hermes_main, "_is_windows", lambda: False)+ monkeypatch.setattr(+ hermes_main,+ "_get_origin_url",+ lambda *a, **k: "https://github.com/NousResearch/hermes-agent.git",+ )+ monkeypatch.setattr(hermes_main, "_is_fork", lambda *a, **k: False)+ monkeypatch.setattr(+ hermes_main, "_stash_local_changes_if_needed", lambda *a, **k: None+ )+ monkeypatch.setattr(hermes_main, "_clear_bytecode_cache", lambda *a, **k: 0)+ monkeypatch.setattr(+ hermes_main, "_record_bytecode_fingerprint", lambda *a, **k: None+ )+ monkeypatch.setattr(hermes_main, "_run_pre_update_backup", lambda *a, **k: None)+ monkeypatch.setattr(+ hermes_main, "_pause_windows_gateways_for_update", lambda: None+ )+ monkeypatch.setattr(+ hermes_main, "_resume_windows_gateways_after_update", lambda *a, **k: None+ )+ monkeypatch.setattr(hermes_main, "_write_update_incomplete_marker", lambda: None)+ monkeypatch.setattr(hermes_main, "_clear_update_incomplete_marker", lambda: None)+ monkeypatch.setattr(+ hermes_main, "_finish_dashboard_update_cleanup", lambda *a, **k: None+ )+ monkeypatch.setattr(hermes_main, "_build_web_ui", lambda *a, **k: None)+ monkeypatch.setattr(+ update_cmd, "_venv_core_imports_healthy", lambda: (True, "")+ )+ monkeypatch.setattr(update_cmd, "_update_node_dependencies", lambda: [])++ import hermes_cli.gateway as hermes_gateway++ monkeypatch.setattr(+ hermes_gateway, "find_gateway_pids", lambda all_profiles=False: []+ )+ monkeypatch.setattr(hermes_gateway, "supports_systemd_services", lambda: False)+ monkeypatch.setattr(+ hermes_gateway, "find_profile_gateway_processes", lambda *a, **k: []+ )+ monkeypatch.setattr(+ "hermes_cli.update_receipt.collect_fleet_versions",+ lambda **k: [],+ )+ monkeypatch.setattr(+ "hermes_cli.update_inventory.collect_runtime_inventory",+ lambda: SimpleNamespace(runtimes=[], to_dict=lambda: {}),+ )+++def _update_args():+ return SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)+++# ---------------------------------------------------------------------------+# Marker helpers+# ---------------------------------------------------------------------------+++def test_marker_round_trip_under_hermes_home():+ path = update_cmd._fleet_restart_pending_marker_path()+ assert path.parent == get_hermes_home()+ assert path.name == "fleet_restart_pending"+ assert not path.exists()++ update_cmd._write_fleet_restart_pending_marker(expected_sha="abc123")+ assert path.is_file()+ body = path.read_text(encoding="utf-8")+ assert "started=" in body+ assert "pid=" in body+ assert "expected_sha=abc123" in body++ update_cmd._clear_fleet_restart_pending_marker()+ assert not path.exists()+++def test_pending_needed_when_marker_exists():+ update_cmd._write_fleet_restart_pending_marker()+ assert update_cmd._pending_fleet_restart_needed() is True+ update_cmd._clear_fleet_restart_pending_marker()+ assert update_cmd._pending_fleet_restart_needed() is False+++def test_pending_needed_when_unfinished_receipt_runtime_sha_skews(monkeypatch):+ disk_sha = "e" * 40+ old_sha = "7" * 40+ monkeypatch.setattr(update_cmd, "_current_checkout_sha", lambda: disk_sha)++ receipt_dir = get_hermes_home() / "logs" / "update_receipts"+ receipt_dir.mkdir(parents=True)+ (receipt_dir / "latest.json").write_text(+ json.dumps(+ {+ "exit_code": 1,+ "stop_reason": "KeyboardInterrupt: ",+ "outcome": "failed",+ "plan": {+ "expected_sha": disk_sha,+ "runtimes": [+ {+ "kind": "gateway",+ "profile": "default",+ "pid": 2111768,+ "supervisor": "systemd",+ "code_sha": old_sha,+ "restart_via": "systemd",+ }+ ],+ },+ }+ ),+ encoding="utf-8",+ )++ assert update_cmd._pending_fleet_restart_needed() is True+++def test_successful_receipt_with_pre_update_plan_shas_does_not_retrigger(+ monkeypatch,+):+ """A completed update's plan.runtimes are pre-pull SHAs — not a catch-up."""+ disk_sha = "n" * 40+ old_sha = "o" * 40+ monkeypatch.setattr(update_cmd, "_current_checkout_sha", lambda: disk_sha)++ receipt_dir = get_hermes_home() / "logs" / "update_receipts"+ receipt_dir.mkdir(parents=True)+ (receipt_dir / "latest.json").write_text(+ json.dumps(+ {+ "exit_code": 0,+ "outcome": "success",+ "plan": {+ "expected_sha": old_sha,+ "runtimes": [+ {+ "kind": "gateway",+ "profile": "default",+ "pid": 1,+ "code_sha": old_sha,+ }+ ],+ },+ "fleet": [+ {+ "profile": "default",+ "pid": 2,+ "code_sha": disk_sha,+ "state": "current",+ }+ ],+ "gateway_restart": {"incomplete": False},+ }+ ),+ encoding="utf-8",+ )++ assert update_cmd._pending_fleet_restart_needed() is False+++def test_stale_fleet_matrix_on_latest_receipt_is_pending(monkeypatch):+ disk_sha = "n" * 40+ monkeypatch.setattr(update_cmd, "_current_checkout_sha", lambda: disk_sha)++ receipt_dir = get_hermes_home() / "logs" / "update_receipts"+ receipt_dir.mkdir(parents=True)+ (receipt_dir / "latest.json").write_text(+ json.dumps(+ {+ "outcome": "partial",+ "exit_code": 1,+ "fleet": [+ {+ "profile": "default",+ "pid": 9,+ "code_sha": "s" * 40,+ "state": "stale",+ }+ ],+ }+ ),+ encoding="utf-8",+ )++ assert update_cmd._pending_fleet_restart_needed() is True+++def test_run_pending_restart_true_when_no_gateways(monkeypatch, capsys):+ monkeypatch.setattr(+ "hermes_cli.gateway.find_gateway_pids", lambda **k: []+ )+ monkeypatch.setattr(hermes_main, "_purge_stale_hermes_modules", lambda: None)++ assert update_cmd._run_pending_fleet_restart() is True+ assert "nothing to restart" in capsys.readouterr().out+++# ---------------------------------------------------------------------------+# cmd_update integration (mocked git / restart)+# ---------------------------------------------------------------------------+++def test_marker_written_after_pull_cleared_after_successful_restart(+ monkeypatch, tmp_path, capsys+):+ args = _update_args()+ _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())++ wrote = []+ orig = update_cmd._write_fleet_restart_pending_marker++ def _spy(*, expected_sha=""):+ orig(expected_sha=expected_sha)+ wrote.append(update_cmd._fleet_restart_pending_marker_path().is_file())++ monkeypatch.setattr(update_cmd, "_write_fleet_restart_pending_marker", _spy)++ hermes_main.cmd_update(args)++ assert wrote == [True], "marker must exist immediately after HEAD advances"+ assert not update_cmd._fleet_restart_pending_marker_path().exists()+ out = capsys.readouterr().out+ assert "✓ Code updated!" in out+++def test_interrupt_between_pull_and_restart_leaves_marker(+ monkeypatch, tmp_path+):+ args = _update_args()+ _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())++ def _interrupt(*_a, **_k):+ raise KeyboardInterrupt()++ monkeypatch.setattr(hermes_main, "_clear_bytecode_cache", _interrupt)++ with pytest.raises(KeyboardInterrupt):+ hermes_main.cmd_update(args)++ marker = update_cmd._fleet_restart_pending_marker_path()+ assert marker.is_file()+ assert "expected_sha=def456" in marker.read_text(encoding="utf-8")+++def test_already_up_to_date_runs_pending_restart_when_marker_present(+ monkeypatch, tmp_path, capsys+):+ args = _update_args()+ _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())+ update_cmd._write_fleet_restart_pending_marker(expected_sha="def456")++ seen = {"ran": False}++ def _restart():+ seen["ran"] = True+ return True++ monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", _restart)++ hermes_main.cmd_update(args)++ assert seen["ran"] is True+ assert not update_cmd._fleet_restart_pending_marker_path().exists()+ out = capsys.readouterr().out+ assert "did not restart running gateways" in out+++def test_already_up_to_date_runs_pending_restart_when_receipt_skewed(+ monkeypatch, tmp_path, capsys+):+ args = _update_args()+ _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())++ disk_sha = "e" * 40+ monkeypatch.setattr(update_cmd, "_current_checkout_sha", lambda: disk_sha)+ receipt_dir = get_hermes_home() / "logs" / "update_receipts"+ receipt_dir.mkdir(parents=True)+ (receipt_dir / "latest.json").write_text(+ json.dumps(+ {+ "exit_code": 1,+ "stop_reason": "KeyboardInterrupt: ",+ "outcome": "failed",+ "plan": {+ "expected_sha": disk_sha,+ "runtimes": [+ {+ "kind": "gateway",+ "profile": "default",+ "pid": 42,+ "code_sha": "7" * 40,+ }+ ],+ },+ }+ ),+ encoding="utf-8",+ )++ seen = {"ran": False}+ monkeypatch.setattr(+ update_cmd,+ "_run_pending_fleet_restart",+ lambda: seen.__setitem__("ran", True) or True,+ )++ hermes_main.cmd_update(args)++ assert seen["ran"] is True+ out = capsys.readouterr().out+ assert "did not restart running gateways" in out+++def test_already_up_to_date_skips_restart_when_nothing_pending(+ monkeypatch, tmp_path, capsys+):+ args = _update_args()+ _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())++ seen = {"ran": False}+ monkeypatch.setattr(+ update_cmd,+ "_run_pending_fleet_restart",+ lambda: seen.__setitem__("ran", True) or True,+ )++ hermes_main.cmd_update(args)++ assert seen["ran"] is False+ assert "did not restart running gateways" not in capsys.readouterr().out+++def test_startup_warn_prints_when_marker_present(capsys):+ update_cmd._write_fleet_restart_pending_marker()+ update_cmd._warn_pending_fleet_restart_on_startup()+ err = capsys.readouterr().err+ assert "did not restart running gateways" in err+ assert "hermes gateway restart" in err+++def test_startup_warn_silent_when_nothing_pending(capsys):+ update_cmd._warn_pending_fleet_restart_on_startup()+ captured = capsys.readouterr()+ assert captured.err == ""+ assert captured.out == ""