The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(updater): recover deferred installs on update retry
fangliquanflq8f5e5e49a2f5
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 910f8566c39..11f0f0ce64e 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -61,6 +61,67 @@ def _project_root() -> Path:return Path(__file__).resolve().parent.parent+def _pid_is_running(pid: int) -> bool:+ """Best-effort stdlib-only process liveness probe.++ ``os.kill(pid, 0)`` is not a no-op on Windows, so use the Win32 process+ handle API there. An access-denied result is conservatively live: racing+ an elevated updater is worse than postponing recovery for one launch.+ """+ if pid <= 0:+ return False+ if sys.platform == "win32":+ try:+ import ctypes++ synchronize = 0x00100000+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.argtypes = [+ ctypes.c_ulong,+ ctypes.c_int,+ ctypes.c_ulong,+ ]+ kernel32.OpenProcess.restype = ctypes.c_void_p+ kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ kernel32.WaitForSingleObject.restype = ctypes.c_ulong+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]+ kernel32.CloseHandle.restype = ctypes.c_int+ handle = kernel32.OpenProcess(synchronize, False, pid)+ if not handle:+ return ctypes.get_last_error() == 5 # ERROR_ACCESS_DENIED+ try:+ return kernel32.WaitForSingleObject(handle, 0) == 258+ finally:+ kernel32.CloseHandle(handle)+ except Exception:+ return True+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ except OSError:+ return False+ return True+++def _marker_owner_is_live(marker: Path) -> bool:+ """True when a legacy update marker names a process still running."""+ try:+ body = marker.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return False+ for line in body.splitlines():+ key, separator, value = line.partition("=")+ if separator and key.strip() == "pid":+ try:+ return _pid_is_running(int(value.strip()))+ except ValueError:+ return False+ return False++def _pinned_specs(packages: list[str], project_root: Path) -> list[str]:"""Map bare package names to their pinned specs from pyproject.toml.@@ -293,10 +354,6 @@ def recover_if_needed("""try:args = sys.argv[1:] if argv is None else argv- # Same deliberately-loose match as main(): the real update flow writes- # and clears its own markers — a recovery install must not race it.- if "update" in args:- returnroot = _project_root() if project_root is None else project_rootif _pytest_owns_live_checkout(root):return@@ -319,10 +376,23 @@ def recover_if_needed(# every launch, so attempts past the ceiling are left for main.py's# post-import recovery path (which can safely probe-import after this# process already holds whatever extensions it needs).+ # A live marker owner means another updater is currently inside the+ # marker-to-install window. Never race it. A dead owner means this is+ # a prior deferral/interruption and MUST be recovered even when this+ # launch is itself `hermes update`: CLI and Desktop retries preserve+ # that argv, and skipping solely on argv recreates the self-lock loop.if core_marker.exists():+ if _marker_owner_is_live(core_marker):+ return_complete_pending_core_install(root, core_marker)return+ # Keep the historical update-argv exclusion for the lazy-refresh+ # marker. Unlike the core marker it is not a deferred native install,+ # and the active update flow owns its probe/repair lifecycle.+ if "update" in args:+ return+broken = _probe_broken_packages()if not broken:# Imports are fine — main.py will load and run full recovery.diff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.pyindex d7f66882542..09de7cad1e6 100644--- a/tests/hermes_cli/test_early_recovery.py+++ b/tests/hermes_cli/test_early_recovery.py@@ -142,6 +142,24 @@ def test_early_recovery_module_is_stdlib_only(tmp_path):# recover_if_needed unit behavior# ---------------------------------------------------------------------------++def test_pid_liveness_recognizes_current_process():+ assert er._pid_is_running(os.getpid()) is True+ assert er._pid_is_running(0) is False+++def test_marker_owner_liveness_uses_recorded_pid(tmp_path, monkeypatch):+ marker = tmp_path / ".update-incomplete"+ marker.write_text("started=1\npid=4321\n", encoding="utf-8")+ seen = []+ monkeypatch.setattr(+ er, "_pid_is_running", lambda pid: seen.append(pid) or True+ )++ assert er._marker_owner_is_live(marker) is True+ assert seen == [4321]++def _project(tmp_path: Path, *, pyproject: bool = True) -> Path:root = tmp_path / "proj"root.mkdir(exist_ok=True)@@ -453,11 +471,38 @@ def test_lazy_marker_alone_does_not_trigger_core_install(tmp_path, monkeypatch):er.recover_if_needed(project_root=root, argv=[])-def test_core_marker_skipped_when_user_is_running_update(tmp_path, monkeypatch):- """A launch of `hermes update` itself must not race its own markers."""+def test_core_marker_from_dead_updater_is_recovered_on_update_retry(+ tmp_path, monkeypatch+):+ """Retrying ``hermes update`` must consume a prior deferral marker.++ The self-lock preflight exits after writing this marker. Desktop and CLI+ retries both keep ``update`` in argv, so an argv-only skip loops forever.+ """root = _project(tmp_path)core_marker = root / ".update-incomplete"- core_marker.write_text('{"attempts": 0}', encoding="utf-8")+ core_marker.write_text("started=1\npid=1234\n", encoding="utf-8")++ from hermes_cli import _install_repair as ir++ calls = []+ monkeypatch.setattr(ir, "run_core_install", lambda project_root: calls.append(project_root))+ monkeypatch.setattr(er, "_marker_owner_is_live", lambda _marker: False, raising=False)+ import hermes_cli._install_repair # noqa: F401++ er.recover_if_needed(project_root=root, argv=["update"])++ assert calls == [root]+ assert not core_marker.exists()+++def test_core_marker_owned_by_live_updater_is_not_recovered(+ tmp_path, monkeypatch+):+ """A second launch must not reinstall into an active updater's venv."""+ root = _project(tmp_path)+ core_marker = root / ".update-incomplete"+ core_marker.write_text("started=1\npid=1234\n", encoding="utf-8")from hermes_cli import _install_repair as ir@@ -465,12 +510,14 @@ def test_core_marker_skipped_when_user_is_running_update(tmp_path, monkeypatch):ir,"run_core_install",lambda _r: (_ for _ in ()).throw(- AssertionError("install must not run for `hermes update` argv")+ AssertionError("must not race a live updater")),)+ monkeypatch.setattr(er, "_marker_owner_is_live", lambda _marker: True, raising=False)import hermes_cli._install_repair # noqa: F401- er.recover_if_needed(project_root=root, argv=["update"])+ er.recover_if_needed(project_root=root, argv=[])+assert core_marker.exists()