The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): every .update_exit_code writer publishes atomically
Maciej Lisiewskif25f23bae1c4
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex d7499d8f2a1..82b7ccbd922 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -73,8 +73,10 @@ output_path, exit_code_path, cmd = sys.argv[1], sys.argv[2], sys.argv[3:]env = dict(os.environ, PYTHONUNBUFFERED="1")with open(output_path, "wb") as f:rc = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env).wait(timeout=3600)-with open(exit_code_path, "w", encoding="utf-8") as f:+# Temp + replace: the gateway watcher polls the exit code and reads an empty file as failure.+with open(exit_code_path + ".tmp", "w", encoding="utf-8") as f:f.write(str(rc))+os.replace(exit_code_path + ".tmp", exit_code_path)""".strip()@@ -145,7 +147,9 @@ def _spawn_detached_update(hermes_cmd, output_path, exit_code_path) -> None:f" > {shlex.quote(str(output_path))} 2>&1; "# Avoid `status=$?`: `status` is read-only in zsh and this template is reused in# macOS/zsh operator wrappers, so keep it zsh-safe even though bash runs it here.- f"rc=$?; printf '%s' \"$rc\" > {shlex.quote(str(exit_code_path))}")+ # Temp + mv: the gateway watcher polls the exit code and reads an empty file as failure.+ f"rc=$?; printf '%s' \"$rc\" > {shlex.quote(str(exit_code_path) + '.tmp')}"+ f" && mv -f {shlex.quote(str(exit_code_path) + '.tmp')} {shlex.quote(str(exit_code_path))}")# Preferred: setsid creates a new session, fully detached; fallback start_new_session=True# calls os.setsid() in the child.setsid_bin = shutil.which("setsid")diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.pyindex d73a9a137be..a4ddeb23fb8 100644--- a/hermes_cli/_update_takeover.py+++ b/hermes_cli/_update_takeover.py@@ -112,12 +112,14 @@ def _head_sha(root: Path) -> str:def _record_failure(request: dict, result: Path, code: int, detail: str) -> None:from hermes_cli import update_receipt+ from hermes_cli.runtime_state import _atomic_bytesfrom hermes_constants import get_hermes_homeupdate_receipt.record_step("historical_takeover", False, detail)saved = update_receipt.finalize_pending_update_receipt(code, detail)if request.get("gateway_mode"):- (get_hermes_home() / ".update_exit_code").write_text(f"{code}\n", encoding="utf-8")+ # Atomic: the gateway watcher polls this file and reads an empty one as exit 1.+ _atomic_bytes(get_hermes_home() / ".update_exit_code", f"{code}\n".encode())result.write_text(json.dumps({"receipt_handled": saved is not None, "resume_handled": False}), encoding="utf-8")@@ -207,9 +209,10 @@ def _record_owed_finish(request: dict, result: Path, detail: str) -> None:saved = update_receipt.finalize_pending_update_receipt(0, f"committed; finishing steps owed: {detail}")if request.get("gateway_mode"):with suppress(Exception): # health: allow BLE001 -- post-commit boundary: see above+ from hermes_cli.runtime_state import _atomic_bytesfrom hermes_constants import get_hermes_home- (get_hermes_home() / ".update_exit_code").write_text("0\n", encoding="utf-8")+ _atomic_bytes(get_hermes_home() / ".update_exit_code", b"0\n")with suppress(OSError): # no result file: the old updater keeps its own receipt and resumesresult.write_text(json.dumps({"receipt_handled": saved is not None, "resume_handled": False}),encoding="utf-8")diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex 776b7b91370..36f94e34b9c 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -39,6 +39,7 @@ _LIST_GATEWAY_UNITS = [def _write_gateway_update_exit_code(ok: bool) -> None:+ from hermes_cli.runtime_state import _atomic_bytesfrom hermes_cli.update_cmd import get_hermes_homefrom hermes_cli.update_receipt import committed_success@@ -47,7 +48,8 @@ def _write_gateway_update_exit_code(ok: bool) -> None: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")+ # Atomic: the gateway watcher polls this file and reads an empty one as exit 1.+ _atomic_bytes(path, b"0" if ok else b"1")def _fleet_restart_pending_marker_path() -> Path:diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex e1806284d41..73401c9b8fd 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -217,7 +217,12 @@ def _publish_gateway_success(request: dict) -> None:if not request.get("gateway_mode"):returntry:- (Path(request["home"]) / ".update_exit_code").write_text("0", encoding="utf-8")+ # Temp + rename (stdlib, like _write_json): the gateway watcher polls this file and reads+ # an empty one as exit 1.+ marker = Path(request["home"]) / ".update_exit_code"+ temporary = marker.with_name(marker.name + ".tmp")+ temporary.write_text("0", encoding="utf-8")+ temporary.replace(marker)except OSError as exc:print(f" ⚠ Could not publish the gateway's update status: {exc}")diff --git a/tests/gateway/test_update_command.py b/tests/gateway/test_update_command.pyindex f426e93ddef..fc0569a885a 100644--- a/tests/gateway/test_update_command.py+++ b/tests/gateway/test_update_command.py@@ -5,6 +5,7 @@ the _send_update_notification startup hook (sends results after restart)."""import json+import osfrom datetime import datetime, timedeltafrom pathlib import Pathfrom unittest.mock import patch, MagicMock, AsyncMock@@ -630,3 +631,46 @@ class TestUpdateCommandInstallMethodRefusal:# No update attempt: nothing spawned, no pending marker written.mock_popen.assert_not_called()assert not (hermes_home / ".update_pending.json").exists()+++# ---------------------------------------------------------------------------+# Exit-code publication: the watcher polls .update_exit_code and reads "" as exit 1+# ---------------------------------------------------------------------------+++class TestDetachedUpdateExitCodePublication:+ """The detached wrapper never exposes an empty ``.update_exit_code`` to the 2 s watcher poll."""++ @pytest.mark.platforms("linux", "macos")+ @pytest.mark.live_system_guard_bypass # runs the wrapper around `sh -c 'exit 3'`, never hermes+ def test_bash_wrapper_never_exposes_an_empty_exit_code(self, tmp_path, monkeypatch):+ import subprocess+ from gateway.slash_commands import _spawn_detached_update++ output, marker, seen = tmp_path / "out.log", tmp_path / ".update_exit_code", tmp_path / "seen.log"+ spawned = MagicMock()+ with patch("shutil.which", return_value=None), patch("subprocess.Popen", spawned):+ _spawn_detached_update(["sh", "-c", "exit 3"], output, marker)+ # Poll the marker at the instant the wrapper's printf runs: a `printf > marker` redirect has+ # already truncated it by then (bash applies redirections before running the command).+ hook = tmp_path / "bash_env.sh"+ hook.write_text('printf() { [ -e "$MARKER" ] && echo "exists:$(cat "$MARKER")" >> "$SEEN"; '+ 'builtin printf "$@"; }\n', encoding="utf-8")+ env = {**os.environ, "BASH_ENV": str(hook), "MARKER": str(marker), "SEEN": str(seen)}+ subprocess.run(spawned.call_args[0][0], env=env, check=True, timeout=60)+ assert not seen.exists() or "exists:\n" not in seen.read_text(encoding="utf-8")+ assert marker.read_text(encoding="utf-8") == "3"++ def test_windows_helper_never_exposes_an_empty_exit_code(self, tmp_path, monkeypatch):+ import sys+ from gateway.slash_commands import _WINDOWS_UPDATE_HELPER+ from tests.file_write_observer import observe_file_writes++ output, marker = tmp_path / "out.log", tmp_path / ".update_exit_code"+ seen = []+ monkeypatch.setattr(sys, "argv", ["-c", str(output), str(marker),+ sys.executable, "-c", "raise SystemExit(4)"])+ with observe_file_writes(lambda: seen.append(marker.read_text() if marker.exists() else None)):+ exec(compile(_WINDOWS_UPDATE_HELPER, "<update-helper>", "exec"), {"__name__": "__main__"})+ assert "" not in seen+ assert marker.read_text(encoding="utf-8") == "4"diff --git a/tests/hermes_cli/test_update_exit_code_publication.py b/tests/hermes_cli/test_update_exit_code_publication.pynew file mode 100644index 00000000000..bbb1454417e--- /dev/null+++ b/tests/hermes_cli/test_update_exit_code_publication.py@@ -0,0 +1,86 @@+"""Every writer of ``.update_exit_code`` publishes it atomically.++The gateway /update watcher (gateway/run_notifications_update.py) polls ``.update_exit_code``+every 2 s from the gateway process and reads ``int(text or "1")``. A writer that truncates the+file in place left it empty for an instant; a poll landing there read exit 1, told the user the+update failed although it succeeded, and cleared the markers so no correction followed.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from tests.file_write_observer import observe_file_writes+++def _watch(marker: Path) -> tuple[list[str], object]:+ """A gateway poll at every write instant: the marker's text whenever it exists."""+ seen: list[str] = []++ def poll() -> None:+ if marker.exists():+ seen.append(marker.read_text(encoding="utf-8-sig"))++ return seen, poll+++def home(tmp_path, monkeypatch) -> Path:+ path = tmp_path / "home"+ path.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(path))+ return path+++def quiet_receipt(monkeypatch):+ from hermes_cli import update_receipt++ monkeypatch.setattr(update_receipt, "record_step", lambda *a, **k: None)+ monkeypatch.setattr(update_receipt, "finalize_pending_update_receipt", lambda *a, **k: None)+++def test_fleet_writer_never_exposes_an_empty_exit_code(home):+ from hermes_cli.update_cmd_fleet import _write_gateway_update_exit_code++ marker = home / ".update_exit_code"+ seen, poll = _watch(marker)+ with observe_file_writes(poll):+ _write_gateway_update_exit_code(True)+ assert "" not in seen+ assert marker.read_text(encoding="utf-8").strip() == "0"+++def test_completion_success_never_exposes_an_empty_exit_code(home):+ from hermes_cli.update_completion import _publish_gateway_success++ marker = home / ".update_exit_code"+ seen, poll = _watch(marker)+ with observe_file_writes(poll):+ _publish_gateway_success({"gateway_mode": True, "home": str(home)})+ assert "" not in seen+ assert marker.read_text(encoding="utf-8").strip() == "0"+++def test_takeover_failure_never_exposes_an_empty_exit_code(home, tmp_path, quiet_receipt):+ from hermes_cli._update_takeover import _record_failure++ marker = home / ".update_exit_code"+ seen, poll = _watch(marker)+ with observe_file_writes(poll):+ _record_failure({"gateway_mode": True}, tmp_path / "result.json", 3, "boom")+ assert "" not in seen+ assert marker.read_text(encoding="utf-8").strip() == "3"+++def test_takeover_owed_finish_never_exposes_an_empty_exit_code(home, tmp_path, quiet_receipt):+ from hermes_cli._update_takeover import _record_owed_finish++ marker = home / ".update_exit_code"+ seen, poll = _watch(marker)+ with observe_file_writes(poll):+ _record_owed_finish({"gateway_mode": True}, tmp_path / "result.json", "child missing")+ assert "" not in seen+ assert marker.read_text(encoding="utf-8").strip() == "0"