The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(update): structured update receipts + post-update fleet version verification
Teknium1d74833d8df3
diff --git a/gateway/status.py b/gateway/status.pyindex d391e278632..1fbbe10a1e2 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -638,6 +638,29 @@ def _build_pid_record() -> dict:}+def _get_code_identity_fields() -> dict[str, Any]:+ """Code identity of THIS gateway process, for fleet version checks.++ Lazy import so ``gateway.status`` keeps no import-time dependency on+ ``hermes_cli``; the helper itself is cached per process. A gateway+ keeps serving the module versions it imported at startup, so stamping+ the identity into ``gateway_state.json`` lets `hermes update` (and the+ dashboard) prove whether a running gateway actually picked up new code+ after the restart phase — instead of assuming it did (#88654, #69754).+ Never raises; degrades to absent fields.+ """+ try:+ from hermes_cli.build_info import get_code_identity++ identity = get_code_identity()+ return {+ "code_sha": identity.get("sha"),+ "code_version": identity.get("version"),+ }+ except Exception:+ return {}++def _build_runtime_status_record() -> dict[str, Any]:payload = _build_pid_record()payload.update({@@ -648,6 +671,7 @@ def _build_runtime_status_record() -> dict[str, Any]:"platforms": {},"updated_at": _utc_now_iso(),})+ payload.update(_get_code_identity_fields())return payload@@ -1075,6 +1099,10 @@ def write_runtime_status(payload["argv"] = current_record["argv"]payload["start_time"] = current_record["start_time"]payload["updated_at"] = _utc_now_iso()+ # Re-stamp code identity on every write: the file can outlive the process+ # that created it, and the top-level record must always describe the+ # CURRENT writer's code (per-process cached, so this is a dict copy).+ payload.update(_get_code_identity_fields())if gateway_state is not _UNSET:payload["gateway_state"] = gateway_statediff --git a/hermes_cli/build_info.py b/hermes_cli/build_info.pyindex e4cc6f09974..03fb7ac4d00 100644--- a/hermes_cli/build_info.py+++ b/hermes_cli/build_info.py@@ -33,6 +33,75 @@ from typing import Optional_BUILD_SHA_FILE = Path(__file__).parent.parent / ".hermes_build_sha"+_code_identity_cache: Optional[dict] = None+++def get_code_identity(refresh: bool = False) -> dict:+ """Return the running checkout's code identity as a dict.++ Shape: ``{"sha": full-or-short sha | None, "short_sha": str | None,+ "version": pyproject version | None, "source": "git" | "build-file" |+ "unknown"}``.++ Resolution order mirrors the banner/dump callsites: live ``git+ rev-parse`` for source installs, the baked ``.hermes_build_sha`` for+ Docker images (no ``.git`` inside the published image), else unknown.++ Cached per process — code identity cannot change while a process is+ running (an updated checkout requires a restart to take effect, which+ is exactly the property the fleet version verification relies on).+ Never raises; every field degrades to ``None`` independently.+ """+ global _code_identity_cache+ if _code_identity_cache is not None and not refresh:+ return dict(_code_identity_cache)++ sha: Optional[str] = None+ source = "unknown"+ project_root = Path(__file__).parent.parent+ try:+ import subprocess++ proc = subprocess.run(+ ["git", "rev-parse", "HEAD"],+ cwd=project_root,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=10,+ )+ candidate = (proc.stdout or "").strip()+ if proc.returncode == 0 and candidate:+ sha = candidate+ source = "git"+ except Exception:+ pass+ if sha is None:+ baked = get_build_sha(short=0)+ if baked:+ sha = baked+ source = "build-file"++ version: Optional[str] = None+ try:+ import tomllib++ with open(project_root / "pyproject.toml", "rb") as fh: # windows-footgun: ok — binary mode, tomllib requires bytes+ raw_version = tomllib.load(fh).get("project", {}).get("version")+ version = str(raw_version) if raw_version else None+ except Exception:+ version = None++ _code_identity_cache = {+ "sha": sha,+ "short_sha": sha[:8] if sha else None,+ "version": version,+ "source": source,+ }+ return dict(_code_identity_cache)++def get_build_sha(short: int = 8) -> Optional[str]:"""Return the baked-in build SHA, truncated to ``short`` chars, or None.diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 1b8c967dd75..4608e3f23f9 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1576,6 +1576,14 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo# Don't stop a working dashboard when the Node refresh failed — see the# git-update path for rationale (#30271)._finish_dashboard_update_cleanup(node_failures)+ try:+ from hermes_cli.update_receipt import finalize_update_receipt++ finalize_update_receipt(+ "success" if (desktop_build_ok and not node_failures) else "partial"+ )+ except Exception as _receipt_exc:+ logger.debug("Update receipt finalize (zip path) failed: %s", _receipt_exc)return desktop_build_okdef _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[str]:@@ -5000,6 +5008,16 @@ def _cmd_update_impl(args, gateway_mode: bool):print("⚕ Updating Hermes Agent...")print()+ # Phase 1 (#91277): structured update receipt — record what this run+ # discovers, does, and skips, so silent-failure classes (#88848,+ # #74973, #85753, #81193) become diagnosable from disk.+ try:+ from hermes_cli.update_receipt import begin_update_receipt++ begin_update_receipt()+ except Exception as _receipt_exc:+ logger.debug("Update receipt unavailable: %s", _receipt_exc)+# On Windows, abort early if another hermes.exe is holding the venv shim# open. Continuing would result in a string of WinError 32 warnings and# then either a deferred-rename leftover or a failed git-pull fast path@@ -5017,6 +5035,16 @@ def _cmd_update_impl(args, gateway_mode: bool):# Returns the quick-snapshot id (or None when disabled/failed); the# post-update cron-jobs safety net uses it to detect job loss.pre_update_snapshot_id = _m()._run_pre_update_backup(args)+ try:+ from hermes_cli.update_receipt import record_step++ record_step(+ "pre_update_backup",+ pre_update_snapshot_id is not None,+ f"snapshot={pre_update_snapshot_id}" if pre_update_snapshot_id else "disabled or failed",+ )+ except Exception:+ pass_windows_gateway_resume = _m()._pause_windows_gateways_for_update()if _windows_gateway_resume:@@ -7087,6 +7115,20 @@ def _cmd_update_impl(args, gateway_mode: bool):pass_warn_incomplete_gateway_fleet_restart(failed_or_stale_units)+ try:+ from hermes_cli.update_receipt import record_gateway_restart++ record_gateway_restart(+ restarted_services=restarted_services,+ relaunched_profiles=relaunched_profiles,+ externally_supervised_profiles=externally_supervised_profiles,+ killed_pids=sorted(killed_pids),+ failed_units=failed_or_stale_units,+ incomplete=bool(failed_or_stale_units),+ )+ except Exception:+ pass+if not restarted_services and not killed_pids:# No gateways were running — nothing to dopass@@ -7157,6 +7199,16 @@ def _cmd_update_impl(args, gateway_mode: bool):_exit_code_path.write_text("1", encoding="utf-8")except OSError:pass+ try:+ from hermes_cli.update_receipt import record_gateway_restart++ record_gateway_restart(+ restarted_services=restarted_services,+ incomplete=gateway_fleet_restart_incomplete,+ phase_error=str(e),+ )+ except Exception:+ pass_m()._resume_windows_gateways_after_update(_windows_gateway_resume)@@ -7206,6 +7258,38 @@ def _cmd_update_impl(args, gateway_mode: bool):print("Tip: You can now select a provider and model:")print(" hermes model # Select provider and model")+ # Phase 1 (#91277): post-update fleet version verification. Compare+ # every live gateway's stamped code_sha against the freshly-updated+ # checkout and surface any gateway still serving pre-update code —+ # instead of assuming the restart phase worked (#88654, #69754).+ _fleet_snapshot: list = []+ try:+ from hermes_cli.update_receipt import (+ collect_fleet_versions,+ print_fleet_version_matrix,+ )++ # A brief settle window: freshly restarted gateways need a+ # moment to rewrite gateway_state.json with their new identity.+ _time.sleep(2.0)+ _fleet_snapshot = collect_fleet_versions()+ if print_fleet_version_matrix(_fleet_snapshot):+ gateway_fleet_restart_incomplete = True+ except Exception as _fleet_exc:+ logger.debug("Fleet version verification failed: %s", _fleet_exc)++ try:+ from hermes_cli.update_receipt import finalize_update_receipt++ _receipt_path = finalize_update_receipt(+ "partial" if gateway_fleet_restart_incomplete else "success",+ fleet=_fleet_snapshot,+ )+ if _receipt_path is not None:+ logger.info("Update receipt written: %s", _receipt_path)+ except Exception as _receipt_exc:+ logger.debug("Update receipt finalize failed: %s", _receipt_exc)+if gateway_fleet_restart_incomplete:# Code update itself succeeded, but at least one gateway still# runs pre-update modules — surface that as a failed update so@@ -7225,6 +7309,12 @@ def _cmd_update_impl(args, gateway_mode: bool):_write_gateway_update_exit_code(desktop_build_ok)else:print(f"✗ Update failed: {e}")+ try:+ from hermes_cli.update_receipt import finalize_update_receipt++ finalize_update_receipt("failed")+ except Exception:+ passsys.exit(1)# --- Hoisted from the body of _cmd_update_impl (self-contained, no closure state) ---diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pynew file mode 100644index 00000000000..63769c4a07e--- /dev/null+++ b/hermes_cli/update_receipt.py@@ -0,0 +1,347 @@+"""Structured update receipts + post-update fleet version verification.++Phase 1 of the fleet-update reliability plan (#91277): the updater must+*prove* its outcome instead of assuming it.++Two additive capabilities, both designed so a failure inside them can never+break an update (every public entry point is exception-swallowing):++1. **Update receipt** — a machine-readable JSON record of what one+ ``hermes update`` run discovered, did, skipped (and why), written to+ ``<HERMES_HOME>/logs/update_receipts/``. Silent-failure classes this+ makes visible: #88848 (helper died after "success" printed), #74973+ (restart silently skipped), #85753 (restart phase never ran), #81193+ (desktop shows failure for a successful update).++2. **Fleet version verification** — after the restart phase, read every+ profile's ``gateway_state.json``, compare each live gateway's stamped+ ``code_sha`` (written by ``gateway/status.py`` on every runtime-status+ write) against the freshly-updated checkout's HEAD, and print a fleet+ version matrix. Mixed-version fleets (#88654, #69754, #77553, #56717)+ become a loud, actionable report instead of a latent state.++Deployment-kind awareness (docker/image-managed installs) rides on+``hermes_cli.build_info.get_code_identity()``: an image build reports+``source="build-file"`` and the receipt records that the install is not+in-place updatable.+"""++from __future__ import annotations++import json+import os+import sys+import time+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Optional++import logging++logger = logging.getLogger(__name__)++_RECEIPT_DIR_NAME = "update_receipts"+_RECEIPT_KEEP = 20 # keep the last N receipts per profile home++# Module-level current receipt. ``hermes update`` is a single-threaded CLI+# command; a module singleton lets the 7k-line updater record steps from+# any depth without threading a handle through every helper.+_current: Optional["UpdateReceipt"] = None+++def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()+++class UpdateReceipt:+ """Collects the observable facts of one ``hermes update`` run."""++ def __init__(self) -> None:+ self.data: dict[str, Any] = {+ "schema": 1,+ "started_at": _utc_now_iso(),+ "finished_at": None,+ "argv": list(sys.argv),+ "pid": os.getpid(),+ "outcome": "running", # running | success | partial | failed+ "pre_update": {},+ "post_update": {},+ "steps": [],+ "skips": [],+ "gateway_restart": {},+ "fleet": [],+ }+ try:+ from hermes_cli.build_info import get_code_identity++ self.data["pre_update"] = get_code_identity()+ except Exception:+ pass++ # -- recording ---------------------------------------------------------+ def step(self, name: str, ok: bool, detail: str = "") -> None:+ self.data["steps"].append(+ {"name": name, "ok": bool(ok), "detail": detail, "at": _utc_now_iso()}+ )++ def skip(self, name: str, reason: str) -> None:+ self.data["skips"].append(+ {"name": name, "reason": reason, "at": _utc_now_iso()}+ )++ def gateway_restart_result(+ self,+ *,+ restarted_services: list | None = None,+ relaunched_profiles: list | None = None,+ externally_supervised_profiles: list | None = None,+ killed_pids: list | None = None,+ failed_units: list | None = None,+ incomplete: bool = False,+ phase_error: str = "",+ ) -> None:+ self.data["gateway_restart"] = {+ "restarted_services": list(restarted_services or []),+ "relaunched_profiles": list(relaunched_profiles or []),+ "externally_supervised_profiles": list(+ externally_supervised_profiles or []+ ),+ "killed_pids": [int(p) for p in (killed_pids or [])],+ "failed_units": [str(u) for u in (failed_units or [])],+ "incomplete": bool(incomplete),+ "phase_error": phase_error,+ }++ def finalize(self, outcome: str) -> None:+ self.data["outcome"] = outcome+ self.data["finished_at"] = _utc_now_iso()+ try:+ from hermes_cli.build_info import get_code_identity++ self.data["post_update"] = get_code_identity(refresh=True)+ except Exception:+ pass+++def _receipt_dir() -> Path:+ from hermes_cli.config import get_hermes_home++ return get_hermes_home() / "logs" / _RECEIPT_DIR_NAME+++def begin_update_receipt() -> None:+ """Start recording a new update receipt. Never raises."""+ global _current+ try:+ _current = UpdateReceipt()+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("Could not start update receipt: %s", exc)+ _current = None+++def record_step(name: str, ok: bool, detail: str = "") -> None:+ """Record one update step outcome. No-op when no receipt is active."""+ try:+ if _current is not None:+ _current.step(name, ok, detail)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("Could not record update step %s: %s", name, exc)+++def record_skip(name: str, reason: str) -> None:+ """Record a skipped step WITH the reason it was skipped."""+ try:+ if _current is not None:+ _current.skip(name, reason)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("Could not record update skip %s: %s", name, exc)+++def record_gateway_restart(**kwargs: Any) -> None:+ """Record the gateway restart phase outcome (see UpdateReceipt)."""+ try:+ if _current is not None:+ _current.gateway_restart_result(**kwargs)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("Could not record gateway restart result: %s", exc)+++def finalize_update_receipt(outcome: str, fleet: list | None = None) -> Optional[Path]:+ """Finalize + persist the receipt. Returns the written path or None.++ ``outcome`` is one of ``success`` / ``partial`` / ``failed``.+ """+ global _current+ receipt = _current+ _current = None+ if receipt is None:+ return None+ try:+ receipt.finalize(outcome)+ if fleet is not None:+ receipt.data["fleet"] = fleet+ directory = _receipt_dir()+ directory.mkdir(parents=True, exist_ok=True)+ stamp = time.strftime("%Y%m%d_%H%M%S")+ path = directory / f"update_{stamp}_{os.getpid()}.json"+ path.write_text(+ json.dumps(receipt.data, indent=2, default=str), encoding="utf-8"+ )+ # Stable pointer for the dashboard/desktop: latest receipt.+ latest = directory / "latest.json"+ try:+ latest.write_text(+ json.dumps(receipt.data, indent=2, default=str), encoding="utf-8"+ )+ except OSError:+ pass+ _prune_old_receipts(directory)+ return path+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("Could not write update receipt: %s", exc)+ return None+++def _prune_old_receipts(directory: Path) -> None:+ try:+ receipts = sorted(+ (p for p in directory.glob("update_*.json") if p.is_file()),+ key=lambda p: p.stat().st_mtime,+ reverse=True,+ )+ for stale in receipts[_RECEIPT_KEEP:]:+ try:+ stale.unlink()+ except OSError:+ pass+ except Exception:+ pass+++def read_latest_receipt() -> Optional[dict[str, Any]]:+ """Read the most recent update receipt, or None. Never raises."""+ try:+ path = _receipt_dir() / "latest.json"+ if not path.is_file():+ return None+ payload = json.loads(path.read_text(encoding="utf-8"))+ return payload if isinstance(payload, dict) else None+ except Exception:+ return None+++# ---------------------------------------------------------------------------+# Fleet version verification+# ---------------------------------------------------------------------------++def collect_fleet_versions() -> list[dict[str, Any]]:+ """Snapshot every profile's gateway code identity vs. the current tree.++ Returns one entry per profile home that has a ``gateway_state.json``+ with a live PID::++ {"profile": str, "pid": int, "code_sha": str|None,+ "code_version": str|None, "state": "current"|"stale"|"unknown"}++ ``stale`` — gateway stamped a code_sha that differs from the updated+ checkout's HEAD (it is still serving pre-update modules).+ ``unknown`` — gateway predates the code-identity stamp (started before+ this feature landed) or identity could not be resolved.+ Never raises; a probe failure yields an empty list.+ """+ results: list[dict[str, Any]] = []+ try:+ from hermes_cli.build_info import get_code_identity++ expected_sha = (get_code_identity(refresh=True) or {}).get("sha")+ except Exception:+ expected_sha = None++ try:+ from gateway.status import _pid_exists, read_runtime_status+ from hermes_cli.profiles import (+ _get_default_hermes_home,+ _get_profiles_root,+ _PROFILE_ID_RE,+ )++ homes: list[tuple[str, Path]] = []+ default_home = _get_default_hermes_home()+ if default_home.is_dir():+ homes.append(("default", default_home))+ profiles_root = _get_profiles_root()+ if profiles_root.is_dir():+ for entry in sorted(profiles_root.iterdir()):+ if entry.is_dir() and entry.name != "default" and _PROFILE_ID_RE.match(entry.name):+ homes.append((entry.name, entry))++ for profile, home in homes:+ status_path = home / "gateway_state.json"+ record = read_runtime_status(status_path)+ if not record:+ continue+ pid = record.get("pid")+ try:+ pid = int(pid)+ except (TypeError, ValueError):+ continue+ if not _pid_exists(pid):+ continue+ code_sha = record.get("code_sha")+ if not code_sha or not expected_sha:+ state = "unknown"+ elif str(code_sha) == str(expected_sha):+ state = "current"+ else:+ state = "stale"+ results.append(+ {+ "profile": profile,+ "pid": pid,+ "code_sha": str(code_sha) if code_sha else None,+ "code_version": record.get("code_version"),+ "state": state,+ }+ )+ except Exception as exc:+ logger.debug("Fleet version probe failed: %s", exc)+ return results+++def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:+ """Print the post-update fleet version matrix.++ Returns True when at least one gateway is provably stale (still+ serving pre-update code), so the caller can escalate. ``unknown``+ entries are reported but do NOT fail the update: gateways started+ before the code-identity stamp existed have no sha to compare, and+ failing on them would turn this feature's own rollout into a+ false-positive storm.+ """+ if not fleet:+ return False+ any_stale = False+ print()+ print("Fleet version check:")+ for entry in fleet:+ sha = entry.get("code_sha")+ short = sha[:8] if isinstance(sha, str) and sha else "?"+ state = entry.get("state")+ profile = entry.get("profile")+ pid = entry.get("pid")+ if state == "current":+ print(f" ✓ {profile} (pid {pid}) @ {short} — up to date")+ elif state == "stale":+ any_stale = True+ print(f" ✗ {profile} (pid {pid}) @ {short} — STALE (pre-update code)")+ else:+ print(+ f" ? {profile} (pid {pid}) — version unknown "+ "(gateway predates version stamping; restart to enable)"+ )+ if any_stale:+ print()+ print(" ⚠ Stale gateways keep serving pre-update code until restarted:")+ print(" hermes gateway restart # active profile")+ print(" hermes -p <profile> gateway restart # named profile")+ return any_stalediff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.pynew file mode 100644index 00000000000..6f2d3f99685--- /dev/null+++ b/tests/hermes_cli/test_update_receipt.py@@ -0,0 +1,259 @@+"""Tests for hermes_cli.update_receipt — Phase 1 of the fleet-update plan (#91277).++Covers:+- receipt lifecycle (begin → record → finalize → read back)+- skip recording with reasons+- gateway restart phase recording (success + phase-error shapes)+- receipt pruning+- fleet version classification (current / stale / unknown)+- gateway_state.json code-identity stamping (gateway/status.py side)+"""++import json+import os+from pathlib import Path++import pytest++import hermes_cli.update_receipt as ur+++def receipt_home(tmp_path, monkeypatch):+ """Isolated HERMES_HOME for receipt writes."""+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(+ "hermes_cli.config.get_hermes_home", lambda: home, raising=False+ )+ # ensure no receipt bleeds between tests+ ur._current = None+ yield home+ ur._current = None+++def _finalize(outcome="success", fleet=None):+ return ur.finalize_update_receipt(outcome, fleet=fleet)+++class TestReceiptLifecycle:+ def test_begin_record_finalize_roundtrip(self, receipt_home):+ ur.begin_update_receipt()+ ur.record_step("pre_update_backup", True, "snapshot=abc123")+ ur.record_skip("gateway_restart", "no gateways running")+ ur.record_gateway_restart(+ restarted_services=["hermes-gateway"],+ relaunched_profiles=["work"],+ killed_pids=[123],+ failed_units=[],+ incomplete=False,+ )+ path = _finalize("success", fleet=[{"profile": "default", "state": "current"}])+ assert path is not None and path.is_file()++ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["schema"] == 1+ assert payload["outcome"] == "success"+ assert payload["finished_at"] is not None+ assert payload["steps"][0]["name"] == "pre_update_backup"+ assert payload["steps"][0]["ok"] is True+ assert payload["skips"][0]["reason"] == "no gateways running"+ gr = payload["gateway_restart"]+ assert gr["restarted_services"] == ["hermes-gateway"]+ assert gr["relaunched_profiles"] == ["work"]+ assert gr["killed_pids"] == [123]+ assert gr["incomplete"] is False+ assert payload["fleet"][0]["profile"] == "default"++ def test_latest_pointer_written_and_readable(self, receipt_home):+ ur.begin_update_receipt()+ ur.record_step("git_pull", True)+ _finalize("partial")+ latest = ur.read_latest_receipt()+ assert latest is not None+ assert latest["outcome"] == "partial"++ def test_phase_error_shape(self, receipt_home):+ ur.begin_update_receipt()+ ur.record_gateway_restart(+ restarted_services=[],+ incomplete=True,+ phase_error="boom: module vanished mid-pull",+ )+ path = _finalize("partial")+ payload = json.loads(path.read_text(encoding="utf-8"))+ gr = payload["gateway_restart"]+ assert gr["incomplete"] is True+ assert "boom" in gr["phase_error"]++ def test_record_without_begin_is_noop(self, receipt_home):+ # No begin — nothing should raise, nothing should be written.+ ur.record_step("orphan", True)+ ur.record_skip("orphan", "no receipt")+ ur.record_gateway_restart(restarted_services=[])+ assert _finalize("success") is None++ def test_finalize_clears_current(self, receipt_home):+ ur.begin_update_receipt()+ assert ur._current is not None+ _finalize("success")+ assert ur._current is None++ def test_pruning_keeps_recent(self, receipt_home, monkeypatch):+ monkeypatch.setattr(ur, "_RECEIPT_KEEP", 3)+ directory = receipt_home / "logs" / "update_receipts"+ directory.mkdir(parents=True)+ for i in range(6):+ p = directory / f"update_2026010{i}_000000_1.json"+ p.write_text("{}", encoding="utf-8")+ os.utime(p, (1000 + i, 1000 + i))+ ur._prune_old_receipts(directory)+ remaining = sorted(p.name for p in directory.glob("update_*.json"))+ assert len(remaining) == 3+ # newest three survive+ assert remaining == [+ "update_20260103_000000_1.json",+ "update_20260104_000000_1.json",+ "update_20260105_000000_1.json",+ ]++ def test_read_latest_receipt_missing(self, receipt_home):+ assert ur.read_latest_receipt() is None+++class TestFleetClassification:+ def _fleet_with(self, monkeypatch, tmp_path, record, expected_sha="a" * 40):+ """Run collect_fleet_versions against one fake default profile."""+ home = tmp_path / "fleet_home"+ home.mkdir()+ (home / "gateway_state.json").write_text(+ json.dumps(record), encoding="utf-8"+ )+ monkeypatch.setattr(+ "hermes_cli.build_info.get_code_identity",+ lambda refresh=False: {"sha": expected_sha, "short_sha": expected_sha[:8],+ "version": "1.0", "source": "git"},+ )+ monkeypatch.setattr(+ "hermes_cli.profiles._get_default_hermes_home", lambda: home+ )+ monkeypatch.setattr(+ "hermes_cli.profiles._get_profiles_root",+ lambda: tmp_path / "nonexistent_profiles_root",+ )+ monkeypatch.setattr("gateway.status._pid_exists", lambda pid: True)+ return ur.collect_fleet_versions()++ def test_current_gateway(self, monkeypatch, tmp_path):+ sha = "a" * 40+ fleet = self._fleet_with(+ monkeypatch, tmp_path,+ {"pid": 4242, "code_sha": sha, "code_version": "1.0"},+ expected_sha=sha,+ )+ assert len(fleet) == 1+ assert fleet[0]["state"] == "current"+ assert fleet[0]["pid"] == 4242++ def test_stale_gateway(self, monkeypatch, tmp_path):+ fleet = self._fleet_with(+ monkeypatch, tmp_path,+ {"pid": 4242, "code_sha": "b" * 40, "code_version": "0.9"},+ expected_sha="a" * 40,+ )+ assert fleet[0]["state"] == "stale"++ def test_unstamped_gateway_is_unknown(self, monkeypatch, tmp_path):+ # Pre-feature gateway: no code_sha in its runtime status.+ fleet = self._fleet_with(+ monkeypatch, tmp_path, {"pid": 4242}, expected_sha="a" * 40+ )+ assert fleet[0]["state"] == "unknown"++ def test_dead_pid_excluded(self, monkeypatch, tmp_path):+ home = tmp_path / "fleet_home2"+ home.mkdir()+ (home / "gateway_state.json").write_text(+ json.dumps({"pid": 999999, "code_sha": "a" * 40}), encoding="utf-8"+ )+ monkeypatch.setattr(+ "hermes_cli.profiles._get_default_hermes_home", lambda: home+ )+ monkeypatch.setattr(+ "hermes_cli.profiles._get_profiles_root",+ lambda: tmp_path / "nope",+ )+ monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)+ assert ur.collect_fleet_versions() == []++ def test_matrix_returns_true_only_on_stale(self, capsys):+ assert ur.print_fleet_version_matrix([]) is False+ ok = ur.print_fleet_version_matrix(+ [{"profile": "default", "pid": 1, "code_sha": "a" * 40, "state": "current"}]+ )+ assert ok is False+ stale = ur.print_fleet_version_matrix(+ [+ {"profile": "default", "pid": 1, "code_sha": "a" * 40, "state": "current"},+ {"profile": "work", "pid": 2, "code_sha": "b" * 40, "state": "stale"},+ ]+ )+ assert stale is True+ out = capsys.readouterr().out+ assert "STALE" in out+ assert "hermes -p <profile> gateway restart" in out++ def test_unknown_does_not_fail_update(self, capsys):+ ok = ur.print_fleet_version_matrix(+ [{"profile": "default", "pid": 1, "code_sha": None, "state": "unknown"}]+ )+ assert ok is False+ assert "version unknown" in capsys.readouterr().out+++class TestGatewayStatusStamping:+ def test_runtime_status_record_carries_code_identity(self, monkeypatch):+ import gateway.status as gs++ monkeypatch.setattr(+ "hermes_cli.build_info.get_code_identity",+ lambda refresh=False: {"sha": "c" * 40, "short_sha": "c" * 8,+ "version": "2.0", "source": "git"},+ )+ record = gs._build_runtime_status_record()+ assert record["code_sha"] == "c" * 40+ assert record["code_version"] == "2.0"++ def test_code_identity_failure_degrades_to_absent(self, monkeypatch):+ import gateway.status as gs++ def _boom(refresh=False):+ raise RuntimeError("no build info")++ monkeypatch.setattr("hermes_cli.build_info.get_code_identity", _boom)+ record = gs._build_runtime_status_record()+ # Must not raise, and must not stamp bogus values.+ assert "code_sha" not in record+ assert record["gateway_state"] == "starting"+++class TestCodeIdentity:+ def test_get_code_identity_shape(self):+ from hermes_cli.build_info import get_code_identity++ identity = get_code_identity(refresh=True)+ assert set(identity) == {"sha", "short_sha", "version", "source"}+ # Running from a git checkout in CI/dev: sha resolves via git.+ if identity["sha"]:+ assert identity["short_sha"] == identity["sha"][:8]+ assert identity["source"] in ("git", "build-file")++ def test_get_code_identity_cached(self):+ from hermes_cli.build_info import get_code_identity++ first = get_code_identity(refresh=True)+ second = get_code_identity()+ assert first == second+ # returned dicts are copies, not the shared cache+ second["sha"] = "mutated"+ assert get_code_identity()["sha"] == first["sha"]