Skip to content

The agent that grows with you

fix(update): the gateway /update status follows a committed run's receipt

Tekniumc7db1c081919
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index cb817be5f38..6d092950862 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -793,6 +793,14 @@ def _complete_source_update(request: dict | None) -> None:
result, lost = settle_lost_completion(
request, result.get("error") or f"the completion process exited {result['exit_code']}"), True
_accept_completion_pm_receipt(result.get("pm_receipt"), request["receipt"]["update_id"])
+ if result.get("receipt") is not None:
+ # The child closed the run: drop the stale pre-child context before anything below can
+ # write it (a later follow-up amends the terminal archive), and let the command boundary
+ # answer the gateway status from the receipt (C3, review regression 3).
+ _completion_receipt.adopt_terminal_receipt(result["receipt"])
+ current = _completion_receipt._current.get()
+ if current is not None:
+ _completion_receipt._current.reset(current.current_token)
token = request["windows_resume"]
if token is not None and result.get("windows_resume") is not None:
resumed = dict(result["windows_resume"])
@@ -810,10 +818,6 @@ def _complete_source_update(request: dict | None) -> None:
record_followup("windows_resume", reason)
amend_terminal_followup(request["receipt"]["update_id"], "windows_resume", reason)
_settle_windows_resume(request)
- if result.get("receipt") is not None:
- current = _completion_receipt._current.get()
- if current is not None:
- _completion_receipt._current.reset(current.current_token)
if result["exit_code"]:
raise SystemExit(result["exit_code"])
if lost:
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 5ca7fd6768d..f37e91eb67a 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -39,6 +39,11 @@ _LIST_GATEWAY_UNITS = [
def _write_gateway_update_exit_code(ok: bool) -> None:
from hermes_cli.update_cmd import get_hermes_home
+ from hermes_cli.update_receipt import committed_success
+
+ # A run whose receipt already closed as a success is never reported failed (C3, review
+ # regression 3): the command boundary's catch-alls call this with False.
+ ok = ok or committed_success()
path = get_hermes_home() / ".update_exit_code"
with suppress(OSError):
path.write_text("0" if ok else "1", encoding="utf-8")
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index bcd6b3cd620..6ab8b6d1e6d 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -454,9 +454,6 @@ def _finish(request: dict, result_path: Path) -> int:
_report_unbuilt_desktop(request)
update_receipt.record_followup("completion", f"{type(exc).__name__}: {exc}")
finally:
- if code and request["gateway_mode"]:
- from hermes_cli.update_cmd import _write_gateway_update_exit_code
- _write_gateway_update_exit_code(False)
# The new interpreter owns recovery too. The original parent's atexit
# token is updated from the response; it acts only if this process dies.
try:
@@ -469,8 +466,13 @@ def _finish(request: dict, result_path: Path) -> int:
update_receipt.amend_terminal_followup(request["receipt"]["update_id"], "windows_resume", step_reason)
update_receipt.finalize_pending_update_receipt(code, reason)
terminal_receipt = _read_terminal_receipt(request)
+ if terminal_receipt and terminal_receipt.get("outcome") == "success":
+ code = 0 # an interrupt that landed after verification closed the run (review regression 3)
+ if code and request["gateway_mode"]:
+ from hermes_cli.update_cmd import _write_gateway_update_exit_code
+ _write_gateway_update_exit_code(False)
if not terminal_receipt:
- code = code or 1
+ code = code or 1 # the parent settles a lost result (settle_lost_completion)
_write_json(result_path, {
"schema": 1, "update_id": request["receipt"]["update_id"], "exit_code": code,
"receipt": terminal_receipt, "windows_resume": request["windows_resume"],
diff --git a/hermes_cli/update_finish.py b/hermes_cli/update_finish.py
index e1aae542c89..beb386eb45d 100644
--- a/hermes_cli/update_finish.py
+++ b/hermes_cli/update_finish.py
@@ -167,12 +167,15 @@ def main(context: Path, result: Path) -> int:
update_receipt.record_step("historical_completion", False, str(exc))
print(f"Update completion failed: {exc}", file=sys.stderr, flush=True)
finally:
+ terminal = update_receipt.finalized_receipt(request["update_id"]) or {}
if code and request.get("gateway_mode"):
- # Even an application import failure must wake the gateway watcher.
+ # Even an application import failure must wake the gateway watcher. A run that already
+ # closed as a success (an interrupt after verification) stays 0 (review regression 3).
from hermes_constants import get_hermes_home
from hermes_cli.runtime_state import _atomic_bytes
- _atomic_bytes(get_hermes_home() / ".update_exit_code", b"1")
+ _atomic_bytes(get_hermes_home() / ".update_exit_code",
+ b"0" if terminal.get("outcome") == "success" else b"1")
if restarting and not cli_started:
# Startup failed before the replacement command could own a
# receipt. Preserve the original handoff, just like preparation.
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 6f6c10078e0..9aadd1117e2 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -58,18 +58,42 @@ COMMAND_BOUNDARY_STOP_REASON = "completed at command boundary"
_current: contextvars.ContextVar[Optional["UpdateReceipt"]] = contextvars.ContextVar(
"update_receipt_current", default=None
)
+#: The terminal outcome of the run the enclosing command scope finalized or adopted (from a
+#: completion child): ``committed_success`` answers the command boundary's gateway status from it.
+_scope_terminal: contextvars.ContextVar[Optional[dict[str, Any]]] = contextvars.ContextVar(
+ "update_receipt_scope_terminal", default=None
+)
@contextmanager
def update_receipt_scope():
"""Keep the command's finalization guard away from an enclosing update."""
token = _current.set(None)
+ terminal = _scope_terminal.set({})
try:
yield
finally:
+ _scope_terminal.reset(terminal)
_current.reset(token)
+def adopt_terminal_receipt(data: Any) -> None:
+ """A completion child finalized this command's run: its terminal outcome is this scope's too."""
+ cell = _scope_terminal.get()
+ if cell is not None and isinstance(data, dict) and data.get("finished_at"):
+ cell["outcome"] = data.get("outcome")
+
+
+def committed_success() -> bool:
+ """True when this command's run is closed and its receipt says ``success`` (C3).
+
+ The gateway ``/update`` status written at the command boundary follows the receipt: an
+ interrupt or error that escapes after the run closed as a success never reports it failed.
+ """
+ cell = _scope_terminal.get()
+ return _current.get() is None and bool(cell) and cell.get("outcome") == "success"
+
+
def current_correlation_id() -> Optional[str]:
"""The update correlation id in force in this context, or None.
@@ -475,6 +499,7 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason
# The terminal facts exist before the store is touched; a store that refuses the write
# (after the commit point) must not erase them for this process's own caller.
_FINALIZED[str(receipt.data.get("update_id"))] = receipt.data
+ adopt_terminal_receipt(receipt.data)
if fleet is not None:
receipt.data["fleet"] = fleet
# Manual serve restart obligations outlive one receipt rotation: carry the previous
diff --git a/tests/hermes_cli/test_update_finish.py b/tests/hermes_cli/test_update_finish.py
index 3f2f6b41eb6..fe2874c2e04 100644
--- a/tests/hermes_cli/test_update_finish.py
+++ b/tests/hermes_cli/test_update_finish.py
@@ -215,6 +215,12 @@ def completion(tmp_path, monkeypatch):
restarted_services=[], failed_or_stale_units=[], relaunched_profiles=[],
externally_supervised_profiles=[], killed_pids=set())
update._restart_gateway_fleet_after_update = restart
+ if fault == 'interrupt':
+ verify = update._verify_fleet_after_update
+ def verify_then_interrupt(*args, **kwargs):
+ verify(*args, **kwargs) # closes the run as a success
+ raise KeyboardInterrupt()
+ update._verify_fleet_after_update = verify_then_interrupt
merge = update._resume_windows_gateways_and_merge_outcome
def resume(outcome, token, gateway_mode):
assert token == request['windows_resume']
@@ -323,6 +329,21 @@ def test_raising_fleet_restart_after_commit_is_a_followup_not_exit_1(completion)
assert (home / ".update_exit_code").read_text(encoding="utf-8-sig").strip() == "0"
+def test_interrupt_after_verification_closed_the_run_keeps_gateway_status_0(completion):
+ """Review regression 3: verification already finalized the takeover's run as ``success``; an
+ interrupt landing after it must not rewrite the gateway /update status to 1."""
+ source, home, request, context, result, run = completion
+ request["gateway_mode"] = True
+ request["receipt"]["started_at"] = "2026-10-04T12:00:00+00:00"
+ context.write_text(json.dumps(request), encoding="utf-8")
+ child = run("interrupt")
+ receipt = json.loads((home / "logs/update_receipts/latest.json").read_text(encoding="utf-8-sig"))
+ assert receipt["update_id"] == request["update_id"]
+ assert receipt["outcome"] == "success", child.stdout + child.stderr
+ assert (home / ".update_exit_code").read_text(encoding="utf-8-sig").strip() == "0", child.stdout + child.stderr
+
+
@pytest.mark.platforms("posix")
@pytest.mark.parametrize("captured, installed, expected", [
(None, None, False),
diff --git a/tests/hermes_cli/test_update_post_commit_followups.py b/tests/hermes_cli/test_update_post_commit_followups.py
index daee3ea287f..522bfedde00 100644
--- a/tests/hermes_cli/test_update_post_commit_followups.py
+++ b/tests/hermes_cli/test_update_post_commit_followups.py
@@ -218,3 +218,69 @@ def test_followup_line_is_the_one_both_desktop_handoffs_parse(tmp_path, monkeypa
pattern = re.search(r"\[regex\]::Matches\(\(\$res\.Output -join \"`n\"\), \"([^\"]+)\"\)",
(scripts / "windows.ps1").read_text(encoding="utf-8")).group(1)
assert [m.group(1) for m in re.finditer(pattern, out)] == ["gateway_restart", "windows_resume"]
+
+
+def test_interrupt_after_the_run_closed_as_success_never_tells_the_gateway_1(tmp_path, monkeypatch):
+ """Review regression 3, the ``cmd_update`` boundary: once this run's receipt says ``success``,
+ an interrupt escaping afterwards must not write 1 to the gateway /update status."""
+ from types import SimpleNamespace
+ from hermes_cli import main, update_cmd
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False)
+ monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None)
+ monkeypatch.setattr(main, "_finalize_update_output", lambda state: None)
+
+ def committed_then_interrupted(args, gateway_mode):
+ update_receipt.begin_update_receipt()
+ update_receipt.finalize_update_receipt("success")
+ raise KeyboardInterrupt()
+
+ monkeypatch.setattr(update_cmd, "_cmd_update_impl", committed_then_interrupted)
+ with pytest.raises(KeyboardInterrupt):
+ main.cmd_update(SimpleNamespace(gateway=True))
+ assert _latest(tmp_path)["outcome"] == "success"
+ assert (tmp_path / ".update_exit_code").read_text(encoding="utf-8").strip() == "0"
+
+
+def test_a_failure_before_the_run_closed_still_tells_the_gateway_1(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+ from hermes_cli import main, update_cmd
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False)
+ monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None)
+ monkeypatch.setattr(main, "_finalize_update_output", lambda state: None)
+
+ def interrupted_while_open(args, gateway_mode):
+ update_receipt.begin_update_receipt()
+ raise KeyboardInterrupt()
+
+ monkeypatch.setattr(update_cmd, "_cmd_update_impl", interrupted_while_open)
+ with pytest.raises(KeyboardInterrupt):
+ main.cmd_update(SimpleNamespace(gateway=True))
+ assert (tmp_path / ".update_exit_code").read_text(encoding="utf-8").strip() == "1"
+
+
+def test_completion_child_interrupted_after_verification_answers_its_success(tmp_path, monkeypatch):
+ """Review regression 3, the selected completion child: verification finalized ``success`` and
+ then an interrupt landed. Exit, result and gateway status follow the receipt (0), not 130/1."""
+ from hermes_cli import update_completion
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ update_receipt.begin_update_receipt()
+ data = dict(update_receipt._current.get().data)
+ update_receipt._current.set(None)
+
+ def verified_then_interrupted(request):
+ update_receipt.finalize_update_receipt("success")
+ raise KeyboardInterrupt()
+
+ monkeypatch.setattr(update_completion, "_complete_selected", verified_then_interrupted)
+ request = {"receipt": data, "pm_receipt": None, "gateway_mode": True, "windows_resume": None}
+ result_path = tmp_path / "result.json"
+ assert update_completion._finish(request, result_path) == 0
+ answer = json.loads(result_path.read_text(encoding="utf-8"))
+ assert answer["exit_code"] == 0 and answer["receipt"]["outcome"] == "success"
+ assert not (tmp_path / ".update_exit_code").exists() or \
+ (tmp_path / ".update_exit_code").read_text(encoding="utf-8").strip() == "0"