The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a dependency sync that fails after the tree moved is a follow-up (A6); Ctrl-C says the code moved
Teknium8e59e0ec2031
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 38eef9c3092..dd292ba496b 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -739,13 +739,28 @@ def _complete_source_update(request: dict | None) -> None:# A head capture that came back empty must not arm an SHA-less record: it names no code the# fleet can be proven current on, so the warning could never clear (#125952)._write_fleet_restart_pending_marker(expected_sha=request.get("expected_sha") or _current_checkout_sha() or "")- result = run_completion(request)+ try:+ result = run_completion(request)+ except KeyboardInterrupt as interrupt:+ # Ctrl-C after the commit point: the tree is new, so the run is interrupted, never "failed".+ _completion_receipt.finalize_interrupted_update_receipt("KeyboardInterrupt: interrupted after the code was updated")+ raise SystemExit(130) from interrupt_accept_completion_pm_receipt(result.get("pm_receipt"), request["receipt"]["update_id"])token = request["windows_resume"]if token is not None and result.get("windows_resume") is not None:resumed = dict(result["windows_resume"])token.clear()token.update(resumed)+ elif token and token.get("resume_needed") and not result["exit_code"]:+ # Dependencies owed (A6): the bootstrap child cannot resume paused gateways; this process can.+ try:+ _m()._resume_windows_gateways_after_update(token)+ except Exception as exc: # noqa: BLE001 — the code is committed (C3)+ from hermes_cli.update_receipt import amend_terminal_followup, record_followup++ reason = f"Windows gateway recovery failed: {exc}"+ record_followup("windows_resume", reason)+ amend_terminal_followup(request["receipt"]["update_id"], "windows_resume", reason)if result.get("receipt") is not None:current = _completion_receipt._current.get()if current is not None:diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex d3732b72440..91325ce8975 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -26,11 +26,11 @@ def _exit_status(code: int) -> int:return code if code >= 0 else 128 - code-def _failed_result(request: dict, result_path: Path, code: int) -> int:- code = _exit_status(code) or 1+def _write_bootstrap_result(request: dict, result_path: Path, code: int, receipt: dict | None) -> int:+ """The bootstrap child's answer; windows_resume stays the parent's token (and its atexit net)."""_write_json(result_path, {"schema": 1, "update_id": request["receipt"]["update_id"], "exit_code": code,- "receipt": None, "windows_resume": None, "pm_receipt": request.get("pm_receipt"),+ "receipt": receipt, "windows_resume": None, "pm_receipt": request.get("pm_receipt"),})return code@@ -144,6 +144,51 @@ def _read_terminal_receipt(request: dict) -> dict | None:return None+def _running_record(request: dict) -> dict | None:+ from hermes_cli.update_receipt import _receipt_dir++ for path in _receipt_dir().glob(f"update_*_{request['receipt']['update_id']}.json"):+ try:+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ continue+ if data.get("update_id") == request["receipt"]["update_id"] and data.get("outcome") == "running":+ data.pop("writer_pid", None)+ return data+ return None+++def _settle_after_commit(request: dict, result_path: Path, step: str, reason: str) -> int:+ """The tree already moved, so a failure here is owed work, never a failed update (C3, A6).++ Runs in the bootstrap interpreter (stdlib + the new tree) when dependency preparation failed or+ the prepared child died without a result. The tail obligation stays armed, so the next launch+ syncs the dependencies and finishes the tail; the run's receipt is a success that names the+ follow-up, so nothing reports "still on the previous version" while the tree is new.+ """+ from hermes_cli import update_receipt+ from hermes_cli.venv_sync import arm_completion++ try:+ arm_completion(Path(request["source"]))+ except OSError as exc: # the next launch still sees stale dependencies and syncs them+ print(f" ⚠ Could not record the owed source-update tail: {exc}")+ receipt = _read_terminal_receipt(request) # a prepared child that finalized, then died+ if receipt is None:+ # A prepared child that died mid-tail persisted stages the parent's snapshot lacks.+ _resume_receipt(_running_record(request) or request["receipt"])+ update_receipt.record_stage("deps" if step == "dependencies" else "build", "failed")+ update_receipt.record_followup(step, reason, retry="dependencies not installed yet — the next launch retries"+ if step == "dependencies" else "the next launch or `hermes update` retries it")+ update_receipt.finalize_pending_update_receipt(0, f"{step} owed after the code was updated")+ receipt = _read_terminal_receipt(request)+ code = 0 if receipt is not None and receipt.get("outcome") == "success" else 1+ if code == 0 and request["gateway_mode"]:+ # The gateway's /update watcher reads this; the code is committed (same as _complete_selected).+ (Path(request["home"]) / ".update_exit_code").write_text("0", encoding="utf-8")+ return _write_bootstrap_result(request, result_path, code, receipt)++def _prepare(request: dict, request_path: Path, result_path: Path) -> int:import pmfrom pm import receipt@@ -179,7 +224,8 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:# and dependency graph. No application maintenance runs in this bootstrap.code = _exit_status(subprocess.call(command, cwd=root, env=activation_environment(root)))if not result_path.exists():- return _failed_result(request, result_path, code)+ return _settle_after_commit(request, result_path, "completion",+ f"the completion process exited {code} without a result")return code@@ -273,9 +319,10 @@ def _finish(request: dict, result_path: Path) -> int:try:_complete_selected(request)except KeyboardInterrupt:- # An operator interrupt is not a step failure; the armed obligations finish the tail.- code, reason = 1, "KeyboardInterrupt: completion interrupted"- print("✗ Source update completion interrupted; the next launch or `hermes update` finishes it")+ # An operator interrupt is not a step failure, and the code already moved: the run is+ # ``interrupted`` (never "failed"), and the armed obligations finish the tail.+ code, reason = 130, "KeyboardInterrupt: interrupted after the code was updated"+ update_receipt.finalize_interrupted_update_receipt(reason, exit_code=code)except SystemExit as exc:if exc.code not in (0, None):update_receipt.record_followup("completion", f"completion exited {exc.code}")@@ -323,14 +370,23 @@ def main() -> int:from pm.environments import activate_dependenciesactivate_dependencies(root)return _finish(request, result_path)+ return _bootstrap(request, request_path, result_path)+++def _bootstrap(request: dict, request_path: Path, result_path: Path) -> int:+ """Dependency preparation in the parent's interpreter; its failure is a follow-up (A6)."""try:return _prepare(request, request_path, result_path)- except BaseException as exc:- # PM failed before application dependencies were ready. Leave the parent- # receipt and paused-gateway obligation intact for boundary recovery.- print(f"✗ Source update preparation failed: {exc}")- code = exc.returncode if isinstance(exc, subprocess.CalledProcessError) else 1- return _failed_result(request, result_path, code)+ except KeyboardInterrupt:+ _resume_receipt(request["receipt"])+ from hermes_cli import update_receipt+ update_receipt.finalize_interrupted_update_receipt(+ "KeyboardInterrupt: interrupted while installing dependencies", exit_code=130)+ return _write_bootstrap_result(request, result_path, 130, _read_terminal_receipt(request))+ except (Exception, SystemExit) as exc: # noqa: BLE001 — after the commit point nothing fails the update+ # The code is committed but its dependencies are not (A6): an owed follow-up, exit 0.+ # Paused Windows gateways stay the parent's to resume (it has the dependencies).+ return _settle_after_commit(request, result_path, "dependencies", str(exc) or type(exc).__name__)if __name__ == "__main__":diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex 1f479bc5280..d00a0473bea 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -310,7 +310,7 @@ def persist_running_receipt() -> None:#: Follow-up steps whose failure leaves the source-update tail owed (``source-completion-pending``).-TAIL_FOLLOWUPS = frozenset({"launchers", "build", "maintenance", "config_migration", "completion"})+TAIL_FOLLOWUPS = frozenset({"dependencies", "launchers", "build", "maintenance", "config_migration", "completion"})def record_followup(step: str, reason: str, *, retry: str = "the next launch or `hermes update` retries it") -> None:@@ -574,6 +574,36 @@ def finalize_pending_update_receipt(exit_code: Optional[int] = None, stop_reasonreturn finalize_update_receipt(outcome, stop_reason=stop_reason)+def finalize_interrupted_update_receipt(stop_reason: str, *, exit_code: int = 130) -> Optional[Path]:+ """Close a run the operator interrupted AFTER the commit point as ``interrupted``. Never raises.++ Not ``failed``: the code already moved, so "still on the previous version" would be false; the+ armed obligations finish the rest. The run's own on-disk record is preferred when it is further+ along (the completion child persisted stages this process never saw).+ """+ print("⚠ Interrupted after the code was updated: the new code is in place; its remaining steps are owed "+ "and the next launch or `hermes update` finishes them.", flush=True)+ current = _current.get()+ if current is None:+ return None+ with suppress(Exception):+ clone = copy.copy(current)+ clone.data = copy.deepcopy(current.data)+ on_disk: dict = {}+ with suppress(Exception):+ path = _run_file(_receipt_dir(), current.data)+ on_disk = json.loads(path.read_text(encoding="utf-8-sig"))+ if on_disk.get("update_id") == current.data.get("update_id"):+ if on_disk.get("finished_at"): # the completion child already closed the run+ _current.reset(current.current_token)+ return path+ on_disk.pop("writer_pid", None)+ clone.data = on_disk+ clone.data["exit_code"] = int(exit_code)+ _current.set(clone)+ return finalize_update_receipt("interrupted", stop_reason=stop_reason)++def _prune_old_receipts(directory: Path) -> None:with suppress(Exception):receipts = (p for p in directory.glob("update_*.json") if p.is_file())diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.pyindex 8fef6c7e600..747d014f41c 100644--- a/tests/hermes_cli/test_update_completion_process.py+++ b/tests/hermes_cli/test_update_completion_process.py@@ -156,7 +156,7 @@ def transition(tmp_path):"class UpdateReceipt: pass\n""def record_stage(*args, **kwargs): pass\n""def record_skip(*args, **kwargs): pass\n"- "TAIL_FOLLOWUPS = frozenset({'launchers', 'build', 'maintenance', 'config_migration', 'completion'})\n"+ "TAIL_FOLLOWUPS = frozenset({'dependencies', 'launchers', 'build', 'maintenance', 'config_migration', 'completion'})\n""def record_followup(step, reason, **kwargs):\n"" print(f' ⚠ Update follow-up {step!r} did not finish: {reason}')\n"" r = _current.get()\n"@@ -343,21 +343,28 @@ def test_interrupt_after_child_success_demotes_gateway_marker_at_boundary(transimonkeypatch.setattr(subprocess, "Popen", capture_child)update_cmd._complete_source_update(request)- monkeypatch.setattr(sys, "stdout", Interrupt())+ stdout = Interrupt()+ monkeypatch.setattr(sys, "stdout", stdout)monkeypatch.setattr(update_cmd, "_cmd_update_impl", complete)- with pytest.raises(KeyboardInterrupt) as error:+ # Was KeyboardInterrupt + a ``failed`` receipt: Ctrl-C after the commit point is an interrupt+ # (exit 130), and the receipt keeps the truth the child already wrote (C3, item 5).+ with pytest.raises(SystemExit) as error:main.cmd_update(SimpleNamespace(gateway=True))+ assert error.value.code == 130assert interrupted, "child never published success before cancellation"assert children[0].poll() is not Noneassert children[0].stdout.closedassert waits and all(timeout is not None and timeout > 0 for timeout in waits)+ assert isinstance(error.value.__cause__, KeyboardInterrupt)if cleanup_failure:- assert error.value.__cause__ is cleanup_error+ assert error.value.__cause__.__cause__ is cleanup_error+ assert "Interrupted after the code was updated" in stdout.getvalue()receipt = update_receipt.read_latest_receipt()assert receipt["update_id"] == request["receipt"]["update_id"]- assert receipt["outcome"] == "failed"- assert receipt["exit_code"] == 1+ assert receipt["outcome"] == "interrupted" # the child was stopped before it closed the run+ assert receipt["exit_code"] == 130assert receipt["stop_reason"].startswith("KeyboardInterrupt:")+ # The gateway watcher still hears the interrupt (a non-zero exit is fine for Ctrl-C).assert marker.read_text().strip() == "1"lock = update_lock.UpdateLock()assert lock.acquire()@@ -375,7 +382,12 @@ def test_killed_selected_python_returns_signal_exit_status(transition):"def build_update_products(*a, **kw): os.kill(os.getpid(), signal.SIGKILL)\n")result = update_completion.run_completion(request)- assert result["exit_code"] == 137+ # Was 137: the tree already moved, so a prepared child that dies without a result is an owed+ # ``completion`` follow-up (C3/A6), the tail obligation armed for the next launch.+ assert result["exit_code"] == 0+ assert result["receipt"]["outcome"] == "success"+ assert [f["step"] for f in result["receipt"]["followups"]] == ["completion"]+ assert "exited 137" in result["receipt"]["followups"][0]["reason"]assert result["pm_receipt"]["update_id"] == request["receipt"]["update_id"]@@ -410,9 +422,8 @@ def test_failed_build_after_commit_is_a_followup_and_later_steps_still_run(transif json.loads(line)["name"] == "exit_marker").items()-def test_prepare_failure_preserves_correlated_pm_receipt(transition, monkeypatch):- from types import SimpleNamespace- from hermes_cli import main, update_cmd, update_completion, update_receipt+def test_prepare_failure_preserves_correlated_pm_receipt(transition):+ from hermes_cli import update_completionroot, git, old, new, request = transitionshutil.copy2(update_completion.__file__, root / "hermes_cli/update_completion.py")@@ -421,24 +432,17 @@ def test_prepare_failure_preserves_correlated_pm_receipt(transition, monkeypatch)with (root / "pm/receipt.py").open("a") as stream:stream.write("last_for_update = lambda update_id: {'update_id': update_id, 'outcome': 'refused', 'refusal': {'reason': 'dependency refused'}}\n")- monkeypatch.setenv("HERMES_HOME", request["home"])- 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 complete(args, gateway_mode):- update_receipt.begin_update_receipt()- request["receipt"] = update_receipt._current.get().data- update_cmd._complete_source_update(request)-- monkeypatch.setattr(update_cmd, "_cmd_update_impl", complete)- with pytest.raises(SystemExit) as error:- main.cmd_update(SimpleNamespace(gateway=True))- assert error.value.code == 1- receipt = update_receipt.read_latest_receipt()- assert receipt["update_id"] == request["receipt"]["update_id"]- assert receipt["pm_sync_outcome"] == "refused"- assert receipt["pm_refusal"] == {"reason": "dependency refused"}+ result = update_completion.run_completion(request)+ # Was exit 1 / no receipt: the dependency sync runs after the tree moved, so its failure is a+ # ``dependencies`` follow-up (A6) with the tail obligation armed — and the correlated pm+ # refusal still travels back for the receipt.+ assert result["exit_code"] == 0+ assert result["receipt"]["outcome"] == "success"+ assert [f["step"] for f in result["receipt"]["followups"]] == ["dependencies"]+ assert "dependency refused" in result["receipt"]["followups"][0]["reason"]+ assert (Path(request["home"]) / "completion-pending").read_text() == "owed"+ assert result["pm_receipt"] == {"update_id": request["receipt"]["update_id"], "outcome": "refused",+ "refusal": {"reason": "dependency refused"}}def test_bootstrap_does_not_initialize_old_site_packages(transition, tmp_path, monkeypatch):diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.pyindex d284761ecbd..d7417177170 100644--- a/tests/hermes_cli/test_update_fleet_restart_pending.py+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py@@ -559,9 +559,11 @@ def test_interrupt_between_pull_and_restart_leaves_marker(monkeypatch.setattr(hermes_main, "_clear_bytecode_cache", _interrupt)- with pytest.raises(KeyboardInterrupt):+ # Was KeyboardInterrupt: Ctrl-C after the commit point exits 130 as an interrupt, not a failure.+ with pytest.raises(SystemExit) as exc:hermes_main.cmd_update(args)+ assert exc.value.code == 130assert update_cmd_fleet._fleet_restart_obligation_armed()record = json.loads(host_obligation.host_obligation_path().read_text(encoding="utf-8"))assert record["expected_sha"] == "def456"diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.pyindex 6f990d8feef..514179e00ad 100644--- a/tests/hermes_cli/test_update_zip_completion.py+++ b/tests/hermes_cli/test_update_zip_completion.py@@ -273,6 +273,75 @@ def test_zip_build_failure_after_swap_is_a_followup(zip_update, monkeypatch, rouassert state.token["resume_needed"] is False[email protected]("route", ["direct", "git-failure"])+def test_zip_dependency_sync_failure_after_swap_is_a_followup(zip_update, monkeypatch, tmp_path, route):+ # The dropped "preparation" case, restored at the real seam: PM's dependency sync in the+ # completion bootstrap fails AFTER the swap. Was pm.InstallError / exit 1 / no receipt, which+ # the Desktop reads as "still on the previous version" while the tree is new. Contract C3/A6:+ # exit 0, a ``dependencies`` follow-up, the tail obligation armed, nothing of the tail run.+ import pm+ import pm.client+ from hermes_cli import update_completion+ from hermes_cli.venv_sync import completion_pending_path++ state = zip_update+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))+ monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)+ monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True)++ def fail_fetch(*args, **kwargs):+ raise subprocess.CalledProcessError(1, ["git", "fetch"])+ monkeypatch.setattr(update_cmd, "_git_run", fail_fetch)+ monkeypatch.setattr(pm.client, "ensure_tools_for_sync", lambda: None)++ def fail_sync(*args, **kwargs):+ assert (state.root / "payload.txt").read_text() == "new"+ raise pm.InstallError("venv", "dependency sync stopped")+ monkeypatch.setattr(pm, "sync_venv", fail_sync)++ def bootstrap(request): # the completion child's first interpreter, in-process+ request = {**request, "bytecode_cache": str(tmp_path / "bytecode")}+ request_path, result_path = tmp_path / "request.json", tmp_path / "result.json"+ update_completion._write_json(request_path, request)+ update_completion._bootstrap(request, request_path, result_path)+ return json.loads(result_path.read_text())+ monkeypatch.setattr(update_cmd, "run_completion", bootstrap)++ update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=True)++ assert (state.root / "payload.txt").read_text() == "new"+ receipt = json.loads((state.active / "logs/update_receipts/latest.json").read_text())+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt["followups"]] == ["dependencies"]+ assert completion_pending_path(state.root).is_file() # the next launch syncs and finishes the tail+ assert "prepare" not in state.events # no build/maintenance ran against stale dependencies+ assert (state.active / ".update_exit_code").read_text() == "0"+ assert "resume" in state.events and state.token["resume_needed"] is False+++def test_ctrl_c_after_the_swap_reports_the_new_code_not_a_failure(zip_update, monkeypatch, capsys):+ # Ctrl-C while the completion child runs: run_completion kills the child group and re-raises.+ # The tree is new, so the run is ``interrupted`` (never "failed" / "still on the previous+ # version") and the message says what is owed; a non-zero exit for an interrupt is fine.+ state = zip_update+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (True, ["git"], False))+ monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)++ def interrupted(request):+ assert (state.root / "payload.txt").read_text() == "new"+ raise KeyboardInterrupt+ monkeypatch.setattr(update_cmd, "run_completion", interrupted)++ with pytest.raises(SystemExit) as exc:+ update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=False)++ assert exc.value.code == 130+ assert "Interrupted after the code was updated: the new code is in place" in capsys.readouterr().out+ receipt = json.loads((state.active / "logs/update_receipts/latest.json").read_text())+ assert receipt["outcome"] == "interrupted" and receipt["exit_code"] == 130+ assert (state.root / "payload.txt").read_text() == "new"++@pytest.mark.parametrize("entry", ["payload.txt", "tools"])def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, monkeypatch, entry):import shutil