The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): authorize the Windows cold-start from the resume token's attestation generation
kshitijk4poor060c0cd0f80a
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex b20c8cb98a3..109d09b6605 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -18,6 +18,7 @@ import shutilimport subprocessimport sysimport time+import uuidfrom datetime import datetime, timezonefrom pathlib import Pathfrom xml.sax.saxutils import escape@@ -870,11 +871,18 @@ def _start_attestation_path() -> Path:def _write_start_attestation(pids: list[int], via: str) -> None:- """Persist the PIDs a ✓ vouched for. Best-effort, never raises."""+ """Persist the PIDs a ✓ vouched for. Best-effort, never raises.++ ``generation`` identifies this marker instance: the update resume token records the generation+ whose death authorized a cold-start, so execution consumes exactly that marker and never a+ newer one written by a concurrent ``hermes gateway start`` (#110020 review)."""try:path = _start_attestation_path()path.parent.mkdir(parents=True, exist_ok=True)- payload = {"pids": [int(p) for p in pids], "via": via, "ts": datetime.now(timezone.utc).isoformat()}+ payload = {+ "pids": [int(p) for p in pids], "via": via, "ts": datetime.now(timezone.utc).isoformat(),+ "generation": uuid.uuid4().hex,+ }tmp = path.with_suffix(".json.tmp")tmp.write_text(json.dumps(payload), encoding="utf-8")tmp.replace(path)@@ -889,6 +897,18 @@ def _clear_start_attestation() -> None:pass+def _attestation_generation(data: object) -> str | None:+ """The marker instance identity, or ``None`` for a marker that carries none."""+ return str(data["generation"]) if isinstance(data, dict) and data.get("generation") else None+++def _consume_start_attestation(generation: str) -> None:+ """Clear the marker only while it is still the ``generation`` that was acted on; a newer+ marker belongs to a gateway start this caller knows nothing about and keeps its own report."""+ if _attestation_generation(_read_start_attestation()) == generation:+ _clear_start_attestation()++def _read_start_attestation() -> object | None:"""Parsed attestation payload (any JSON type), or ``None`` when absent/unreadable. Never raises."""try:@@ -927,17 +947,22 @@ def _attested_dead(attested: list[int], current_pids: list[int]) -> bool:return not current_pids and not any(_attested_pid_exited_cleanly(pid) for pid in attested)-def attested_gateway_died(current_pids: list[int]) -> bool:- """True when the start attestation vouches for gateway PID(s) that are gone without a clean exit.+def attested_death_generation(current_pids: list[int]) -> str | None:+ """The generation of a start attestation that vouches for gateway PID(s) gone without a clean exit,+ or ``None``.Read-only twin of :func:`check_start_attestation` for callers that must not consume theone-shot marker — ``hermes update`` consults it to decide whether a Desktop-owned install- still owes a gateway cold-start (#109538). Callers pass the liveness they already established- (``[]`` after their own discovery came back empty) so the process table is not scanned twice.- ``False`` for anything undecidable (no marker, a clean ledger exit): "unknown" must never read- as "dead"."""- attested = _attested_pids_from(_read_start_attestation())- return bool(attested) and _attested_dead(attested, current_pids)+ still owes a gateway cold-start (#109538) and records the generation in its resume token so the+ execution step consumes exactly the marker it was authorized by. Callers pass the liveness they+ already established (``[]`` after their own discovery came back empty) so the process table is+ not scanned twice. ``None`` for anything undecidable (no marker, no generation, a clean ledger+ exit): "unknown" must never read as "dead"."""+ data = _read_start_attestation()+ attested = _attested_pids_from(data)+ if not attested or not _attested_dead(attested, current_pids):+ return None+ return _attestation_generation(data)def check_start_attestation(current_pids: list[int] | None = None) -> str | None:diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 379841978df..115ab4fe648 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -750,18 +750,24 @@ def _windows_cold_start_plan() -> dict | None:gateway that died without a clean exit. The Desktop hand-off exits the app before the updater startsand can kill the running gateway in those same seconds, so discovery finds no live PID to pause(#109538) — the dead attestation is the only surviving "a gateway was up" evidence, and the Desktop- does not restart the messaging gateway itself. Keep the plan; the spawn-time re-check in- ``_cold_start_windows_gateway_after_update`` stays the ownership authority."""+ does not restart the messaging gateway itself. Keep the plan, and record the attestation+ *generation* that authorized it on the token: the marker is a mutable one-shot that any concurrent+ ``hermes gateway status``/``start`` consumes, so execution authorizes the spawn from the token and+ consumes only that generation (#110020 review)."""from hermes_cli.update_cmd import _desktop_owns_gateway_lifecyclefrom hermes_cli import gateway_windowswith _best_effort('Could not check Windows gateway autostart state before update: %s'):if not gateway_windows.is_installed():return None+ token = {"resume_needed": True, "profiles": {}, "unmapped_pids": [], "unmapped": [], "cold_start_if_installed": True}with _best_effort('Could not check Desktop gateway-lifecycle ownership before update: %s'):- if _desktop_owns_gateway_lifecycle() and not gateway_windows.attested_gateway_died(current_pids=[]):- logger.debug("Skipping Windows gateway cold-start plan: Desktop owns gateway lifecycle")- return None- return {"resume_needed": True, "profiles": {}, "unmapped_pids": [], "unmapped": [], "cold_start_if_installed": True}+ if _desktop_owns_gateway_lifecycle():+ generation = gateway_windows.attested_death_generation(current_pids=[])+ if generation is None:+ logger.debug("Skipping Windows gateway cold-start plan: Desktop owns gateway lifecycle")+ return None+ token["attested_generation"] = generation+ return tokenreturn None@@ -915,7 +921,7 @@ def _pause_windows_gateways_for_update() -> dict | None:return _pause_windows_gateway_services(service_gateways, token, profiles, unmapped)-def _cold_start_windows_gateway_after_update() -> bool:+def _cold_start_windows_gateway_after_update(token: dict | None = None) -> bool:"""Direct-spawn a detached gateway after update for the ``cold_start_if_installed`` case (installed but down).Idempotent: re-checks nothing is running so a concurrent autostart can't duplicate. A successful Popen@@ -930,7 +936,10 @@ def _cold_start_windows_gateway_after_update() -> bool:Desktop-owned lifecycle suppresses the spawn only while nothing attests a gateway is expected: anattested gateway that died without a clean exit is restored even then (#109538) — the Desktop does- not restart the messaging gateway itself.+ not restart the messaging gateway itself. That authority is the ``attested_generation`` the plan+ recorded on ``token``, not the marker on disk: the marker is a mutable one-shot a concurrent+ ``hermes gateway status``/``start`` consumes, which would otherwise skip this spawn and clear the+ token (#110020 review). Only that generation is consumed afterwards — never a newer marker."""from hermes_cli.update_cmd import _desktop_owns_gateway_lifecycle, _mif not _m()._is_windows():@@ -941,8 +950,9 @@ def _cold_start_windows_gateway_after_update() -> bool:with _abort_on_error("Could not re-check gateway liveness before cold-start"):if list(find_gateway_pids(all_profiles=True)):return True+ generation = (token or {}).get("attested_generation")with _abort_on_error("Could not re-check Desktop gateway-lifecycle ownership before cold-start"):- if _desktop_owns_gateway_lifecycle() and not gateway_windows.attested_gateway_died(current_pids=[]):+ if _desktop_owns_gateway_lifecycle() and not generation:logger.debug("Skipping Windows gateway cold-start: Desktop owns gateway lifecycle")return Truewith _abort_on_error("Could not cold-start Windows gateway after update"):@@ -956,7 +966,8 @@ def _cold_start_windows_gateway_after_update() -> bool:# it only now: a spawn that never became ready leaves it in place, so the registered retry still# holds its recovery obligation instead of seeing Desktop ownership with no marker and returning# success without a gateway (#110020 review).- gateway_windows._clear_start_attestation()+ if generation:+ gateway_windows._consume_start_attestation(generation)print(f"\n✓ Gateway started via cold-start after update (PID: {', '.join(map(str, ready_pids))})")with suppress(Exception):gateway_windows._write_start_attestation(ready_pids, "cold-start after update")@@ -1137,7 +1148,7 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:unmapped = token.get("unmapped") or []if not profiles and not any(u.get("argv") for u in unmapped):if token.get("cold_start_if_installed"):- if not _m()._cold_start_windows_gateway_after_update():+ if not _m()._cold_start_windows_gateway_after_update(token):raise RuntimeError("Windows gateway cold-start was not verified")token["cold_start_if_installed"] = Falsetoken["resume_needed"] = Falsediff --git a/tests/hermes_cli/test_gateway_start_attestation.py b/tests/hermes_cli/test_gateway_start_attestation.pyindex e38a3f6f26e..d82db4c069a 100644--- a/tests/hermes_cli/test_gateway_start_attestation.py+++ b/tests/hermes_cli/test_gateway_start_attestation.py@@ -204,7 +204,7 @@ def test_attested_probe_fails_closed_without_a_well_formed_dead_attestation(attethe same death to the user."""marker = attest_home / "state" / "gateway.start-attestation.json"- assert gateway_windows.attested_gateway_died(current_pids=[]) is False # no marker yet+ assert gateway_windows.attested_death_generation(current_pids=[]) is None # no marker yetmarker.parent.mkdir(exist_ok=True)# Exact positive ints only: ``True`` is an int subclass, 0/-1 are not PIDs, and a single@@ -214,11 +214,11 @@ def test_attested_probe_fails_closed_without_a_well_formed_dead_attestation(atte'{"pids": [true]}', '{"pids": [0]}', '{"pids": [-1]}', '{"pids": [555, "556"]}', '{"pids": [555, 0]}',):marker.write_text(malformed, encoding="utf-8")- assert gateway_windows.attested_gateway_died(current_pids=[]) is False, malformed+ assert gateway_windows.attested_death_generation(current_pids=[]) is None, malformedgateway_windows._write_start_attestation([555], "cold-start after update")- assert gateway_windows.attested_gateway_died(current_pids=[555]) is False # alive- assert gateway_windows.attested_gateway_died(current_pids=[]) is True # dead, unclean+ assert gateway_windows.attested_death_generation(current_pids=[555]) is None # alive+ assert gateway_windows.attested_death_generation(current_pids=[]) is not None # dead, uncleanassert marker.exists() # unconsumed — the CLI start below still reports itassert gateway_windows.check_start_attestation(current_pids=[]) is not None@@ -227,4 +227,4 @@ def test_attested_probe_fails_closed_without_a_well_formed_dead_attestation(atteencoding="utf-8",)gateway_windows._write_start_attestation([556], "cold-start after update")- assert gateway_windows.attested_gateway_died(current_pids=[]) is False # planned stop+ assert gateway_windows.attested_death_generation(current_pids=[]) is None # planned stopdiff --git a/tests/hermes_cli/test_update_cold_start_gateway_liveness.py b/tests/hermes_cli/test_update_cold_start_gateway_liveness.pyindex c7b2a4309a3..782e93df1bd 100644--- a/tests/hermes_cli/test_update_cold_start_gateway_liveness.py+++ b/tests/hermes_cli/test_update_cold_start_gateway_liveness.py@@ -59,7 +59,7 @@ def test_failed_readiness_keeps_the_dead_attestation_for_the_retry(monkeypatch,with pytest.raises(RuntimeError, match="did not become ready"):_run_cold_start(monkeypatch, capsys, surviving_pids=[])assert marker.exists()- assert gateway_windows.attested_gateway_died(current_pids=[]) is True+ assert gateway_windows.attested_death_generation(current_pids=[]) is not Nonedef test_cold_start_reports_success_when_process_survives(monkeypatch, capsys):diff --git a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.pyindex 6b8de2486c4..d7ec3023e66 100644--- a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py+++ b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py@@ -18,6 +18,8 @@ does not restart the messaging gateway itself.from __future__ import annotations+import json+from hermes_cli import gateway as hermes_gatewayfrom hermes_cli import gateway_windowsfrom hermes_cli import main as cli_main@@ -101,7 +103,7 @@ def test_pause_skips_cold_start_plan_when_desktop_owns_lifecycle(monkeypatch):hermes_gateway, "find_windows_gateway_services", lambda **_k: [])monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)- monkeypatch.setattr(gateway_windows, "attested_gateway_died", lambda **_k: False)+ monkeypatch.setattr(gateway_windows, "attested_death_generation", lambda **_k: None)monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)@@ -135,7 +137,7 @@ def test_cold_start_aborts_when_desktop_owns_lifecycle(monkeypatch):monkeypatch.setattr(cli_main, "_is_windows", lambda: True)monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])- monkeypatch.setattr(gateway_windows, "attested_gateway_died", lambda **_k: False)+ monkeypatch.setattr(gateway_windows, "attested_death_generation", lambda **_k: None)monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)monkeypatch.setattr(@@ -168,6 +170,8 @@ def test_attested_dead_gateway_survives_desktop_ownership_and_marker_is_consumedtoken = update_cmd._pause_windows_gateways_for_update()+ generation = token.pop("attested_generation")+ assert generation == json.loads(marker.read_text(encoding="utf-8"))["generation"]assert token == {"resume_needed": True,"profiles": {},@@ -175,6 +179,7 @@ def test_attested_dead_gateway_survives_desktop_ownership_and_marker_is_consumed"unmapped": [],"cold_start_if_installed": True,}+ token["attested_generation"] = generationassert marker.exists() # plan-time probe is read-onlyspawned = []@@ -182,8 +187,46 @@ def test_attested_dead_gateway_survives_desktop_ownership_and_marker_is_consumedmonkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: [4242])monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)- assert update_cmd._cold_start_windows_gateway_after_update() is True+ assert update_cmd._cold_start_windows_gateway_after_update(token) is Trueassert spawned == [1]assert "Gateway started via cold-start after update (PID: 4242)" in capsys.readouterr().outassert not marker.exists() # consumed by the spawn- assert gateway_windows.attested_gateway_died(current_pids=[]) is False+ assert gateway_windows.attested_death_generation(current_pids=[]) is None+++def test_cold_start_is_authorized_by_the_token_generation_not_the_mutable_marker(+ monkeypatch, tmp_path, capsys+):+ """#110020 review (a): the marker is a one-shot that a concurrent ``hermes gateway status``+ consumes between plan and execution. The spawn must still happen (authority lives on the+ token), and a *newer* marker written by a concurrent ``hermes gateway start`` must not be+ consumed as if it were ours."""+ monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: str(tmp_path))+ monkeypatch.setattr(cli_main, "_is_windows", lambda: True)+ monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)+ monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])+ monkeypatch.setattr(hermes_gateway, "find_windows_gateway_services", lambda **_k: [])+ monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)+ monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)+ monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)+ gateway_windows._write_start_attestation([555], "direct spawn (PID 555)")+ marker = tmp_path / "state" / "gateway.start-attestation.json"+ token = update_cmd._pause_windows_gateways_for_update()+ assert token["attested_generation"]++ # Concurrent ``hermes gateway status`` consumed the marker...+ assert gateway_windows.check_start_attestation(current_pids=[]) is not None+ assert not marker.exists()+ # ...and a concurrent ``hermes gateway start`` wrote a fresh one for its own PID.+ gateway_windows._write_start_attestation([777], "direct spawn (PID 777)")+ newer = json.loads(marker.read_text(encoding="utf-8"))["generation"]+ assert newer != token["attested_generation"]++ spawned = []+ monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda: spawned.append(1) or 4242)+ monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: [4242])+ monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)++ assert update_cmd._cold_start_windows_gateway_after_update(token) is True+ assert spawned == [1] # authorized by the token, not by the (consumed) marker+ assert json.loads(marker.read_text(encoding="utf-8"))["generation"] == newer # not ours to consume