The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): restore the retired old-updater shims the main merge overwrote
ethernetcdf48a1fd27d
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 1433eb36a0b..dedd0f25157 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -720,59 +720,13 @@ def _norm_exe(path) -> str:def _detect_concurrent_hermes_instances(scripts_dir: Path, *, exclude_pid: int | None = None) -> list[tuple[int, str]]:- """``(pid, name)`` of other live processes whose .exe is one of our entry-point shims.+ """Historical main export: stop old updaters without scanning live shims.- Windows blocks DELETE/REPLACE on a running .exe, so a Desktop-spawned ``hermes.EXE`` makes- the update's quarantine rename fail with ``[WinError 32]``. Excludes our PID and every- *shim* ancestor (the setuptools launcher is a separate native process from its- ``python.exe``); ``proc.parents()`` at once because a per-hop loop bailed on the first- AccessDenied. Empty off-Windows / without psutil. Never raises.+ PM stages a fresh generation instead of replacing a mapped hermes.exe.+ Returning an empty list would let old callers continue into that mutation."""- from hermes_cli.main_install_repair import _hermes_exe_shims, _is_windows-- if not _is_windows():- return []- try:- import psutil- except Exception:- return []- shim_paths = {_norm_exe(shim) for shim in _hermes_exe_shims(scripts_dir)}- if not shim_paths:- return []- seed = int(exclude_pid) if exclude_pid is not None else os.getpid()- exclude_pids: set[int] = {seed}- # Broad ``except Exception`` guards against partially-stubbed psutil in unit tests; this helper is- # documented as "never raises". Only the per-ancestor exe()/pid reads skip that ancestor; anything- # else aborts the whole walk (BASE semantics).- try:- for ancestor in psutil.Process(seed).parents():- try:- anc_exe = ancestor.exe()- except Exception:- continue- if not anc_exe:- continue- if _norm_exe(anc_exe) in shim_paths:- try:- exclude_pids.add(int(ancestor.pid))- except Exception:- continue- except Exception:- pass- matches: list[tuple[int, str]] = []- try:- proc_iter = psutil.process_iter(["pid", "exe", "name"])- except Exception:- return []- for proc in proc_iter:- try:- info = proc.info- except Exception:- continue- pid, exe = info.get("pid"), info.get("exe")- if exe and pid is not None and pid not in exclude_pids and _norm_exe(exe) in shim_paths:- matches.append((int(pid), str(info.get("name") or Path(exe).name)))- return matches+ from hermes_cli._old_updater import stop_for_relaunch+ stop_for_relaunch()def _is_desktop_local_serve_cmdline(command: str) -> bool:@@ -1012,3 +966,4 @@ def _reap_orphaned_desktop_local_serves(with contextlib.suppress(Exception):print(f"⟲ Reaped {len(killed)} orphaned desktop-local serve backend(s) ({reason}): {killed or matched}")return {"matched": matched, "killed": killed, "failed": failed}+diff --git a/hermes_cli/psutil_android.py b/hermes_cli/psutil_android.pyindex 4bb0df83599..4a85c73a728 100644--- a/hermes_cli/psutil_android.py+++ b/hermes_cli/psutil_android.py@@ -1,47 +1,24 @@-"""Helpers for the temporary psutil-on-Android compatibility installer."""--from __future__ import annotations+"""Shims to stop the old updater doing work until relaunch, not Android support."""from pathlib import Path+from typing import NoReturn-from hermes_cli.archive_safe import safe_extract_targz+from hermes_cli._old_updater import stop_for_relaunch-# Pinned to a version whose marker line patches cleanly; bump when upstream changes its shape.+# Frozen data for old imports, not a download performed by this module.PSUTIL_URL = ("https://files.pythonhosted.org/packages/aa/c6/"- "d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz"+ "d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/"+ "psutil-7.2.2.tar.gz")-MARKER = 'LINUX = sys.platform.startswith("linux")'-REPLACEMENT = 'LINUX = sys.platform.startswith(("linux", "android"))'--class PsutilAndroidInstallError(RuntimeError):- """Raised when the pinned psutil sdist is missing or unsafe."""+def prepare_patched_psutil_sdist(archive: Path, destination: Path) -> NoReturn:+ # Shim to stop the old updater doing work until relaunch. Extract nothing.+ stop_for_relaunch()-def prepare_patched_psutil_sdist(archive: Path, destination: Path) -> Path:- """Safely extract the pinned psutil sdist and patch it for Android."""- try:- safe_extract_targz(archive, destination) # rejects traversal, links and device nodes- except ValueError as exc:- raise PsutilAndroidInstallError(str(exc)) from exc- src_roots = [path for path in destination.iterdir() if path.is_dir() and path.name.startswith("psutil-")]- if not src_roots:- raise PsutilAndroidInstallError("psutil sdist did not contain a psutil-* directory")- src_root = min(src_roots, key=lambda path: path.name)- common_py = src_root / "psutil" / "_common.py"- rel = common_py.relative_to(src_root)- if not common_py.is_file():- raise PsutilAndroidInstallError(f"psutil sdist did not contain {rel!s}")- try:- content = common_py.read_text(encoding="utf-8-sig")- except OSError as exc:- raise PsutilAndroidInstallError(f"Failed to read {rel!s}") from exc- if MARKER not in content:- raise PsutilAndroidInstallError("psutil Android compatibility patch marker not found")- try:- common_py.write_text(content.replace(MARKER, REPLACEMENT), encoding="utf-8")- except OSError as exc:- raise PsutilAndroidInstallError(f"Failed to write {rel!s}") from exc- return src_root+# Shim to stop the old updater doing work until relaunch. Historical callers+# download PSUTIL_URL BEFORE calling prepare_patched_psutil_sdist, so waiting+# for that call is too late. Stop the import without offering a fake URL.+stop_for_relaunch()diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex fc13d0f2851..312ec51fb2d 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -276,13 +276,26 @@ def _refresh_dashboard_after_update(*, already_restarted_units: set[str] | NoneSee #83595."""- from hermes_cli.update_cmd import _m+ from hermes_cli.update_cmd import _m, _record_update_stepfrom hermes_constants import get_hermes_home- stop_result = _m()._kill_stale_dashboard_processes(- restart_managed=True, already_restarted_units=already_restarted_units,- scope_home=str(get_hermes_home()),- )+ try:+ stop_result = _m()._kill_stale_dashboard_processes(+ restart_managed=True, already_restarted_units=already_restarted_units,+ scope_home=str(get_hermes_home()),+ )+ except Exception as exc:+ # Isolated like every sibling post-update step: a failure here (#112604) used to abort+ # the fleet matrix, reconciliation and the inner receipt finalize that follow it. A+ # dashboard/serve left on pre-update code is still caught by the survivor probe →+ # reconciliation (exit 1).+ logger.warning("Post-update dashboard cleanup failed: %s", exc)+ _record_update_step("dashboard_cleanup", False, f"{type(exc).__name__}: {exc}")+ print()+ print(f"⚠ Could not refresh running dashboard/serve process(es): {exc}")+ print(" If one is still running, restart it so it serves the updated code:")+ print(" hermes dashboard --port <port> (or: systemctl --user restart hermes-dashboard)")+ returnif not stop_result.get("unrecovered"):returndiff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 9abc2fe7f66..21bae47b7f2 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -618,7 +618,7 @@ def _desktop_owns_gateway_lifecycle() -> bool:if any(e.get("purpose") in _BACKEND_PURPOSES and spawner_is_dead(e) is False for e in ledger_entries()):return Truepsutil = _psutil()- for pid, _name, cmdline in _try_call(_m()._detect_venv_python_processes, "Desktop-lifecycle holder scan failed: %s") or []:+ for pid, _name, cmdline in _try_call(_detect_venv_python_processes, "Desktop-lifecycle holder scan failed: %s") or []:if not _looks_like_desktop_control_plane(cmdline):continueif psutil is None:@@ -1290,7 +1290,7 @@ def _reap_and_rescan(message: str, pids, stop=None) -> list[tuple[int, str, str]print(message)(stop or _m()._stop_process_trees)(pids)_time.sleep(1.0)- return _m()._detect_venv_python_processes()+ return _detect_venv_python_processes()def _terminate_leftover_gateways(pids) -> None:@@ -1327,7 +1327,7 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew_m()._resume_windows_gateways_after_update(_windows_gateway_resume)sys.exit(2)- holders = _m()._detect_venv_python_processes()+ holders = _detect_venv_python_processes()# Gateways the pause machinery owns (respawned in the pause->guard window or unmapped# spawn path): stop and re-check; post-update resume brings them back.if holders and (gateway_holders := _m()._leftover_pausable_gateway_pids(holders)) is not None:diff --git a/tests/hermes_cli/test_psutil_android_extract.py b/tests/hermes_cli/test_psutil_android_extract.pydeleted file mode 100644index 2596e80c09d..00000000000--- a/tests/hermes_cli/test_psutil_android_extract.py+++ /dev/null@@ -1,73 +0,0 @@-"""Regression tests for the Android psutil compatibility installer."""--from __future__ import annotations--import io-import tarfile-from pathlib import Path--import pytest--from hermes_cli.psutil_android import (- MARKER,- PsutilAndroidInstallError,- prepare_patched_psutil_sdist,-)---def _add_dir(tf: tarfile.TarFile, name: str) -> None:- info = tarfile.TarInfo(name)- info.type = tarfile.DIRTYPE- info.mode = 0o755- tf.addfile(info)---def _add_file(tf: tarfile.TarFile, name: str, content: str) -> None:- payload = content.encode("utf-8")- info = tarfile.TarInfo(name)- info.size = len(payload)- info.mode = 0o644- tf.addfile(info, io.BytesIO(payload))---def _build_psutil_archive(archive: Path, *, malicious_symlink: bool) -> None:- with tarfile.open(archive, "w:gz") as tf:- _add_dir(tf, "psutil-7.2.2")- if malicious_symlink:- link = tarfile.TarInfo("psutil-7.2.2/psutil")- link.type = tarfile.SYMTYPE- link.linkname = "../../outside"- tf.addfile(link)- else:- _add_dir(tf, "psutil-7.2.2/psutil")- _add_file(- tf,- "psutil-7.2.2/psutil/_common.py",- f"{MARKER}\n",- )---def test_prepare_patched_psutil_sdist_rejects_symlink_member(tmp_path):- """A symlink member must be rejected before any file payload is written."""- archive = tmp_path / "evil.tar.gz"- _build_psutil_archive(archive, malicious_symlink=True)-- destination = tmp_path / "extract"- with pytest.raises(PsutilAndroidInstallError, match="Unsupported archive member type"):- prepare_patched_psutil_sdist(archive, destination)-- assert not (tmp_path / "outside" / "_common.py").exists()---def test_prepare_patched_psutil_sdist_rejects_traversal_member(tmp_path):- """A ``..`` member must be refused the same way the shared archive guard refuses it- (one traversal check for every tar.gz we extract), surfaced as the installer's own error."""- archive = tmp_path / "evil.tar.gz"- with tarfile.open(archive, "w:gz") as tf:- _add_dir(tf, "psutil-7.2.2")- _add_file(tf, "psutil-7.2.2/../escaped.py", "x")-- with pytest.raises(PsutilAndroidInstallError, match="Unsafe archive member path"):- prepare_patched_psutil_sdist(archive, tmp_path / "extract")-- assert not (tmp_path / "escaped.py").exists()diff --git a/tests/hermes_cli/test_update_sqlite_remediation.py b/tests/hermes_cli/test_update_sqlite_remediation.pyindex d0f662e61b2..42d233528e6 100644--- a/tests/hermes_cli/test_update_sqlite_remediation.py+++ b/tests/hermes_cli/test_update_sqlite_remediation.py@@ -27,7 +27,7 @@ def test_selected_sqlite_controls_completion_and_action_receipt(tmp_path, monkeyassert (message in output) is (verdict != 'unsafe')assert ('=== hermes-update completed' in output) is (verdict != 'unsafe' and action_id != 'invalid')if verdict == 'unsafe':- for text in ('SQLite 3.46.1', 'WAL-reset', 'uv-managed Python', 'hermes doctor'):+ for text in ('SQLite (3.46.1)', 'corruption bug', 'run the installer again', 'hermes doctor'):assert text in outputelif action_id != 'invalid':assert f'=== hermes-update completed {action_id} ===' in output@@ -39,5 +39,7 @@ def test_dashboard_refresh_preserves_restart_bookkeeping(already_restarted_unitsmonkeypatch.setattr(update_cmd, '_m', lambda: SimpleNamespace(_kill_stale_dashboard_processes=lambda **kwargs: calls.append(kwargs) or {'unrecovered': [1234]}))update_cmd_maint._refresh_dashboard_after_update(already_restarted_units=already_restarted_units)- assert calls == [{'restart_managed': True, 'already_restarted_units': already_restarted_units}]+ from hermes_constants import get_hermes_home+ assert calls == [{'restart_managed': True, 'already_restarted_units': already_restarted_units,+ 'scope_home': str(get_hermes_home())}]assert 'could not be auto-restarted' in capsys.readouterr().outdiff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.pyindex 2e11d53f47e..79c500c84a9 100644--- a/tests/hermes_cli/test_update_stale_dashboard.py+++ b/tests/hermes_cli/test_update_stale_dashboard.py@@ -867,7 +867,7 @@ class TestPostUpdateDashboardCleanupIsolation:tail (matrix, reconciliation, inner receipt finalize): contained, visible, recorded asa failed step on the open receipt."""import hermes_cli.update_receipt as ur- from hermes_cli import update_cmd+ from hermes_cli import update_cmd_maintur._current.set(None)try:@@ -878,7 +878,7 @@ class TestPostUpdateDashboardCleanupIsolation:"module 'hermes_cli.main_dashboard' has no attribute '_loaded_launchd_backend_jobs'"),):- update_cmd._finish_dashboard_update_cleanup([]) # must not raise+ update_cmd_maint._refresh_dashboard_after_update() # must not raisesteps = {s["name"]: s for s in ur._current.get().data["steps"]}finally:diff --git a/tests/hermes_cli/test_update_venv_holder_retirement.py b/tests/hermes_cli/test_update_venv_holder_retirement.pyindex ac3186d0180..08851f58d12 100644--- a/tests/hermes_cli/test_update_venv_holder_retirement.py+++ b/tests/hermes_cli/test_update_venv_holder_retirement.py@@ -9,14 +9,13 @@ from unittest.mock import Mockimport pytestfrom hermes_cli import main, update_cmd, update_cmd_windows+from tests.compat.old_updater_support import fresh_child as fresh_child, no_external_work as no_external_work # noqa: F401@pytest.mark.real_concurrent_gate@pytest.mark.parametrize("module,name,args,kwargs",[- (update_cmd, "_refuse_gateway_ancestor_tree_kill", ([123, 456],), {"gateway_mode": False}),- (update_cmd, "_refuse_gateway_ancestor_tree_kill", ([123, 456],), {"gateway_mode": True}),(main, "_filter_non_gateway_concurrent_instances", ([(123, "hermes.exe")],), {}),(main, "_detect_concurrent_hermes_instances", (Path("Scripts"),), {"exclude_pid": 123}),(main, "_leftover_pausable_gateway_pids", ([(123, "python.exe", "hermes serve")],), {}),@@ -24,13 +23,14 @@ from hermes_cli import main, update_cmd, update_cmd_windows(main, "_ledger_reapable_backend_pids", ([(123, "python.exe", "hermes serve")],), {}),(main, "_orphaned_desktop_backend_pids", ([(123, "python.exe", "hermes serve")],), {}),(main, "_handoff_reapable_backend_pids", ([(123, "python.exe", "hermes serve")],), {}),- (main, "_relaunch_stopped_serves", ({"pending": True, "entries": [{"pid": 123, "port": 9000}]},), {}),(main, "_stop_process_trees", ([123, (456, 789)],), {}),],)-def test_historical_holder_hooks_stop_without_inspecting_or_killing(- monkeypatch, capsys, module, name, args, kwargs,+def test_historical_holder_hooks_hand_off_without_inspecting_or_killing(+ monkeypatch, module, name, args, kwargs, fresh_child,):+ """A historical main's holder gates hand the update to the fresh child and exit with its+ status; the old parent never classifies, inspects or kills processes itself."""import hermes_cli.gateway as gatewayfrom hermes_cli import process_identityimport psutil@@ -41,19 +41,39 @@ def test_historical_holder_hooks_stop_without_inspecting_or_killing(monkeypatch.setattr(process_identity, "ledger_entries", forbidden)monkeypatch.setattr(psutil, "process_iter", forbidden)monkeypatch.setattr(psutil, "Process", forbidden)- monkeypatch.setattr(update_cmd_windows.subprocess, "run", forbidden)- monkeypatch.setattr(os, "kill", forbidden)before = deepcopy((args, kwargs))- with pytest.raises(SystemExit) as stopped:- # Frozen and historical main addresses must not return into the old- # updater's destructive ladder, even when asked for a read-only probe.+ with fresh_child.exits():getattr(module, name)(*args, **kwargs)- assert stopped.value.code == 0- assert "run `hermes` again" in capsys.readouterr().err.lower()assert (args, kwargs) == beforeforbidden.assert_not_called()+def test_relaunch_stopped_serves_is_separate_work_not_an_update(monkeypatch, fresh_child, capsys):+ """The historical atexit token restarts stopped serves through the child and returns."""+ token = {"pending": True, "entries": [{"pid": 123, "port": 9000}]}+ fresh_child.returncode = 0+ fresh_child.result = {"serves_handled": True}+ main._relaunch_stopped_serves(token)+ assert token["pending"] is False+ assert fresh_child.requests[-1]["stopped_serves"]["entries"] == token["entries"]+ assert "did not complete" not in capsys.readouterr().err++[email protected]("gateway_mode", [False, True])+def test_gateway_ancestor_refusal_never_kills_unknown_ancestry(monkeypatch, gateway_mode):+ """The live guard only refuses a tree-kill when a nominated gateway is positively an ancestor."""+ import hermes_cli.gateway as gateway+ import psutil++ forbidden = Mock(side_effect=AssertionError("refusal probe performed work"))+ monkeypatch.setattr(gateway, "_is_pid_ancestor_of_current_process", lambda pid: False)+ monkeypatch.setattr(psutil, "Process", forbidden)+ monkeypatch.setattr(update_cmd_windows.subprocess, "run", forbidden)+ monkeypatch.setattr(os, "kill", forbidden)+ assert update_cmd._refuse_gateway_ancestor_tree_kill([123, 456], gateway_mode=gateway_mode) is False+ forbidden.assert_not_called()++def test_command_reaches_checkout_preparation_without_holder_gates(monkeypatch, tmp_path):from hermes_cli import update_inventory@@ -90,3 +110,4 @@ def test_command_reaches_checkout_preparation_without_holder_gates(monkeypatch,main.cmd_update(SimpleNamespace(gateway=False, check=False, yes=True, force=False, force_venv=False))assert reached == ["backup", "pause", "checkout"]forbidden.assert_not_called()+