The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): hand-off carries sibling snapshots + Windows pause token on both paths; child pinned to the parent's home
teknium1bec892459453
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex aa099f1f496..a6f677dd113 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -576,6 +576,11 @@ def _apply_profile_override() -> None:hermes_home_env = os.environ.get("HERMES_HOME", "")if profile_name is None and hermes_home_env and Path(hermes_home_env).parent.name == "profiles":return+ # The post-swap updater child inherits the home its parent already resolved (possibly the+ # root for `-p default`); re-reading the sticky active_profile here would finish the update+ # — receipt, config migration, exit code — in another profile's home.+ if profile_name is None and hermes_home_env and os.environ.get("HERMES_UPDATE_POST_SWAP") == "1":+ returnif profile_name is None and not _under_gateway_supervisor(argv) and not _desktop_ssh_backend(argv):try:diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 759b0d8085a..816f59a85a7 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1162,7 +1162,8 @@ def _current_branch_name(git_cmd, *, check: bool = False) -> str:def _handle_update_called_process_error(- e, args, gateway_mode: bool, had_desktop_app_before_update: bool) -> None:+ e, args, gateway_mode: bool, had_desktop_app_before_update: bool,+ _windows_gateway_resume=None) -> None:"""Git/installer failure: ZIP-fallback when safe, else report and ``sys.exit(1)``."""stage = _format_update_failure_stage(e)if _should_zip_fallback_on_update_error(e):@@ -1170,7 +1171,8 @@ def _handle_update_called_process_error(print("→ Falling back to ZIP download...")print()desktop_build_ok = _update_via_zip(- args, had_desktop_app_before_update=had_desktop_app_before_update)+ args, had_desktop_app_before_update=had_desktop_app_before_update,+ _windows_gateway_resume=_windows_gateway_resume)if gateway_mode:_write_gateway_update_exit_code(desktop_build_ok)else:@@ -1311,10 +1313,20 @@ def _post_swap_payload("active_tool_dependencies": opts.active_tool_dependencies,"plan": _pre_update_plan.to_dict() if _pre_update_plan is not None else None,"windows_gateway_resume": _windows_gateway_resume,+ # {profile: snapshot_id} from the pre-update backup; the post-migration safety nets for+ # sibling profiles read it (update_cmd_config._LAST_SIBLING_SNAPSHOTS).+ "sibling_snapshots": dict(_sibling_snapshots_module()._LAST_SIBLING_SNAPSHOTS),"receipt": detach_update_receipt(),}+def _sibling_snapshots_module():+ # The backup phase REBINDS ``update_cmd_config._LAST_SIBLING_SNAPSHOTS``; read the module+ # attribute at call time, never this module's import-time copy of the empty dict.+ import hermes_cli.update_cmd_config as _cfg+ return _cfg++def _hand_off_post_swap(args, **payload_kwargs) -> None:"""Re-execute ``hermes update --post-swap`` on the pulled tree and exit with its code.@@ -1322,13 +1334,26 @@ def _hand_off_post_swap(args, **payload_kwargs) -> None:and only relays the exit code (``hermes_cli/update_handoff.py``)."""from hermes_cli.update_handoff import continue_update_in_fresh_interpreter+ from hermes_cli.update_receipt import resume_update_receiptpayload = _post_swap_payload(**payload_kwargs)- if payload["windows_gateway_resume"]:- import atexit as _atexit- with suppress(Exception):- _atexit.unregister(_m()._resume_windows_gateways_after_update)code = continue_update_in_fresh_interpreter(payload, argv_tail=_post_swap_argv_tail(args))+ token = payload_kwargs.get("_windows_gateway_resume")+ if token and code is not None:+ # The child got its own copy (serialized before this flip) and owns the resume; every+ # parent-side hook (atexit, the ZIP path's ``finally``) reads this flag and stays out+ # of the way. When no child ran, the parent still resumes what it paused.+ token["resume_needed"] = False+ if code is None:+ # No child ran: take the receipt back so this failure is recorded, and leave the+ # install breadcrumb so the next launch finishes the dependency sync (new code, old deps).+ if payload["receipt"]:+ resume_update_receipt(payload["receipt"])+ _record_update_step("post_swap_handoff", False, "child interpreter could not start")+ _m()._write_update_incomplete_marker()+ if payload_kwargs.get("gateway_mode"):+ _write_gateway_update_exit_code(False)+ code = 1sys.exit(code)@@ -1339,6 +1364,8 @@ def _run_post_swap_phase(args, gateway_mode: bool) -> None:from hermes_cli.update_receipt import resume_update_receiptpayload = read_handoff(args.post_swap)+ with suppress(OSError):+ Path(args.post_swap).unlink()if payload.get("receipt"):resume_update_receipt(payload["receipt"])_execute_post_swap(payload, args, gateway_mode)@@ -1348,8 +1375,10 @@ def _execute_post_swap(payload: dict, args, gateway_mode: bool) -> None:"""The tail ``_apply_pulled_update`` / ``_update_via_zip`` used to run in the pre-pullinterpreter, driven from a hand-off payload."""from dataclasses import replace as _replace+ import hermes_cli.update_cmd_config as _cfgfrom hermes_cli.update_inventory import UpdatePlan+ _cfg._LAST_SIBLING_SNAPSHOTS = dict(payload.get("sibling_snapshots") or {})_pre_update_plan = UpdatePlan.from_dict(payload["plan"]) if payload.get("plan") else None_windows_gateway_resume = payload.get("windows_gateway_resume")if _windows_gateway_resume:@@ -1370,11 +1399,14 @@ def _execute_post_swap(payload: dict, args, gateway_mode: bool) -> None:desktop_build_ok = _finish_zip_update(active_tool_dependencies=opts.active_tool_dependencies,pre_update_version=opts.pre_update_version,- had_desktop_app_before_update=had_desktop_app_before_update)+ had_desktop_app_before_update=had_desktop_app_before_update,+ _windows_gateway_resume=_windows_gateway_resume)if gateway_mode:_write_gateway_update_exit_code(desktop_build_ok)return- _, git_cmd, _ = _prepare_git_command()+ # The parent already ran the checkout preflight (fork banner, lockfile churn, EOL); the+ # child only needs a working git.+ git_cmd = _ensure_non_trampoline_git(_base_git_cmd())_finish_pulled_update(git_cmd, payload["branch"], payload.get("pre_pull_sha"), opts, gateway_mode=gateway_mode,is_fork=bool(payload.get("is_fork")), desktop_dir=desktop_dir,@@ -1384,7 +1416,9 @@ def _execute_post_swap(payload: dict, args, gateway_mode: bool) -> None:except _shim_quarantine_error_type() as e:_refuse_update_for_contended_shims(e)except subprocess.CalledProcessError as e:- _handle_update_called_process_error(e, args, gateway_mode, had_desktop_app_before_update)+ _handle_update_called_process_error(+ e, args, gateway_mode, had_desktop_app_before_update,+ _windows_gateway_resume=_windows_gateway_resume)def _finish_pulled_update(@@ -1505,8 +1539,11 @@ def _cmd_update_impl(args, gateway_mode: bool):if use_zip_update:try:desktop_build_ok = _update_via_zip(- args, had_desktop_app_before_update=had_desktop_app_before_update)+ args, had_desktop_app_before_update=had_desktop_app_before_update,+ _windows_gateway_resume=_windows_gateway_resume)finally:+ # No-op once the post-swap child owns the token (``resume_needed`` flipped);+ # still resumes after a pre-swap refusal (dirty tree, --branch)._m()._resume_windows_gateways_after_update(_windows_gateway_resume)if gateway_mode:_write_gateway_update_exit_code(desktop_build_ok)@@ -1586,7 +1623,9 @@ def _cmd_update_impl(args, gateway_mode: bool):# See #87331._refuse_update_for_contended_shims(e)except subprocess.CalledProcessError as e:- _handle_update_called_process_error(e, args, gateway_mode, had_desktop_app_before_update)+ _handle_update_called_process_error(+ e, args, gateway_mode, had_desktop_app_before_update,+ _windows_gateway_resume=_windows_gateway_resume)# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 62348484fa3..86cf6ef5b49 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -356,7 +356,7 @@ def _reinstall_python_deps_after_zip(active_tool_dependencies) -> None:_m()._refresh_active_memory_provider_dependencies()-def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> bool:+def _update_via_zip(args, *, had_desktop_app_before_update: bool = False, _windows_gateway_resume=None) -> bool:"""Update via ZIP archive; used on Windows when git file I/O is broken (antivirus / NTFS filterdrivers causing 'Invalid argument'). Swaps the tree, then hands the rest of the run to aninterpreter born on the new code (never returns; the child owns the receipt and exit code)."""@@ -383,11 +383,14 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boofrom dataclasses import replace as _replace_hand_off_post_swap(args, swap="zip", branch=branch, opts=_replace(opts, pre_update_version=pre_update_version),- gateway_mode=gateway_mode, had_desktop_app_before_update=had_desktop_app_before_update)+ gateway_mode=gateway_mode, had_desktop_app_before_update=had_desktop_app_before_update,+ _windows_gateway_resume=_windows_gateway_resume)return True # unreachable: _hand_off_post_swap exits with the child's code-def _finish_zip_update(*, active_tool_dependencies, pre_update_version, had_desktop_app_before_update: bool) -> bool:+def _finish_zip_update(+ *, active_tool_dependencies, pre_update_version, had_desktop_app_before_update: bool,+ _windows_gateway_resume=None) -> bool:"""Post-swap tail of the ZIP path (runs in the interpreter born on the new tree). Returns``False`` when a Desktop rebuild ran and failed."""from hermes_cli.update_cmd import (@@ -401,7 +404,7 @@ def _finish_zip_update(*, active_tool_dependencies, pre_update_version, had_desk# Reinstall Python dependencies. Prefer .[all], but if one optional extra breaks on this machine, keep# base deps and reinstall the remaining extras individually so update does not silently strip working# capabilities. See #86735.- _m()._abort_dependency_sync_if_self_locked()+ _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)print("→ Updating Python dependencies...")_reinstall_python_deps_after_zip(active_tool_dependencies)# Verify the tree imports (catches the parse-OK-but-skewed tree an interrupted copy leaves). Runsdiff --git a/hermes_cli/update_handoff.py b/hermes_cli/update_handoff.pyindex ab39c46cb48..68cc3aa7ab5 100644--- a/hermes_cli/update_handoff.py+++ b/hermes_cli/update_handoff.py@@ -90,21 +90,44 @@ def post_swap_command(handoff_path: Path, argv_tail: list[str]) -> list[str]:return [str(post_swap_python()), "-m", "hermes_cli.main", "update", *argv_tail, "--post-swap", str(handoff_path)]-def continue_update_in_fresh_interpreter(payload: dict[str, Any], *, argv_tail: list[str]) -> int:- """Run the post-swap tail in a child interpreter on the pulled code; returns its exit code.-- The parent has already detached from the receipt (the child resumes it) and only relays the- exit code. On Windows, when this process runs from ``hermes.exe``, the child cannot be- awaited: the shim is one of the files the dependency sync must replace and it stays open- for as long as this process lives (#88838, #89599). That case spawns detached, prints where- the run continues and returns 0 — the child prints its own result and ``--gateway`` writes- the true exit code to ``.update_exit_code`` exactly as before.- """+def post_swap_child_env() -> dict[str, str]:+ """Environment for the child. ``HERMES_UPDATE_REEXEC`` marks it as already off the Windows+ shim (no second re-exec at the sync boundary; ``cmd_update`` hard-exits it when its receipt+ is durable instead of waiting on a leftover non-daemon thread). The lock hand-off pid is+ only claimed when nobody upstream (Tauri/Electron updater) already named theirs."""+ from hermes_cli.main_install_repair import _UPDATE_REEXEC_ENVfrom hermes_cli.update_lock import HANDOFF_PID_ENV+ env = {**os.environ, POST_SWAP_ENV: "1", _UPDATE_REEXEC_ENV: "1"}+ env.setdefault(HANDOFF_PID_ENV, str(os.getpid()))+ return env+++def _print_manual_continuation(cmd: list[str], exc: OSError) -> None:+ logger.warning("Post-swap hand-off could not start: %s", exc)+ print(f" ⚠ Could not start the post-update interpreter: {exc}")+ print(" The code update is applied. Finish it with:")+ print(f" {subprocess.list2cmdline(cmd)}")+++def continue_update_in_fresh_interpreter(payload: dict[str, Any], *, argv_tail: list[str]) -> int | None:+ """Run the post-swap tail in a child interpreter on the pulled code.++ Returns the child's exit code, or ``None`` when no child could be started (the caller then+ owns the failure bookkeeping). The parent has already detached from the receipt (the child+ resumes it) and only relays the exit code. On Windows, when this process runs from+ ``hermes.exe``, the child cannot be awaited: the shim is one of the files the dependency+ sync must replace and it stays open for as long as this process lives (#88838, #89599).+ That case spawns detached, prints where the run continues and returns 0 — the child prints+ its own result and ``--gateway`` writes the true exit code to ``.update_exit_code``.++ Ctrl-C reaches parent and child together; the child owns the receipt and the Windows+ gateway resume, so the parent keeps waiting for it instead of ``subprocess.run``'s+ kill-on-interrupt, which would cut it off mid-cleanup.+ """handoff_path = write_handoff(payload)cmd = post_swap_command(handoff_path, argv_tail)- env = {**os.environ, POST_SWAP_ENV: "1", HANDOFF_PID_ENV: str(os.getpid())}+ env = post_swap_child_env()logger.debug("Post-swap hand-off → %s", subprocess.list2cmdline(cmd))sys.stdout.flush()sys.stderr.flush()@@ -113,23 +136,27 @@ def continue_update_in_fresh_interpreter(payload: dict[str, Any], *, argv_tail:try:subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL)except OSError as exc:- logger.debug("Detached post-swap hand-off failed: %s", exc)- print(" ⚠ Could not continue the update under the venv Python. Run it yourself:")- print(f" {subprocess.list2cmdline(cmd)}")- return 1+ _print_manual_continuation(cmd, exc)+ return Noneprint("→ Windows: hermes.exe cannot replace itself while it runs; the update")print(" continues under the venv Python. The code update is already applied and")print(" this shell returns right away; the install finishes below.")return 0try:- result = subprocess.run(cmd, env=env)+ child = subprocess.Popen(cmd, env=env, stdin=sys.stdin)except OSError as exc:- logger.warning("Post-swap hand-off could not start: %s", exc)- print(f" ⚠ Could not start the post-update interpreter: {exc}")- print(" The code update is applied. Finish it with:")- print(f" {subprocess.list2cmdline(cmd)}")- return 1- with _best_effort("Could not remove post-swap hand-off file: %s"):- handoff_path.unlink()- return int(result.returncode)+ _print_manual_continuation(cmd, exc)+ return None+ try:+ return int(child.wait())+ except KeyboardInterrupt:+ print("\n Interrupted — waiting for the update child to finish its cleanup...")+ try:+ return int(child.wait(timeout=60))+ except subprocess.TimeoutExpired:+ child.terminate()+ return 130+ except KeyboardInterrupt:+ child.terminate()+ return 130diff --git a/tests/hermes_cli/test_update_post_swap_handoff.py b/tests/hermes_cli/test_update_post_swap_handoff.pyindex 0ca4b5387b2..98358e08ef6 100644--- a/tests/hermes_cli/test_update_post_swap_handoff.py+++ b/tests/hermes_cli/test_update_post_swap_handoff.py@@ -29,41 +29,70 @@ def test_parent_reexecs_tail_on_pulled_tree_and_relays_exit_code(monkeypatch, tm"""The pre-swap interpreter runs NOTHING after the swap: it spawns ``python -m hermes_cli.mainupdate <flags> --post-swap <file>`` with the detached receipt + plan in the file and exitswith the child's code, leaving no open receipt for its own boundary to finalize."""+ import hermes_cli.update_cmd_config as cfgmonkeypatch.setattr(update_handoff, "_running_from_windows_shim", lambda: False)+ monkeypatch.delenv(HANDOFF_PID_ENV, raising=False)+ monkeypatch.setattr(cfg, "_LAST_SIBLING_SNAPSHOTS", {"work": "snap-w"})spawned = {}- def fake_run(cmd, env=None, **kwargs):+ def fake_popen(cmd, env=None, **kwargs):spawned["cmd"], spawned["env"] = cmd, envspawned["payload"] = json.loads(open(cmd[cmd.index("--post-swap") + 1], encoding="utf-8").read())- return SimpleNamespace(returncode=7)+ return SimpleNamespace(wait=lambda timeout=None: 7)- monkeypatch.setattr(update_handoff.subprocess, "run", fake_run)+ monkeypatch.setattr(update_handoff.subprocess, "Popen", fake_popen)update_receipt._current = Noneupdate_receipt.begin_update_receipt()update_receipt.record_step("pre_update_backup", True, "snapshot=s1")plan = UpdatePlan(expected_sha="a" * 40, runtimes=[RuntimeRecord(kind="gateway", profile="default", pid=4, code_sha="a" * 40)])args = SimpleNamespace(yes=True, no_gateway_restart=True, branch="main", gateway=False)+ token = {"resume_needed": True, "profiles": {"default": 4}}with pytest.raises(SystemExit) as exit_info:update_cmd._hand_off_post_swap(args, swap="git", branch="main", pre_pull_sha="a" * 40, is_fork=False, opts=_opts(),gateway_mode=False, had_desktop_app_before_update=True, pre_update_snapshot_id="s1",- _pre_update_plan=plan, _windows_gateway_resume=None)+ _pre_update_plan=plan, _windows_gateway_resume=token)assert exit_info.value.code == 7assert spawned["cmd"][:4] == [sys.executable, "-m", "hermes_cli.main", "update"]assert spawned["cmd"][4:] == ["--yes", "--no-gateway-restart", "--branch", "main", "--post-swap", spawned["cmd"][-1]]- assert spawned["env"][update_handoff.POST_SWAP_ENV] == "1"- assert spawned["env"][HANDOFF_PID_ENV] == str(os.getpid())+ env = spawned["env"]+ assert env[update_handoff.POST_SWAP_ENV] == "1" and env["HERMES_UPDATE_REEXEC"] == "1"+ assert env[HANDOFF_PID_ENV] == str(os.getpid())payload = spawned["payload"]assert payload["receipt"]["steps"][0]["name"] == "pre_update_backup"assert payload["plan"]["runtimes"][0]["profile"] == "default"assert payload["pre_update_version"] == "0.21.3" and payload["pre_pull_sha"] == "a" * 40+ assert payload["sibling_snapshots"] == {"work": "snap-w"}+ # The child owns the Windows resume: its copy still says resume_needed, the parent's does not.+ assert payload["windows_gateway_resume"]["resume_needed"] is True and token["resume_needed"] is False# Detached: the parent's command-boundary finalize is a no-op — the child writes the receipt.assert update_receipt._current is Noneassert update_receipt.finalize_pending_update_receipt(7) is None[email protected]_post_swap_handoff+def test_parent_records_failure_when_child_cannot_start(monkeypatch, tmp_path):+ """No child → the parent takes the receipt back (a pulled update must leave a record), drops+ the install breadcrumb for the next launch and exits 1."""+ monkeypatch.setattr(update_handoff, "_running_from_windows_shim", lambda: False)+ monkeypatch.setattr(update_handoff.subprocess, "Popen", lambda *a, **k: (_ for _ in ()).throw(OSError("no python")))+ marker = {}+ monkeypatch.setattr(update_cmd._m(), "_write_update_incomplete_marker", lambda: marker.setdefault("written", True))+ update_receipt._current = None+ update_receipt.begin_update_receipt()++ with pytest.raises(SystemExit) as exit_info:+ update_cmd._hand_off_post_swap(+ SimpleNamespace(), swap="git", branch="main", opts=_opts(), gateway_mode=False,+ had_desktop_app_before_update=False)++ assert exit_info.value.code == 1 and marker == {"written": True}+ assert [s["name"] for s in update_receipt._current.data["steps"]] == ["post_swap_handoff"]+ update_receipt._current = None++def test_child_resumes_receipt_and_runs_git_tail_from_payload(monkeypatch, tmp_path):started = "2026-09-16T15:57:48+00:00"handoff = tmp_path / "post_swap.json"@@ -72,12 +101,15 @@ def test_child_resumes_receipt_and_runs_git_tail_from_payload(monkeypatch, tmp_p"gateway_mode": False, "had_desktop_app_before_update": True, "pre_update_snapshot_id": "s1","pre_update_version": "0.21.3", "active_lazy_features": ["voice"], "active_tool_dependencies": {},"plan": UpdatePlan(expected_sha="a" * 40, runtimes=[RuntimeRecord(kind="gateway", profile="work", pid=9)]).to_dict(),- "windows_gateway_resume": None,+ "windows_gateway_resume": None, "sibling_snapshots": {"work": "snap-w"},"receipt": {"schema": 1, "started_at": started, "outcome": "running", "steps": [{"name": "pre_update_backup", "ok": True}],"skips": [], "gateway_restart": {}, "fleet": [], "pre_update": {"sha": "a" * 40}, "argv": ["hermes", "update"]},}), encoding="utf-8")+ import hermes_cli.update_cmd_config as cfgseen = {}- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (False, ["git"], True))+ monkeypatch.setattr(cfg, "_LAST_SIBLING_SNAPSHOTS", {})+ monkeypatch.setattr(update_cmd, "_base_git_cmd", lambda: ["git"])+ monkeypatch.setattr(update_cmd, "_ensure_non_trampoline_git", lambda cmd: cmd)monkeypatch.setattr(update_cmd, "_finish_pulled_update", lambda *a, **kw: seen.update(args=a, kw=kw))monkeypatch.setattr(update_cmd, "_resolve_update_options", lambda args, gateway_mode: update_cmd._UpdateOptions(active_lazy_features=None, active_tool_dependencies=None, pre_update_version="NEW", gw_input_fn=None,@@ -96,4 +128,6 @@ def test_child_resumes_receipt_and_runs_git_tail_from_payload(monkeypatch, tmp_pplan = seen["kw"]["_pre_update_plan"]assert isinstance(plan, UpdatePlan) and isinstance(plan.runtimes[0], RuntimeRecord)assert plan.runtimes[0].profile == "work" and seen["kw"]["is_fork"] is True+ assert cfg._LAST_SIBLING_SNAPSHOTS == {"work": "snap-w"}+ assert not handoff.exists() # consumed: nothing left to leakupdate_receipt._current = None