The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): every begun update receipt is now persisted — command-boundary finalization
Teknium40b4a3bfe150
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 0c7c51608fa..7aa49f83d4b 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -10130,6 +10130,38 @@ def cmd_update(args):try:_self()._cmd_update_impl(args, gateway_mode=gateway_mode)+ except SystemExit as _update_exit:+ # Receipt boundary (#91283 review): the impl has many early+ # sys.exit paths (concurrent-instance preflight, venv-holder+ # refusal, head-pinned no-op, fetch failure) that never reach an+ # inner finalize. Persist any still-open receipt with the real+ # exit code, then let the exit proceed unchanged. No-op when an+ # inner path already finalized (exactly-once by construction).+ try:+ from hermes_cli.update_receipt import finalize_pending_update_receipt++ _code = _update_exit.code if isinstance(_update_exit.code, int) else 1+ finalize_pending_update_receipt(_code, f"sys.exit({_code})")+ except Exception:+ pass+ raise+ except BaseException as _update_exc:+ try:+ from hermes_cli.update_receipt import finalize_pending_update_receipt++ finalize_pending_update_receipt(+ 1, f"{type(_update_exc).__name__}: {_update_exc}"+ )+ except Exception:+ pass+ raise+ else:+ try:+ from hermes_cli.update_receipt import finalize_pending_update_receipt++ finalize_pending_update_receipt(0, "completed at command boundary")+ except Exception:+ passfinally:_update_lock.release()_finalize_update_output(_update_io_state)diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex 63769c4a07e..db90a2f3198 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -166,10 +166,15 @@ def record_gateway_restart(**kwargs: Any) -> None:logger.debug("Could not record gateway restart result: %s", exc)-def finalize_update_receipt(outcome: str, fleet: list | None = None) -> Optional[Path]:+def finalize_update_receipt(+ outcome: str, fleet: list | None = None, stop_reason: str = ""+) -> Optional[Path]:"""Finalize + persist the receipt. Returns the written path or None.- ``outcome`` is one of ``success`` / ``partial`` / ``failed``.+ ``outcome`` is one of ``success`` / ``partial`` / ``failed`` /+ ``refused``. Exactly-once by construction: the module singleton is+ popped first, so a second call (e.g. the command-boundary safety net+ after an inner path already finalized) is a no-op returning None."""global _currentreceipt = _current@@ -178,6 +183,8 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None) -> Optionalreturn Nonetry:receipt.finalize(outcome)+ if stop_reason:+ receipt.data["stop_reason"] = stop_reasonif fleet is not None:receipt.data["fleet"] = fleetdirectory = _receipt_dir()@@ -202,6 +209,42 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None) -> Optionalreturn None+def finalize_pending_update_receipt(+ exit_code: Optional[int] = None, stop_reason: str = ""+) -> Optional[Path]:+ """Command-boundary safety net: persist a still-open receipt, if any.++ ``hermes update`` has many early-termination paths (Windows+ concurrent-instance preflight, venv-holder refusal, head-pinned no-op,+ fetch failure — all ``sys.exit``) that predate the inner finalize+ call sites. Any receipt still open when the update COMMAND unwinds is+ finalized here so every post-begin run leaves a record — the+ refused/failed runs are exactly the ones a receipt matters most for+ (review on #91283). No-op when no receipt is open (the inner paths+ already finalized — exactly-once via the popped singleton) or when+ recording was never started. Never raises.++ Outcome mapping: exit 0/None → ``success`` (a path that completed+ without an explicit inner finalize), exit 2 → ``refused`` (the+ updater's preflight-refusal convention), anything else → ``failed``.+ """+ if _current is None:+ return None+ if exit_code in (0, None):+ outcome = "success"+ elif exit_code == 2:+ outcome = "refused"+ else:+ outcome = "failed"+ try:+ receipt = _current+ if receipt is not None and exit_code is not None:+ receipt.data["exit_code"] = int(exit_code)+ except Exception:+ pass+ return finalize_update_receipt(outcome, stop_reason=stop_reason)++def _prune_old_receipts(directory: Path) -> None:try:receipts = sorted(diff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.pyindex 6f2d3f99685..e120bb9e06a 100644--- a/tests/hermes_cli/test_update_receipt.py+++ b/tests/hermes_cli/test_update_receipt.py@@ -11,6 +11,7 @@ Covers:import jsonimport os+import sysfrom pathlib import Pathimport pytest@@ -121,6 +122,111 @@ class TestReceiptLifecycle:assert ur.read_latest_receipt() is None+class TestCommandBoundaryFinalization:+ """Receipt lifetime is owned by the update-command boundary (#91283 review).++ Early sys.exit paths (concurrent-instance preflight exit-2, venv-holder+ refusal, fetch failure) predate the inner finalize sites; the boundary+ safety net must persist the receipt exactly once with the stop reason,+ while inner-finalized runs are untouched.+ """++ def test_pending_receipt_persisted_on_exit_2_refusal(self, receipt_home):+ ur.begin_update_receipt()+ ur.record_step("windows_preflight", False, "another hermes.exe running")+ path = ur.finalize_pending_update_receipt(2, "sys.exit(2)")+ assert path is not None and path.is_file()+ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["outcome"] == "refused"+ assert payload["exit_code"] == 2+ assert payload["stop_reason"] == "sys.exit(2)"+ assert payload["finished_at"] is not None+ assert ur._current is None++ def test_pending_receipt_persisted_on_exit_1_failure(self, receipt_home):+ ur.begin_update_receipt()+ path = ur.finalize_pending_update_receipt(1, "sys.exit(1)")+ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["outcome"] == "failed"+ assert payload["exit_code"] == 1++ def test_noop_when_inner_path_already_finalized(self, receipt_home):+ """Exactly-once: boundary call after an inner finalize writes nothing."""+ ur.begin_update_receipt()+ first = ur.finalize_update_receipt("success")+ assert first is not None+ second = ur.finalize_pending_update_receipt(0, "boundary")+ assert second is None+ directory = receipt_home / "logs" / "update_receipts"+ assert len(list(directory.glob("update_*.json"))) == 1++ def test_noop_when_never_begun(self, receipt_home):+ assert ur.finalize_pending_update_receipt(2, "sys.exit(2)") is None+ assert ur.read_latest_receipt() is None++ def test_cmd_update_boundary_finalizes_on_early_exit(+ self, receipt_home, monkeypatch+ ):+ """End-to-end through the real cmd_update wrapper: an impl that begins+ a receipt then sys.exit(2)s (the concurrent-instance shape) must leave+ a finalized 'refused' receipt, preserve the exit code, and clear the+ singleton."""+ from types import SimpleNamespace++ from hermes_cli import main as hermes_main++ def _fake_impl(args, gateway_mode):+ ur.begin_update_receipt()+ ur.record_step("windows_preflight", False, "hermes.exe holds venv")+ sys.exit(2)++ monkeypatch.setattr(hermes_main, "_cmd_update_impl", _fake_impl)+ monkeypatch.setattr(+ hermes_main, "detect_install_method", lambda *a, **k: "git", raising=False+ )+ monkeypatch.setattr(+ hermes_main,+ "_install_hangup_protection",+ lambda gateway_mode: None,+ raising=False,+ )+ monkeypatch.setattr(+ hermes_main, "_finalize_update_output", lambda state: None, raising=False+ )++ class _FakeLock:+ holder = None++ def acquire(self):+ return True++ def release(self):+ pass++ import hermes_cli.update_lock as update_lock_mod++ monkeypatch.setattr(update_lock_mod, "UpdateLock", _FakeLock)++ args = SimpleNamespace(+ check=False, gateway=False, branch=None, yes=False,+ force=False, force_venv=False,+ )+ with pytest.raises(SystemExit) as exc_info:+ hermes_main.cmd_update(args)++ assert exc_info.value.code == 2 # exit code preserved+ latest = ur.read_latest_receipt()+ assert latest is not None+ assert latest["outcome"] == "refused"+ assert latest["exit_code"] == 2+ assert latest["stop_reason"] == "sys.exit(2)"+ assert latest["steps"][0]["name"] == "windows_preflight"+ assert ur._current is None+ # exactly-once: exactly one receipt file+ directory = receipt_home / "logs" / "update_receipts"+ assert len(list(directory.glob("update_*.json"))) == 1++class TestFleetClassification:def _fleet_with(self, monkeypatch, tmp_path, record, expected_sha="a" * 40):"""Run collect_fleet_versions against one fake default profile."""