The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): finish `hermes update` in an interpreter born on the pulled code
teknium194ced1a2b263
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex e27e54df7f1..aa099f1f496 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2131,10 +2131,10 @@ _FROZEN_UPDATER_SURFACE: dict[str, tuple[str, ...]] = {"_ledger_reapable_backend_pids", "_leftover_pausable_gateway_pids", "_npm_lockfile_changed","_orphaned_desktop_backend_pids", "_park_stashed_changes","_pause_windows_gateways_for_update", "_print_parked_branch_kept_notice",- "_print_parked_branch_skip_warning", "_purge_stale_hermes_modules",+ "_print_parked_branch_skip_warning","_refresh_active_lazy_features", "_refresh_active_memory_provider_dependencies","_refresh_bootstrap_cache_scripts", "_refresh_windows_gateway_launchers",- "_relaunch_stopped_serves", "_reload_updated_runtime_modules",+ "_relaunch_stopped_serves","_restore_active_tool_dependencies", "_restore_stashed_changes","_resume_windows_gateways_after_update", "_run_logged_subprocess", "_run_pre_update_backup","_stash_local_changes_if_needed", "_stop_process_trees", "_sync_with_upstream_if_needed",diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex d285376c161..fd3187ddab1 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -443,7 +443,8 @@ def _install_hangup_protection(gateway_mode: bool = False):import datetime as _dt- log_file.write(f"\n=== hermes update started {_dt.datetime.now().isoformat(timespec='seconds')} ===\n")+ stage = "continued on the pulled code" if os.environ.get("HERMES_UPDATE_POST_SWAP") == "1" else "started"+ log_file.write(f"\n=== hermes update {stage} {_dt.datetime.now().isoformat(timespec='seconds')} ===\n")state["log_file"] = log_filesys.stdout = _UpdateOutputStream(state["prev_stdout"], log_file)diff --git a/hermes_cli/subcommands/update.py b/hermes_cli/subcommands/update.pyindex 9a74403ecf0..d088af43451 100644--- a/hermes_cli/subcommands/update.py+++ b/hermes_cli/subcommands/update.py@@ -2,6 +2,7 @@from __future__ import annotations+import argparsefrom typing import Callable@@ -73,4 +74,9 @@ def build_update_parser(subparsers, *, cmd_update: Callable) -> None:"the gateway would otherwise restart its own cgroup and kill the updater. ""Pair with a separate restart step (e.g. a cron that runs 10-15 min later).",)+ update_parser.add_argument(+ "--post-swap", default=None, metavar="FILE", help=argparse.SUPPRESS,+ # Internal: the pre-pull interpreter re-executes itself here after the code swap so the+ # rest of the update runs on the pulled code (hermes_cli/update_handoff.py).+ )update_parser.set_defaults(func=cmd_update)diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 72f9630a2bb..759b0d8085a 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -59,7 +59,7 @@ from hermes_cli.update_cmd_fleet import ( # noqa: F401_write_gateway_update_exit_code)from hermes_cli.update_cmd_zip import ( # noqa: F401_ZIP_PRESERVED_TOP_LEVEL, _ZIP_STAGING_ARTIFACT_SUFFIXES, _abort_zip_update_if_dirty_tree,- _atomic_replace_dir, _commit_staged_replacements, _discard_staged,+ _atomic_replace_dir, _commit_staged_replacements, _discard_staged, _finish_zip_update,_is_zip_preserved_entry_status_line, _is_zip_staging_artifact_status_line, _stage_replacement,_update_via_zip, _zip_overlay_block_reason)from hermes_cli.update_cmd_stash import ( # noqa: F401@@ -70,7 +70,7 @@ from hermes_cli.update_cmd_stash import ( # noqa: F401_stash_local_changes_if_needed, _warn_orphaned_update_autostashes)from hermes_cli.update_cmd_config import ( # noqa: F401_LAST_SIBLING_SNAPSHOTS, _check_and_apply_config_migration, _migrate_sibling_profile_configs,- _print_items, _reload_config_modules, _run_config_check_fresh, _run_migrate_config_fresh)+ _print_items, _run_config_check_fresh, _run_migrate_config_fresh)from hermes_cli.update_cmd_deps import ( # noqa: F401_INSTALL_DEFINING_FILES, _SELF_LOCKING_NATIVE_MODULES, _UPDATE_CRITICAL_MODULES,_abort_dependency_sync_if_self_locked, _capture_active_lazy_features,@@ -98,16 +98,14 @@ from hermes_cli.update_cmd_git import ( # noqa: F401_sync_with_upstream_if_needed)from hermes_cli.update_cmd_maint import ( # noqa: F401_PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- _STALE_PURGE_PROTECTED,- _UPDATE_RUNTIME_RELOAD_MODULES, _clear_stale_sqlite_sidecars,+ _clear_stale_sqlite_sidecars,_ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,_format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,_print_curator_first_run_notice, _print_curator_recent_run_notice,_print_fts_optimize_available_notice, _print_update_completion, _print_update_summary,- _print_verified_update_completion, _purge_stale_hermes_modules, _read_project_version,- _reload_process_scan_modules, _reload_updated_runtime_modules,+ _print_verified_update_completion, _read_project_version,_resolve_pre_update_backup_mode, _restore_state_db_from_snapshot,- _run_post_update_maintenance, _run_pre_update_backup, _stale_purge_prefixes,+ _run_post_update_maintenance, _run_pre_update_backup,_sweep_bytecode_after_update,_update_complete_message, _verify_and_restore_one_state_db,_verify_and_restore_state_dbs_post_update)@@ -1254,8 +1252,9 @@ def _finish_already_up_to_date(def _apply_pulled_update(git_cmd, branch, pre_pull_sha, _plan, opts, *, gateway_mode, is_fork, desktop_dir,had_desktop_app_before_update, pre_update_snapshot_id, _pre_update_plan,- _windows_gateway_resume) -> None:- """Post-pull phase: verify HEAD, sync Python/Node/web/Desktop, maintenance, fleet restart."""+ _windows_gateway_resume, args) -> None:+ """Post-pull phase, pre-swap half: verify HEAD, arm the fleet marker, sweep bytecode, then+ hand the rest of the run to an interpreter born on the pulled code (never returns)."""_invalidate_update_cache()post_pull_sha = _verify_head_after_pull(git_cmd, branch, pre_pull_sha, in_place_update=_plan.in_place_update,@@ -1269,6 +1268,130 @@ def _apply_pulled_update(# Stale .pyc would ImportError on gateway restart when new source references new names._sweep_bytecode_after_update(branch)+ _hand_off_post_swap(+ args, swap="git", branch=branch, pre_pull_sha=pre_pull_sha, is_fork=is_fork, opts=opts,+ gateway_mode=gateway_mode, had_desktop_app_before_update=had_desktop_app_before_update,+ pre_update_snapshot_id=pre_update_snapshot_id, _pre_update_plan=_pre_update_plan,+ _windows_gateway_resume=_windows_gateway_resume)+++# ``store_true`` update flags the post-swap child must see exactly as the user passed them.+_POST_SWAP_FORWARDED_FLAGS = (+ ("gateway", "--gateway"), ("no_backup", "--no-backup"), ("backup", "--backup"),+ ("yes", "--yes"), ("keep_stash", "--keep-stash"), ("switch_branch", "--switch-branch"),+ ("force", "--force"), ("force_venv", "--force-venv"),+ ("no_gateway_restart", "--no-gateway-restart"),+)+++def _post_swap_argv_tail(args) -> list[str]:+ tail = [flag for attr, flag in _POST_SWAP_FORWARDED_FLAGS if getattr(args, attr, False)]+ branch = getattr(args, "branch", None)+ if branch:+ tail += ["--branch", str(branch)]+ return tail+++def _post_swap_payload(+ *, swap: str, branch: str, opts, gateway_mode: bool, had_desktop_app_before_update: bool,+ pre_pull_sha=None, is_fork: bool = False, pre_update_snapshot_id=None, _pre_update_plan=None,+ _windows_gateway_resume=None) -> dict:+ """Everything the post-swap tail needs that only the pre-swap process could observe: the+ open receipt (detached here — the child resumes it), the pre-update fleet plan, the+ pre-update version and active features, the Windows pause token. Flags cross as argv."""+ from hermes_cli.update_receipt import detach_update_receipt++ return {+ "swap": swap, "branch": branch, "pre_pull_sha": pre_pull_sha, "is_fork": bool(is_fork),+ "gateway_mode": bool(gateway_mode),+ "had_desktop_app_before_update": bool(had_desktop_app_before_update),+ "pre_update_snapshot_id": pre_update_snapshot_id,+ "pre_update_version": opts.pre_update_version,+ "active_lazy_features": opts.active_lazy_features,+ "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,+ "receipt": detach_update_receipt(),+ }+++def _hand_off_post_swap(args, **payload_kwargs) -> None:+ """Re-execute ``hermes update --post-swap`` on the pulled tree and exit with its code.++ The parent detaches from the receipt and its Windows resume hook — the child owns both —+ and only relays the exit code (``hermes_cli/update_handoff.py``).+ """+ from hermes_cli.update_handoff import continue_update_in_fresh_interpreter++ payload = _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))+ sys.exit(code)+++def _run_post_swap_phase(args, gateway_mode: bool) -> None:+ """Child half of the update (``--post-swap``): resume the receipt and finish the run on the+ pulled code."""+ from hermes_cli.update_handoff import read_handoff+ from hermes_cli.update_receipt import resume_update_receipt++ payload = read_handoff(args.post_swap)+ if payload.get("receipt"):+ resume_update_receipt(payload["receipt"])+ _execute_post_swap(payload, args, gateway_mode)+++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-pull+ interpreter, driven from a hand-off payload."""+ from dataclasses import replace as _replace+ from hermes_cli.update_inventory import UpdatePlan++ _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:+ import atexit as _atexit+ _atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume)+ # Flags and config resolve here exactly as they did pre-swap; the three pre-update+ # snapshots come from the payload (the new tree would report the NEW version).+ opts = _replace(+ _resolve_update_options(args, gateway_mode),+ pre_update_version=payload.get("pre_update_version"),+ active_lazy_features=payload.get("active_lazy_features"),+ active_tool_dependencies=payload.get("active_tool_dependencies"))+ had_desktop_app_before_update = bool(payload.get("had_desktop_app_before_update"))+ desktop_dir = _m().PROJECT_ROOT / "apps" / "desktop"++ try:+ if payload.get("swap") == "zip":+ 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)+ if gateway_mode:+ _write_gateway_update_exit_code(desktop_build_ok)+ return+ _, git_cmd, _ = _prepare_git_command()+ _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,+ had_desktop_app_before_update=had_desktop_app_before_update,+ pre_update_snapshot_id=payload.get("pre_update_snapshot_id"),+ _pre_update_plan=_pre_update_plan, _windows_gateway_resume=_windows_gateway_resume)+ 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)+++def _finish_pulled_update(+ git_cmd, branch, pre_pull_sha, opts, *, gateway_mode, is_fork, desktop_dir,+ had_desktop_app_before_update, pre_update_snapshot_id, _pre_update_plan,+ _windows_gateway_resume) -> None:+ """Post-swap tail (git path): sync Python/Node/web/Desktop, maintenance, fleet restart."""if is_fork and branch == "main":_m()._sync_with_upstream_if_needed(git_cmd, _m().PROJECT_ROOT, assume_yes=opts.assume_yes, input_fn=opts.gw_input_fn)@@ -1337,6 +1460,11 @@ def _cmd_update_impl(args, gateway_mode: bool):opts = _resolve_update_options(args, gateway_mode)gw_input_fn, assume_yes = opts.gw_input_fn, opts.assume_yes+ if getattr(args, "post_swap", None):+ # Second half of a run whose pre-pull interpreter stopped at the code swap.+ _run_post_swap_phase(args, gateway_mode)+ return+print("☤ Updating Hermes Agent...")print()@@ -1452,7 +1580,7 @@ def _cmd_update_impl(args, gateway_mode: bool):is_fork=is_fork, desktop_dir=desktop_dir,had_desktop_app_before_update=had_desktop_app_before_update,pre_update_snapshot_id=pre_update_snapshot_id, _pre_update_plan=_pre_update_plan,- _windows_gateway_resume=_windows_gateway_resume)+ _windows_gateway_resume=_windows_gateway_resume, args=args)except _shim_quarantine_error_type() as e:# Strict quarantine refused BEFORE any installer ran — defer via marker, exit 2, no ZIP.# See #87331.diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.pyindex a57c16e7f54..2587a7db44c 100644--- a/hermes_cli/update_cmd_config.py+++ b/hermes_cli/update_cmd_config.py@@ -12,38 +12,14 @@ from hermes_cli.update_cmd_common import _best_effortlogger = logging.getLogger("hermes_cli.update_cmd")-def _reload_config_modules() -> None:- """Force-reload config modules after git pull: the updater is the PRE-pull process, so the- cached modules hold OLD code and ``check_config_version()`` would report "up to date" despite a- pulled migration. ``_subprocess_compat`` / ``dashboard_procs`` reload too so the later dashboard- cleanup sees symbols the update added. ``tools_config`` reloads as well: migrations import its- helpers at call time (``_migrate_to_45`` needs ``_configurable_keys``), and a pre-pull cache- lacks symbols the pull added (#111271)."""- import importlib- importlib.invalidate_caches()- for mod_name in (- "hermes_cli.config_defaults", "hermes_cli.config", "hermes_cli.tools_config",- "hermes_cli.config_migrations", "hermes_cli._subprocess_compat", "hermes_cli.dashboard_procs"):- mod = sys.modules.get(mod_name)- if mod is not None:- try:- importlib.reload(mod)- except Exception as exc:- logger.debug("Could not reload %s for fresh post-update code: %s", mod_name, exc)--def _run_config_check_fresh() -> tuple:- """``(current_ver, latest_ver)`` from freshly-reloaded modules (see ``_reload_config_modules``)."""- from hermes_cli.update_cmd import _reload_config_modules- _reload_config_modules()+ """``(current_ver, latest_ver)`` of the active profile's config against the running code."""from hermes_cli.config import check_config_versionreturn check_config_version(raise_on_parse_error=True)def _run_migrate_config_fresh(*, interactive: bool = False, quiet: bool = False) -> dict:- """Run config migration with freshly-reloaded modules; returns the results dict."""- from hermes_cli.update_cmd import _reload_config_modules- _reload_config_modules()+ """Run config migration; returns the results dict."""from hermes_cli.config import migrate_configreturn migrate_config(interactive=interactive, quiet=quiet)@@ -164,30 +140,19 @@ def _ask_configure_new_options(*, assume_yes: bool, gateway_mode: bool) -> str:def _check_and_apply_config_migration(*, assume_yes: bool = False, gateway_mode: bool = False, pre_update_snapshot_id: str | None = None) -> None:- """Check/apply config migrations with freshly-reloaded modules. Runs on EVERY completion path+ """Check/apply config migrations. Runs on EVERY completion path(post-pull, venv-repair, Node-deps repair on ``commit_count == 0``) so an interrupted updatethat already pulled code doesn't strand an old config version.See #91360."""from hermes_cli.update_cmd import (- _migrate_sibling_profile_configs, _reload_config_modules, _run_config_check_fresh,- _run_migrate_config_fresh)+ _migrate_sibling_profile_configs, _run_config_check_fresh, _run_migrate_config_fresh)print()print("→ Checking configuration for new options...")- # Evict EVERY cached Hermes module before touching migration code: the updater is the- # pre-pull process, and a migration step's call-time import (``_migrate_to_45`` →- # ``hermes_cli.tools_config._configurable_keys``) resolves against whatever old module- # object is still cached — reloading a hand-picked list re-fixes this per symptom- # (#111271). The purge is the class fix already used by the fleet-restart phase.- from hermes_cli.update_cmd import _m- # A config-check failure must not break an otherwise-successful update.+ # A config-check failure must not break an otherwise-successful update; it still fails+ # when the pulled tree is internally inconsistent, hence the try.try:- _m()._purge_stale_hermes_modules()- # Reload BEFORE any config reads so all checks use the updated code.- _reload_config_modules()- # Post-purge this re-executes the NEW config.py; it still fails if the pulled tree- # is internally inconsistent, hence the try.from hermes_cli.config import get_missing_env_vars, get_missing_config_fields# Log, point at the manual command, and return. See #91360.missing_env = get_missing_env_vars(required_only=True)diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex f86352acae6..4198a8b7353 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -1025,11 +1025,9 @@ def _sync_python_dependencies_after_pull(# failure can't be "healed" by a narrow core import probe._m()._clear_update_incomplete_marker()- # Still the old interpreter process: refresh caches/modules before lazy refresh imports- # newly-pulled modules. The install may have regenerated bytecode from build-cache- # copies — this second sweep catches those stragglers.+ # The install may have regenerated bytecode from build-cache copies — this second sweep+ # catches those stragglers._sweep_bytecode_after_update(branch)- _m()._reload_updated_runtime_modules()# Stale pip can fail source builds and leave partially-written packages.# See #57828.diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex 88eb0b4e61b..686a5606c93 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -358,8 +358,6 @@ def _run_pending_fleet_restart() -> bool:"""from hermes_cli.update_cmd import _mprint("→ Restarting gateways left on pre-update code...")- with suppress(Exception):- _m()._purge_stale_hermes_modules()# Warn if legacy Hermes gateway unit files are still installed. When both hermes.service (from a# pre-rename install) and the current hermes-gateway.service are enabled, they SIGTERM-fight for the# same bot token (see PR #11909). Flagging here means every `hermes update` surfaces the issue until the@@ -1342,10 +1340,6 @@ def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):# already-restarted units to ``_finish_dashboard_update_cleanup`` (review on #83595).restarted_scoped_units: set = set()- # Purge stale cached Hermes modules FIRST: the import below loads new gateway- # source into this pre-update interpreter, and a cached sibling missing a- # symbol the new source expects would ImportError and abort the whole phase.- _m()._purge_stale_hermes_modules()try:# Every gateway helper the phase needs is imported up front so a broken gateway# module aborts into recovery BEFORE any unit is touched.diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex 13a3757c53e..ba4eeb410e7 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -1,11 +1,10 @@-"""Post-update maintenance for ``hermes update``: pre-update backup snapshot, state-db verify/restore, curator/FTS notices, FHS path guard, completion summary, stale-module purge.+"""Post-update maintenance for ``hermes update``: pre-update backup snapshot, state-db verify/restore, curator/FTS notices, FHS path guard, completion summary.Split out of ``update_cmd.py``, which re-imports every name so ``hermes_cli.update_cmd.<name>``still resolves/monkeypatches. Origin helpers are imported lazily per function (no cycle;test patches on ``update_cmd`` stay effective)."""-import importlibimport loggingfrom contextlib import suppressimport os@@ -23,24 +22,6 @@ from hermes_cli.update_cmd_common import _best_effortlogger = logging.getLogger("hermes_cli.update_cmd")-_UPDATE_RUNTIME_RELOAD_MODULES = "hermes_constants", "tools.environments.local", "tools.lazy_deps"--#: Modules EXECUTING the update survive the purge: evicting them buys nothing (running frames-#: keep them alive) and reloading them mid-flight is the one genuinely unsafe move.-#: Two root modules carry process-wide identity state and are refreshed in place by-#: ``_reload_updated_runtime_modules`` instead: ``hermes_logging`` (a fresh copy starts a SECOND-#: QueueListener over the same log files while the first keeps running) and ``hermes_constants``-#: (its ``_HERMES_HOME_OVERRIDE`` ContextVar — a token taken through the old module cannot reset a-#: fresh module's var, and an override set before the purge would silently vanish).-_STALE_PURGE_PROTECTED = frozenset({"hermes_cli", "hermes_cli.main", "hermes_logging", "hermes_constants"})--#: The updater's own module family (``update_cmd*``, ``update_receipt``, ``update_inventory``,-#: ``update_lock``, ...) is protected as a prefix: these hold per-run state — the open receipt-#: singleton, the pre-update plan's ``RuntimeRecord`` class identity, the lock — and evicting-#: one swaps in a fresh module whose ``_current`` is None (receipt silently never written) or-#: whose dataclass fails every ``isinstance`` against the plan built before the purge.-_STALE_PURGE_PROTECTED_PREFIX = "hermes_cli.update_"-_PRE_UPDATE_SNAPSHOT_KEEP = 1# Per-file cap for the quick snapshot (larger files skipped with a warning): it protects@@ -76,97 +57,6 @@ def _load_updates_cfg() -> dict:return updates if isinstance(updates, dict) else {}-def _reload_modules(names, *, modules, log) -> None:- """``importlib.reload`` each module of *names* cached in *modules*; failures go to *log*."""- importlib.invalidate_caches()- for module_name in names:- module = modules.get(module_name)- if module is None:- continue- try:- importlib.reload(module)- except Exception as exc:- log(module_name, exc)---def _stale_purge_prefixes() -> frozenset:- """Top-level names the checkout owns, for the post-pull purge.-- Scanned, not listed: a hardcoded tuple stops covering each newly added top-level module- without anything failing, and the symbol that breaks the next update is in whichever one- drifted out — ``utils`` gaining ``base_url_origin`` / ``file_signature`` were the field cases.- """- from hermes_cli.update_cmd import _m- names = set()- for entry in Path(_m().PROJECT_ROOT).iterdir():- if entry.suffix == ".py" and entry.is_file():- names.add(entry.stem)- elif (entry / "__init__.py").is_file():- names.add(entry.name)- # ``tests`` is owned by the checkout but never purged: the in-process purge tests would- # otherwise re-import a fresh copy of the very test module their monkeypatches point at.- return frozenset(names) - {"tests"}---def _evict_module(modules: dict, name: str) -> bool:- """Returns True when *name* was cached in *modules*; also unbinds the evicted module from its- parent package.-- The attribute matters: ``from hermes_cli import main_dashboard`` is resolved by- ``_handle_fromlist``, which is satisfied by the ATTRIBUTE the import system left on the parent- package — so a purged submodule keeps being handed to call-time imports unless the attribute- goes too. The parent (``hermes_cli``) is protected and survives the purge, which is how a- pre-pull ``main_dashboard`` outlived it and crashed the dashboard cleanup on a symbol the pull- had just added (#112604).- """- dropped = modules.pop(name, None)- parent_name, _, child = name.rpartition(".")- parent = modules.get(parent_name)- # Identity, not name: a same-named module that something else already rebound on the- # package is newer than the one evicted here and must stay. ``vars()`` keeps a lazy- # package ``__getattr__`` (``providers``) from importing during the purge.- if parent is not None and dropped is not None and vars(parent).get(child) is dropped:- del vars(parent)[child]- return dropped is not None---def _purge_stale_hermes_modules() -> None:- """Evict every cached Hermes module after the checkout changed in-place. Never raises.-- The update runs in the pre-pull process; later phases lazily import NEW source into an OLD- ``sys.modules`` world and die when new code references a symbol missing from a cached- module. Purging (unlike reload) only drops the ``sys.modules`` entry — running frames keep- their module objects — so later imports rebuild a self-consistent graph from the new tree.- """- from hermes_cli.update_cmd import _m- with _best_effort('Could not purge stale Hermes modules: %s'):- importlib.invalidate_caches()- modules = _m().sys.modules- prefixes = _stale_purge_prefixes()- purged = [- name for name in list(modules)- if name not in _STALE_PURGE_PROTECTED- and not name.startswith(_STALE_PURGE_PROTECTED_PREFIX)- # Root-package check: startswith() alone also matches unrelated ``gateway_foo``.- and name.split(".", 1)[0] in prefixes- and _evict_module(modules, name)- ]- if purged:- logger.debug("Purged %d stale Hermes module(s) after checkout update", len(purged))---def _reload_updated_runtime_modules() -> None:- """Reload the modules used by lazy-backend refresh: the pre-pull process's cached modules- can expose old symbols despite new source on disk."""- from hermes_cli.update_cmd import _m- with _best_effort('Could not refresh update runtime modules: %s'):- _reload_modules(- _UPDATE_RUNTIME_RELOAD_MODULES,- modules=_m().sys.modules,- log=lambda name, exc: logger.debug("Could not reload updated module %s: %s", name, exc),- )--def _print_curator_first_run_notice() -> None:"""Curator heads-up after update. Fires only when enabled AND never run — the window wherethe first pass (deferred one ``interval_hours``) is pending, so the user can preview or@@ -345,34 +235,6 @@ def _format_time_ago(iso_ts: str) -> str:return "recently"-def _reload_process_scan_modules() -> None:- """Reload the process-scan modules, dependency-first, so ``dashboard_procs`` binds against a- fresh ``_subprocess_compat``: cleanup runs in the PRE-update process and a symbol the update- added would otherwise ImportError after the code update succeeded. Called from the cleanup- entry point so every caller (git path, ZIP fallback) is covered.-- ``_finish_dashboard_update_cleanup`` runs in the PRE-update Python process, but- ``_scan_dashboard_processes`` does a function-level ``from hermes_cli._subprocess_compat import- bounded_probe_run``. If the update added a new symbol to ``_subprocess_compat`` (as #87134 did with- ``bounded_probe_run``), the cached OLD module object doesn't have it and the cleanup step crashes with- ImportError — after the code update itself already succeeded.-- The helpers it imports from ``hermes_cli.main_dashboard`` / ``main_install_repair`` are NOT- refreshed here: ``hermes_cli.main`` imports those eagerly at CLI start, so reloading would- rewrite the module dict the running update still holds bindings into. The- ``_purge_stale_hermes_modules`` eviction, which runs earlier in the update, is what makes the- call-time ``from hermes_cli import main_dashboard`` re-read the pulled source (#112604).- """- _reload_modules(- ("hermes_cli._subprocess_compat", "hermes_cli.dashboard_procs"),- modules=sys.modules,- # warning, not debug: a failed reload surfaces as ImportError seconds later.- log=lambda name, exc: logger.warning(- "Could not reload %s for post-update cleanup: %s", name, exc- ),- )--def _finish_dashboard_update_cleanup(node_failures: list[str], already_restarted_units: "set[str] | None" = None) -> None:@@ -383,15 +245,13 @@ def _finish_dashboard_update_cleanup(See #83595."""- from hermes_cli.update_cmd import _m, _record_update_step, _reload_process_scan_modules+ from hermes_cli.update_cmd import _m, _record_update_stepif node_failures:print()print(" ℹ Leaving running dashboard process(es) untouched because the")print(" Node.js dependency refresh did not complete.")return- _reload_process_scan_modules()-try:stop_result = _m()._kill_stale_dashboard_processes(restart_managed=True, already_restarted_units=already_restarted_unitsdiff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex dfc219f217d..62348484fa3 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -358,15 +358,13 @@ def _reinstall_python_deps_after_zip(active_tool_dependencies) -> None:def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> bool:"""Update via ZIP archive; used on Windows when git file I/O is broken (antivirus / NTFS filter- drivers causing 'Invalid argument'). Returns ``False`` when a Desktop rebuild ran and failed."""- from hermes_cli.update_cmd import (- _finish_dashboard_update_cleanup, _m, _print_bundled_skills_sync_report, _print_curator_first_run_notice,- _print_curator_recent_run_notice, _print_update_summary, _read_project_version, _rebuild_desktop_after_update,- _sweep_bytecode_after_update, _update_node_dependencies, _validate_critical_modules_import,- _verify_and_restore_state_dbs_post_update,- )- active_tool_dependencies = _m()._capture_active_tool_dependencies()- pre_update_version = _read_project_version() # snapshot before files are replaced, for the completion line+ drivers causing 'Invalid argument'). Swaps the tree, then hands the rest of the run to an+ interpreter born on the new code (never returns; the child owns the receipt and exit code)."""+ from hermes_cli.update_cmd import _hand_off_post_swap, _m, _read_project_version, _resolve_update_options, _sweep_bytecode_after_update+ gateway_mode = bool(getattr(args, "gateway", False))+ opts = _resolve_update_options(args, gateway_mode)+ # Snapshot before files are replaced, for the completion line.+ pre_update_version = _read_project_version()# The static archive would silently ignore --branch — the exact silent-divergence bug it exists to# prevent. Refuse rather than lie.branch = _m()._resolve_update_branch(args)@@ -382,6 +380,22 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo_abort_zip_update_if_dirty_tree()_download_and_swap_zip(branch, f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip")_sweep_bytecode_after_update(branch)+ from 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)+ 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:+ """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 (+ _finish_dashboard_update_cleanup, _m, _print_bundled_skills_sync_report, _print_curator_first_run_notice,+ _print_curator_recent_run_notice, _print_update_summary, _rebuild_desktop_after_update,+ _update_node_dependencies, _validate_critical_modules_import,+ _verify_and_restore_state_dbs_post_update,+ )# Self-lock deferral: the code swap is committed; defer only the dependency sync when this process# holds a native extension the sync must rewrite.# Reinstall Python dependencies. Prefer .[all], but if one optional extra breaks on this machine, keepdiff --git a/hermes_cli/update_handoff.py b/hermes_cli/update_handoff.pynew file mode 100644index 00000000000..ab39c46cb48--- /dev/null+++ b/hermes_cli/update_handoff.py@@ -0,0 +1,135 @@+"""Post-swap hand-off: finish ``hermes update`` in an interpreter born on the pulled code.++``hermes update`` starts in an interpreter that imported the PRE-pull tree. Once ``git merge``+(or the ZIP swap) has replaced the checkout, every later phase — dependency sync, Node/web/+Desktop builds, maintenance, fleet restart, verification, receipt — used to keep running in+that stale process and lazily import NEW source into an OLD ``sys.modules`` graph. Any rename+between the two commits then surfaced as an ``ImportError``/``AttributeError`` inside the+updater itself, after the code swap had already succeeded (#87134, #112465, #112558, #112604+and their siblings). Module purges and targeted reloads only ever moved the crash to the next+unpurged module.++The permanent shape: the pre-pull process stops at the swap, writes everything the tail needs+into a hand-off file and re-executes ``hermes update --post-swap <file>`` under the venv+interpreter. The child imports exclusively from the pulled tree, resumes the open receipt and+owns the rest of the run; the parent relays its exit code. Nothing in the updater runs pulled+code inside a pre-pull interpreter any more, so there is no stale-symbol class left to isolate.+"""++from __future__ import annotations++import json+import logging+import os+import subprocess+import sys+from pathlib import Path+from typing import Any++from hermes_cli.update_cmd_common import _best_effort++logger = logging.getLogger("hermes_cli.update_cmd")++# Set on the post-swap child: the receipt header says "continued", the lock is the parent's.+POST_SWAP_ENV = "HERMES_UPDATE_POST_SWAP"+++def _json_default(value: Any):+ if isinstance(value, (set, frozenset)):+ return sorted(value, key=str)+ if isinstance(value, Path):+ return str(value)+ raise TypeError(f"not JSON serializable: {type(value).__name__}")+++def write_handoff(payload: dict[str, Any]) -> Path:+ """Persist the post-swap payload under HERMES_HOME; returns its path."""+ from hermes_constants import get_hermes_home++ directory = get_hermes_home() / "logs" / "update_receipts"+ directory.mkdir(parents=True, exist_ok=True)+ path = directory / f"post_swap_{os.getpid()}.json"+ path.write_text(json.dumps(payload, indent=2, default=_json_default), encoding="utf-8")+ return path+++def read_handoff(path: str | Path) -> dict[str, Any]:+ payload = json.loads(Path(path).read_text(encoding="utf-8"))+ if not isinstance(payload, dict):+ raise ValueError(f"post-swap hand-off {path} is not a JSON object")+ return payload+++def is_post_swap_child() -> bool:+ return os.environ.get(POST_SWAP_ENV) == "1"+++def _running_from_windows_shim() -> bool:+ from hermes_cli.main_install_repair import _windows_shim_in_process_chain++ return _windows_shim_in_process_chain() is not None+++def post_swap_python() -> Path:+ """Interpreter for the child: the project venv's python (the console shim can never be+ re-executed on Windows — it holds itself open), else the running interpreter."""+ from hermes_cli.main_install_repair import _windows_shim_in_process_chain++ shim = _windows_shim_in_process_chain()+ if shim is not None:+ from hermes_constants import venv_python_path++ candidate = venv_python_path(shim.parent.parent, windows=True)+ if candidate.is_file():+ return candidate+ return Path(sys.executable)+++def post_swap_command(handoff_path: Path, argv_tail: list[str]) -> list[str]:+ """``python -m hermes_cli.main update <original flags> --post-swap <file>``."""+ 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.+ """+ from hermes_cli.update_lock import HANDOFF_PID_ENV++ 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())}+ logger.debug("Post-swap hand-off → %s", subprocess.list2cmdline(cmd))+ sys.stdout.flush()+ sys.stderr.flush()++ if _running_from_windows_shim():+ 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("→ 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 0++ try:+ result = subprocess.run(cmd, env=env)+ 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)diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.pyindex 503c1aa2359..e1fe2c654de 100644--- a/hermes_cli/update_inventory.py+++ b/hermes_cli/update_inventory.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport loggingimport sysfrom contextlib import contextmanager, suppress-from dataclasses import dataclass, field, asdict+from dataclasses import dataclass, field, asdict, fields as dataclass_fieldsfrom typing import Any, Callable, Optionallogger = logging.getLogger(__name__)@@ -46,6 +46,18 @@ class UpdatePlan:def to_dict(self) -> dict[str, Any]:return asdict(self) # recursive: RuntimeRecord entries become dicts+ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> "UpdatePlan":+ """Inverse of :meth:`to_dict` (the plan crosses the post-swap hand-off as JSON)."""+ fields_ = {f.name for f in dataclass_fields(cls)}+ plan = cls(**{k: v for k, v in data.items() if k in fields_ and k != "runtimes"})+ record_fields = {f.name for f in dataclass_fields(RuntimeRecord)}+ plan.runtimes = [+ RuntimeRecord(**{k: v for k, v in r.items() if k in record_fields})+ for r in data.get("runtimes") or [] if isinstance(r, dict)+ ]+ return plan+def _detect_supervisor_for_pid(pid: int, service_pids: set, windows_service_pids: set | None = None) -> str:"""Classify how a live gateway PID is supervised."""diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex 0f12d465676..3aa876ad95a 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -137,6 +137,27 @@ def begin_update_receipt() -> None:_current = None+def detach_update_receipt() -> Optional[dict[str, Any]]:+ """Hand the open receipt to another process: return its data and forget it here.++ The post-swap child resumes it via :func:`resume_update_receipt`; the parent's+ command-boundary finalize then no-ops, so the run still produces exactly one receipt.+ """+ global _current+ receipt, _current = _current, None+ return None if receipt is None else receipt.data+++def resume_update_receipt(data: dict[str, Any]) -> None:+ """Continue a receipt detached by the pre-swap interpreter (``started_at``, ``pre_update``,+ ``argv``, steps and plan intact); records this process as the one that finished it."""+ global _current+ receipt = UpdateReceipt()+ receipt.data = data+ receipt.data["post_swap_pid"] = os.getpid()+ _current = receipt++def _record(method: str, what: str, *args: Any, **kwargs: Any) -> None:"""Invoke ``method`` on the active receipt; no-op when none, never raises."""try:diff --git a/pyproject.toml b/pyproject.tomlindex 4ddeea131d7..34c382a6e47 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -606,6 +606,7 @@ testpaths = ["tests"]markers = ["integration: marks tests requiring external services (API keys, Modal, etc.)","real_concurrent_gate: opt out of the autouse stub that disables _detect_concurrent_hermes_instances",+ "real_post_swap_handoff: opt out of the autouse stub that runs the update post-swap tail in-process","real_agent_prewarm: opt out of the autouse stub that disables the tui_gateway deferred agent pre-warm timer","real_retry_backoff: opt out of the tests/agent autouse stub that zeroes jittered_backoff","requires_wal: needs the runtime to actually enable SQLite WAL mode (skipped where Hermes falls back to journal_mode=DELETE)",diff --git a/tests/hermes_cli/conftest.py b/tests/hermes_cli/conftest.pyindex 1db3887b7ec..7f88065f335 100644--- a/tests/hermes_cli/conftest.py+++ b/tests/hermes_cli/conftest.py@@ -56,6 +56,32 @@ def _suppress_concurrent_hermes_gate(request, monkeypatch):)[email protected](autouse=True)+def _inline_post_swap_handoff(request, monkeypatch):+ """Run the post-swap tail in-process instead of re-executing ``hermes update --post-swap``.++ ``_apply_pulled_update`` / ``_update_via_zip`` hand the rest of the run to a child+ interpreter on the pulled tree. A mocked updater flow must not spawn that child (it would+ run a real dependency sync against the worktree), so the tail runs here through the same+ payload round-trip — every step stays patchable and the payload shape is still exercised.+ Tests of the hand-off itself opt out with ``@pytest.mark.real_post_swap_handoff``.+ """+ if request.node.get_closest_marker("real_post_swap_handoff"):+ return+ try:+ from hermes_cli import update_cmd, update_receipt+ except Exception:+ return++ def _inline(args, **payload_kwargs):+ payload = update_cmd._post_swap_payload(**payload_kwargs)+ if payload["receipt"]:+ update_receipt.resume_update_receipt(payload["receipt"])+ update_cmd._execute_post_swap(payload, args, payload_kwargs["gateway_mode"])++ monkeypatch.setattr(update_cmd, "_hand_off_post_swap", _inline, raising=False)++@pytest.fixturedef isolated_update_runtime(monkeypatch, tmp_path, request):"""Keep mocked updater flows off the host checkout and runtime fleet."""@@ -69,8 +95,6 @@ def isolated_update_runtime(monkeypatch, tmp_path, request):if hasattr(request.module, "PROJECT_ROOT"):monkeypatch.setattr(request.module, "PROJECT_ROOT", checkout)- # A real purge would discard the module objects patched below.- monkeypatch.setattr(main, "_purge_stale_hermes_modules", lambda: None)monkeypatch.setattr(gateway, "find_gateway_pids", lambda *a, **k: [])monkeypatch.setattr(gateway, "find_profile_gateway_processes", lambda *a, **k: [])monkeypatch.setattr(gateway, "_get_service_pids", lambda *a, **k: set())diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.pyindex b19e2153981..b9d38f847f1 100644--- a/tests/hermes_cli/test_cmd_update.py+++ b/tests/hermes_cli/test_cmd_update.py@@ -587,8 +587,8 @@ class TestCmdUpdateBranchFallback:hm, "_sync_with_upstream_if_needed"), patch.object(hm,- "_reload_updated_runtime_modules",- # Reaching the reload step IS the proof the post-update path ran+ "_upgrade_pip_before_lazy_refresh",+ # Reaching the lazy-refresh step IS the proof the post-update path ran# (the bug returned from "Already up to date!" before it). Abort# the pipeline right here: everything past this point (skills# sync, desktop rebuild, gateway restart, fleet check) would run@@ -599,7 +599,7 @@ class TestCmdUpdateBranchFallback:cmd_update(mock_args)assert exit_info.value.code == 0- post_update_step.assert_called_once_with()+ post_update_step.assert_called_once()captured = capsys.readouterr()assert "Already up to date!" not in captured.out@@ -612,8 +612,6 @@ class TestCmdUpdateBranchFallback:), patch("hermes_cli.config.get_missing_config_fields",return_value=[{"key": "new.option", "default": True}],- ), patch(- "hermes_cli.update_cmd._reload_config_modules"), patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2)), patch(@@ -655,8 +653,6 @@ class TestCmdUpdateMigrationPrompt:"hermes_cli.config.get_missing_env_vars", return_value=[]), patch("hermes_cli.config.get_missing_config_fields", return_value=[]- ), patch(- "hermes_cli.update_cmd._reload_config_modules"), patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(5, 24)), patch(@@ -694,8 +690,6 @@ class TestCmdUpdateMigrationPrompt:"hermes_cli.config.get_missing_env_vars", return_value=[]), patch("hermes_cli.config.get_missing_config_fields", return_value=[]- ), patch(- "hermes_cli.update_cmd._reload_config_modules"), patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(33, 34)), patch(@@ -736,8 +730,6 @@ class TestCmdUpdateMigrationPrompt:"hermes_cli.config.get_missing_env_vars", return_value=env_items), patch("hermes_cli.config.get_missing_config_fields", return_value=cfg_items- ), patch(- "hermes_cli.update_cmd._reload_config_modules"), patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 24)), patch(@@ -759,37 +751,6 @@ class TestCmdUpdateMigrationPrompt:assert "display.new_widget" in out-class TestConfigVersionCheckUsesFreshModules:- """Regression: config migration must use freshly-reloaded modules, not the- sys.modules cache from before git pull.-- Before the fix, ``hermes update`` ran in the PRE-pull Python process.- After ``git pull`` updated the source on disk, function-level imports- returned the OLD cached ``hermes_cli.config`` module — so- ``DEFAULT_CONFIG["_config_version"]`` was stale and- ``check_config_version()`` reported ``(33, 33)`` "up to date" even though- the freshly-pulled code had v34 with a migration to run. The personality- reset migration (#81946) was silently skipped this way.- """-- def test_run_config_check_fresh_reloads_modules(self):- """_run_config_check_fresh must call _reload_config_modules which- force-reloads the config modules from disk.-- Regression: config migration was silently skipped because- sys.modules held the OLD hermes_cli.config with the OLD- DEFAULT_CONFIG["_config_version"] after git pull.- """- from unittest.mock import patch-- import hermes_cli.update_cmd as update_cmd-- with patch.object(update_cmd, "_reload_config_modules") as mock_reload:- update_cmd._run_config_check_fresh()-- mock_reload.assert_called_once()--class TestCmdUpdateProfileSkillSync:"""cmd_update syncs bundled skills to all profiles, including the active one.diff --git a/tests/hermes_cli/test_pending_supervisor_recovery.py b/tests/hermes_cli/test_pending_supervisor_recovery.pyindex 46b974708f3..26bedf69e80 100644--- a/tests/hermes_cli/test_pending_supervisor_recovery.py+++ b/tests/hermes_cli/test_pending_supervisor_recovery.py@@ -10,7 +10,6 @@ from hermes_cli import gateway, main, update_cmd_fleet as fleet@pytest.mark.linux_only@pytest.mark.parametrize("failure", ["listing", "timeout", "missing", "restart", "inactive", "running", None])def test_pending_marker_requires_complete_systemd_recovery(monkeypatch, tmp_path, failure):- monkeypatch.setattr(main, "_purge_stale_hermes_modules", lambda: None)stopped = []monkeypatch.setattr(gateway, "find_gateway_pids", lambda **kw: [123] if failure == "running" and not stopped else [])monkeypatch.setattr(gateway, "kill_gateway_processes", lambda **kw: stopped.append(True))diff --git a/tests/hermes_cli/test_sibling_config_migration.py b/tests/hermes_cli/test_sibling_config_migration.pyindex a9847ba2d76..006baa0d0b5 100644--- a/tests/hermes_cli/test_sibling_config_migration.py+++ b/tests/hermes_cli/test_sibling_config_migration.py@@ -42,12 +42,6 @@ def _setup(monkeypatch, tmp_path, active_home: Path):monkeypatch.setattr(hermes_constants, "get_process_hermes_home", lambda: active_home)- monkeypatch.setattr(- update_cmd, "_reload_config_modules", lambda: None- ) # module reload is orthogonal here; the real one re-imports from disk- monkeypatch.setattr(- update_cmd_config, "_reload_config_modules", lambda: None- ) # module reload is orthogonal here; the real one re-imports from diskdef test_sibling_behind_is_migrated_on_disk(monkeypatch, tmp_path):diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.pyindex 6ac9c04e48c..265148d67dd 100644--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@ -52,12 +52,6 @@ def _patch_gateway_discovery():``sys.exit(1)`` (#78574). Discovery returning nothing makes the phase aclean no-op — none of the tests here assert on gateway restarts.- ``_purge_stale_hermes_modules`` must also be stubbed: it evicts- ``hermes_cli.gateway`` from ``sys.modules`` mid-update, and the restart- phase's fresh ``from hermes_cli.gateway import ...`` then loads an- UNPATCHED copy of the module — silently discarding every mock here and- letting real gateway discovery (and real ``os.kill``) run on the dev box.-The launchd scope is neutralised too: on a macOS host the restart phasederives labels from the profile layout, so a default profile alone handsit ``ai.hermes.gateway`` and the verify step exits 1 (#111866, #110701).@@ -69,7 +63,6 @@ def _patch_gateway_discovery():patch("hermes_cli.update_inventory.collect_runtime_inventory", return_value=None), \patch("hermes_cli.update_inventory.report_unaccounted_runtimes", return_value=False), \patch.object(hermes_main, "_fleet_probe_expected_runtimes", lambda *a, **kw: False), \- patch.object(hermes_main, "_purge_stale_hermes_modules", lambda *a, **kw: None), \patch("hermes_cli.update_receipt.collect_fleet_versions", return_value=[]):yield@@ -125,26 +118,6 @@ def test_refresh_active_memory_provider_dependencies_reinstalls_active_provider(-def test_reload_updated_runtime_modules_restores_new_hermes_constants_symbol(monkeypatch):- """A pre-pull module object missing a new helper is repaired by reload."""- import hermes_constants-- monkeypatch.delattr(hermes_constants, "apply_subprocess_home_env", raising=False)- assert not hasattr(hermes_constants, "apply_subprocess_home_env")-- hermes_main._reload_updated_runtime_modules()-- assert callable(hermes_constants.apply_subprocess_home_env)-------# ----------------------------------------------------------------------------# ff-only fallback to reset --hard on diverged history-# ----------------------------------------------------------------------------def _make_update_side_effect(current_branch="main",commit_count="3",diff --git a/tests/hermes_cli/test_update_config_migration_on_current.py b/tests/hermes_cli/test_update_config_migration_on_current.pyindex 907818a3dde..8984e9f4efd 100644--- a/tests/hermes_cli/test_update_config_migration_on_current.py+++ b/tests/hermes_cli/test_update_config_migration_on_current.py@@ -34,7 +34,7 @@ def _run(current: int, latest: int):migrate_calls.append((interactive, quiet))return {"env_added": [], "config_added": [], "warnings": []}- with patch.object(update_cmd, "_reload_config_modules"), patch(+ with patch("hermes_cli.config.get_missing_env_vars", return_value=[]), patch("hermes_cli.config.get_missing_config_fields", return_value=[]@@ -83,7 +83,7 @@ def test_surfaces_migration_warnings():"warnings": ["personality reset: kawaii → default"],}- with patch.object(update_cmd, "_reload_config_modules"), patch(+ with patch("hermes_cli.config.get_missing_env_vars", return_value=[]), patch("hermes_cli.config.get_missing_config_fields", return_value=[]@@ -104,7 +104,7 @@ def test_surfaces_migration_warnings():def test_check_failure_does_not_break_repair_path():"""A config-check failure must not break the repair path."""- with patch.object(update_cmd, "_reload_config_modules"), patch(+ with patch("hermes_cli.config.get_missing_env_vars", return_value=[]), patch("hermes_cli.config.get_missing_config_fields", return_value=[]diff --git a/tests/hermes_cli/test_update_config_migration_on_current_checkout.py b/tests/hermes_cli/test_update_config_migration_on_current_checkout.pyindex 563213507c1..4e434ad4fdd 100644--- a/tests/hermes_cli/test_update_config_migration_on_current_checkout.py+++ b/tests/hermes_cli/test_update_config_migration_on_current_checkout.py@@ -20,7 +20,6 @@ from hermes_cli import update_cmddef _no_stale_module_purge(monkeypatch):"""The migration step evicts every cached Hermes module first (#111271); a real purgewould discard the ``hermes_cli.config`` object these tests patch."""- monkeypatch.setattr(cli_main, "_purge_stale_hermes_modules", lambda: None)def test_repair_node_deps_runs_config_migration_on_version_bump(capsys):@@ -30,7 +29,6 @@ def test_repair_node_deps_runs_config_migration_on_version_bump(capsys):with (patch.object(update_cmd, "_update_node_dependencies", return_value=[]),patch.object(update_cmd, "_m") as m,- patch.object(update_cmd, "_reload_config_modules"),patch.object(update_cmd, "_run_config_check_fresh", return_value=(37, 38)),patch("hermes_cli.config.get_missing_env_vars", return_value=[]),patch("hermes_cli.config.get_missing_config_fields", return_value=[]),@@ -58,7 +56,6 @@ def test_repair_node_deps_up_to_date_config(capsys):with (patch.object(update_cmd, "_update_node_dependencies", return_value=[]),patch.object(update_cmd, "_m") as m,- patch.object(update_cmd, "_reload_config_modules"),patch.object(update_cmd, "_run_config_check_fresh", return_value=(38, 38)),patch("hermes_cli.config.get_missing_env_vars", return_value=[]),patch("hermes_cli.config.get_missing_config_fields", return_value=[]),@@ -78,7 +75,6 @@ def test_repair_node_deps_up_to_date_config(capsys):def test_check_and_apply_config_migration_interactive_prompt():"""When new config options exist in an interactive session, it prompts the user."""with (- patch.object(update_cmd, "_reload_config_modules"),patch.object(update_cmd, "_run_config_check_fresh", return_value=(37, 38)),patch("hermes_cli.config.get_missing_env_vars", return_value=[{"name": "NEW_KEY", "description": "desc"}]),patch("hermes_cli.config.get_missing_config_fields", return_value=[]),@@ -99,7 +95,6 @@ def test_check_and_apply_config_migration_interactive_prompt():def test_check_and_apply_config_migration_assume_yes():"""When assume_yes=True, it applies migrations non-interactively without prompting."""with (- patch.object(update_cmd, "_reload_config_modules"),patch.object(update_cmd, "_run_config_check_fresh", return_value=(37, 38)),patch("hermes_cli.config.get_missing_env_vars", return_value=[{"name": "NEW_KEY"}]),patch("hermes_cli.config.get_missing_config_fields", return_value=[]),@@ -117,7 +112,6 @@ def test_check_and_apply_config_migration_assume_yes():def test_check_and_apply_config_migration_non_interactive():"""In a non-interactive session (e.g. CI/scripts), it applies safe migrations automatically."""with (- patch.object(update_cmd, "_reload_config_modules"),patch.object(update_cmd, "_run_config_check_fresh", return_value=(37, 38)),patch("hermes_cli.config.get_missing_env_vars", return_value=[]),patch("hermes_cli.config.get_missing_config_fields", return_value=[{"key": "new_setting"}]),diff --git a/tests/hermes_cli/test_update_config_reload_tools_config.py b/tests/hermes_cli/test_update_config_reload_tools_config.pydeleted file mode 100644index 03feb631c17..00000000000--- a/tests/hermes_cli/test_update_config_reload_tools_config.py+++ /dev/null@@ -1,91 +0,0 @@-"""``hermes update`` runs config migrations in the PRE-pull updater process. A migration step-that imports a helper at call time (``_migrate_to_45`` → ``hermes_cli.tools_config``) resolves-against whatever OLD module object is still cached, and dies with ``cannot import name`` when the-pull added that symbol — config silently stays behind while the code moves on (#111271).--The class fix: the migration step evicts every cached Hermes module (``_purge_stale_hermes_modules``,-the same primitive the fleet-restart phase uses) before importing migration code, so ANY symbol the-pull added to ANY module a migration imports is found. The pinned-list reload of ``tools_config`` is-the per-symptom half; the purge covers the class.-"""--from __future__ import annotations--import importlib-import sys--import pytest--[email protected](autouse=True)-def _restore_sys_modules():- """The purge under test evicts real Hermes modules; put the originals back for later tests."""- snapshot = dict(sys.modules)- yield- for name, mod in snapshot.items():- sys.modules[name] = mod---def test_reload_config_modules_restores_missing_tools_config_symbol():- """A pre-pull ``tools_config`` cache must be reloaded before migrations run."""- tools_config = sys.modules.get("hermes_cli.tools_config")- if tools_config is None:- import hermes_cli.tools_config as tools_config # noqa: F811- assert hasattr(tools_config, "_configurable_keys")-- del tools_config._configurable_keys- try:- from hermes_cli.update_cmd_config import _reload_config_modules- _reload_config_modules()- assert hasattr(sys.modules["hermes_cli.tools_config"], "_configurable_keys")- finally:- reloaded = sys.modules["hermes_cli.tools_config"]- if not hasattr(reloaded, "_configurable_keys"):- importlib.reload(reloaded) # keep other tests on a clean module---def test_update_migration_survives_stale_module_missing_call_time_symbol(tmp_path, monkeypatch):- """The reporter's exact shape: the cached ``tools_config`` predates ``_configurable_keys`` while- the on-disk v45 step imports it at call time. The updater's migration entry must still land- v44 → v45 instead of printing "Config format update failed"."""- home = tmp_path / "flat-home"- home.mkdir()- (home / "config.yaml").write_text(- "_config_version: 44\nplatform_toolsets:\n telegram:\n - web\n - file\n", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(home))- from hermes_constants import set_hermes_home_override- token = set_hermes_home_override(home)- try:- import hermes_cli.tools_config as tools_config- monkeypatch.delattr(tools_config, "_configurable_keys")-- from hermes_cli.update_cmd import _check_and_apply_config_migration- _check_and_apply_config_migration(assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None)- finally:- from hermes_constants import reset_hermes_home_override- reset_hermes_home_override(token)-- text = (home / "config.yaml").read_text(encoding="utf-8")- assert "_config_version: 45" in text, text---def test_update_migration_import_failure_after_purge_prints_fallback(tmp_path, monkeypatch, capsys):- """The purge protects ``hermes_constants`` (identity-bearing ContextVar state), so the- post-purge ``from hermes_cli.config import ...`` re-executes NEW config.py against that OLD- root module and can raise ImportError. That must print the 'run hermes config migrate' fallback and- return — not escape and abort the rest of post-update maintenance (fleet restart)."""- home = tmp_path / "flat-home"- home.mkdir()- (home / "config.yaml").write_text("_config_version: 44\n", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(home))- import hermes_cli.config # noqa: F401 (pre-pull world has config cached)- import hermes_constants- # A pre-pull root module lacking a symbol the post-pull hermes_cli/config.py imports at module level.- monkeypatch.delattr(hermes_constants, "get_process_hermes_home")-- from hermes_cli.update_cmd import _check_and_apply_config_migration- _check_and_apply_config_migration(assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None)-- out = capsys.readouterr().out- assert "Could not check config version" in out, out- assert "hermes config migrate" in out, outdiff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.pyindex c73cc170e25..87086167351 100644--- a/tests/hermes_cli/test_update_fleet_restart_pending.py+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py@@ -127,8 +127,6 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):)monkeypatch.setattr(update_cmd, "_update_node_dependencies", lambda: [])monkeypatch.setattr(update_cmd_deps, "_update_node_dependencies", lambda: [])- monkeypatch.setattr(update_cmd, "_purge_stale_hermes_modules", lambda: None)- monkeypatch.setattr(hermes_main, "_purge_stale_hermes_modules", lambda: None)import hermes_cli.gateway as hermes_gateway@@ -347,7 +345,6 @@ def test_run_pending_restart_true_when_no_gateways(monkeypatch, capsys):monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda **k: [])- monkeypatch.setattr(hermes_main, "_purge_stale_hermes_modules", lambda: None)# An empty PID scan is insufficient; every supervisor scope must answer empty.monkeypatch.setattr(update_cmd_fleet, "_systemd_gateway_unit_listings", lambda: [@@ -767,3 +764,4 @@ def test_startup_warn_kept_when_receipt_owed_gateway_is_down(monkeypatch, capsysassert "did not restart running gateways" in capsys.readouterr().errassert update_cmd._fleet_restart_pending_marker_path().exists()+diff --git a/tests/hermes_cli/test_update_no_gateway_restart.py b/tests/hermes_cli/test_update_no_gateway_restart.pyindex dda29a71325..2b732ab67de 100644--- a/tests/hermes_cli/test_update_no_gateway_restart.py+++ b/tests/hermes_cli/test_update_no_gateway_restart.py@@ -46,7 +46,7 @@ def test_pulled_update_defers_restart_and_keeps_marker_under_flag():_opts(no_gateway_restart=True), gateway_mode=False,is_fork=False, desktop_dir="/tmp", had_desktop_app_before_update=False,pre_update_snapshot_id=None, _pre_update_plan=None,- _windows_gateway_resume=None,+ _windows_gateway_resume=None, args=SimpleNamespace(no_gateway_restart=True, yes=True),)mock_restart.assert_not_called()mock_verify.assert_not_called()diff --git a/tests/hermes_cli/test_update_post_swap_handoff.py b/tests/hermes_cli/test_update_post_swap_handoff.pynew file mode 100644index 00000000000..0ca4b5387b2--- /dev/null+++ b/tests/hermes_cli/test_update_post_swap_handoff.py@@ -0,0 +1,99 @@+"""``hermes update`` finishes in an interpreter born on the pulled code (hermes_cli/update_handoff.py).++Class: every post-swap phase used to run in the pre-pull process and lazily import NEW source+into an OLD ``sys.modules`` graph, so any rename between the two commits crashed the updater+after the code swap (#87134, #112465, #112558, #112604). The boundary under test: the parent+stops at the swap and re-executes ``hermes update --post-swap <file>``; the child resumes the+receipt and owns the tail.+"""++import json+import os+import sys+from types import SimpleNamespace++import pytest++from hermes_cli import update_cmd, update_handoff, update_receipt+from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan+from hermes_cli.update_lock import HANDOFF_PID_ENV+++def _opts():+ return SimpleNamespace(+ pre_update_version="0.21.3", active_lazy_features=["voice"], active_tool_dependencies={"x": 1})++[email protected]_post_swap_handoff+def test_parent_reexecs_tail_on_pulled_tree_and_relays_exit_code(monkeypatch, tmp_path):+ """The pre-swap interpreter runs NOTHING after the swap: it spawns ``python -m hermes_cli.main+ update <flags> --post-swap <file>`` with the detached receipt + plan in the file and exits+ with the child's code, leaving no open receipt for its own boundary to finalize."""+ monkeypatch.setattr(update_handoff, "_running_from_windows_shim", lambda: False)+ spawned = {}++ def fake_run(cmd, env=None, **kwargs):+ spawned["cmd"], spawned["env"] = cmd, env+ spawned["payload"] = json.loads(open(cmd[cmd.index("--post-swap") + 1], encoding="utf-8").read())+ return SimpleNamespace(returncode=7)++ monkeypatch.setattr(update_handoff.subprocess, "run", fake_run)+ update_receipt._current = None+ update_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)++ 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)++ assert exit_info.value.code == 7+ assert 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())+ 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+ # Detached: the parent's command-boundary finalize is a no-op — the child writes the receipt.+ assert update_receipt._current is None+ assert update_receipt.finalize_pending_update_receipt(7) is 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"+ handoff.write_text(json.dumps({+ "swap": "git", "branch": "main", "pre_pull_sha": "a" * 40, "is_fork": True,+ "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,+ "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")+ seen = {}+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (False, ["git"], True))+ 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,+ assume_yes=True, keep_stash=False, switch_branch=False, discard_local_changes=False))+ update_receipt._current = None++ update_cmd._run_post_swap_phase(SimpleNamespace(post_swap=str(handoff), yes=True), gateway_mode=False)++ assert update_receipt._current.data["started_at"] == started+ assert update_receipt._current.data["post_swap_pid"] == os.getpid()+ assert [s["name"] for s in update_receipt._current.data["steps"]] == ["pre_update_backup"]+ git_cmd, branch, pre_pull_sha, opts = seen["args"]+ assert (git_cmd, branch, pre_pull_sha) == (["git"], "main", "a" * 40)+ # Pre-update snapshots come from the payload, never re-read from the new tree.+ assert opts.pre_update_version == "0.21.3" and opts.active_lazy_features == ["voice"]+ plan = 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+ update_receipt._current = Nonediff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.pyindex 95ab333b4c2..82be3d45cf6 100644--- a/tests/hermes_cli/test_update_self_lock.py+++ b/tests/hermes_cli/test_update_self_lock.py@@ -251,7 +251,7 @@ def test_pre_fetch_flow_has_no_self_lock_preflight():assert "_m()._abort_dependency_sync_if_self_locked" not in pre_fetch# ... and it must still guard the dependency sync after the code swap# (the sync itself lives in _sync_python_dependencies_after_pull).- post_fetch = src[fetch_idx:] + inspect.getsource(update_cmd._apply_pulled_update)+ post_fetch = src[fetch_idx:] + inspect.getsource(update_cmd._finish_pulled_update)assert "_sync_python_dependencies_after_pull(" in post_fetchsync_src = inspect.getsource(update_cmd._sync_python_dependencies_after_pull)assert "_m()._abort_dependency_sync_if_self_locked" in sync_src@@ -260,7 +260,7 @@ def test_pre_fetch_flow_has_no_self_lock_preflight():def test_zip_update_guards_dependency_sync():import inspect- src = inspect.getsource(update_cmd._update_via_zip)+ src = inspect.getsource(update_cmd._finish_zip_update)swap_idx = src.index("Updating Python dependencies")assert "_abort_dependency_sync_if_self_locked" in src[:swap_idx]diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.pyindex 025aac8a00b..2e756346963 100644--- a/tests/hermes_cli/test_update_stale_dashboard.py+++ b/tests/hermes_cli/test_update_stale_dashboard.py@@ -857,102 +857,20 @@ class TestCmdlineCapture:assert main_dashboard._dashboard_cmdline_for_pid(123) is None-class TestPostUpdateStaleModuleReload:- """Regression tests for the post-update stale-module ImportError.-- ``hermes update`` runs in the PRE-pull Python process. When the update- adds a new symbol to ``hermes_cli._subprocess_compat`` (as #87134 added- ``bounded_probe_run``), the post-update dashboard cleanup's lazy- ``from hermes_cli._subprocess_compat import bounded_probe_run`` hits the- stale cached module and crashes with ImportError — after the code update- itself already succeeded. The cleanup entry point must force-reload the- process-scan modules first (PR #87757 + ZIP-path widening).- """-- def test_cleanup_reloads_before_scanning(self):- """_finish_dashboard_update_cleanup must reload the process-scan- modules BEFORE calling _kill_stale_dashboard_processes, on every- call path (git update and ZIP fallback both route here)."""- from hermes_cli import update_cmd-- order: list[str] = []- with patch.object(- update_cmd, "_reload_process_scan_modules",- side_effect=lambda: order.append("reload"),- ), patch(- "hermes_cli.main._kill_stale_dashboard_processes",- side_effect=lambda **kw: order.append("kill") or {"unrecovered": []},- ):- update_cmd._finish_dashboard_update_cleanup([])-- assert order == ["reload", "kill"]-- def test_node_failures_skip_reload_and_kill(self):- """A failed Node refresh leaves the running dashboard untouched —- no reload, no kill (existing safety rule preserved)."""- from hermes_cli import update_cmd-- with patch.object(update_cmd, "_reload_process_scan_modules") as mock_reload, \- patch("hermes_cli.main._kill_stale_dashboard_processes") as mock_kill:- update_cmd._finish_dashboard_update_cleanup(["dashboard"])-- mock_reload.assert_not_called()- mock_kill.assert_not_called()-- def test_reload_restores_missing_symbol(self):- """Simulate the stale-module state: strip ``bounded_probe_run`` off- the cached module object (what an old pre-#87134 module looks like)- and verify the reload restores it from disk — the exact state the- Windows update crash came from."""- import hermes_cli._subprocess_compat as compat- from hermes_cli import update_cmd-- assert hasattr(compat, "bounded_probe_run")- try:- delattr(compat, "bounded_probe_run")- assert not hasattr(compat, "bounded_probe_run")-- update_cmd._reload_process_scan_modules()-- stale = sys.modules["hermes_cli._subprocess_compat"]- assert hasattr(stale, "bounded_probe_run")- finally:- importlib.reload(sys.modules["hermes_cli._subprocess_compat"])- importlib.reload(sys.modules["hermes_cli.dashboard_procs"])-- def test_reload_failure_is_nonfatal(self):- """A reload failure must log and continue, never raise — the cleanup- step runs after the update already succeeded."""- from hermes_cli import update_cmd-- with patch("importlib.reload", side_effect=RuntimeError("boom")):- update_cmd._reload_process_scan_modules() # must not raise-- def test_config_reload_list_includes_process_scan_modules(self):- """PR #87757's half: the git-path pre-cleanup reload also refreshes- the process-scan modules (belt to the entry-point suspenders)."""- from hermes_cli import update_cmd-- reloaded: list[str] = []- with patch("importlib.reload", side_effect=lambda m: reloaded.append(m.__name__)):- update_cmd._reload_config_modules()-- assert "hermes_cli._subprocess_compat" in reloaded- assert "hermes_cli.dashboard_procs" in reloaded+class TestPostUpdateDashboardCleanupIsolation:+ """Post-update dashboard cleanup is one isolated step among the others."""def test_cleanup_failure_is_isolated_and_recorded(self, capsys):- """#112604 class: the cleanup runs pulled ``dashboard_procs`` in the pre-pull interpreter,- so a symbol gap raises AttributeError from inside the scan. That exception used to- propagate out of ``_finish_dashboard_update_cleanup`` and abort the fleet-verification- tail (matrix, reconciliation, inner receipt finalize). It must be contained, made- visible, and recorded as a failed step on the open receipt."""+ """A failure inside the dashboard scan (#112604) must not abort the fleet-verification+ tail (matrix, reconciliation, inner receipt finalize): contained, visible, recorded as+ a failed step on the open receipt."""import hermes_cli.update_receipt as urfrom hermes_cli import update_cmdur._current = Nonetry:ur.begin_update_receipt()- with patch.object(update_cmd, "_reload_process_scan_modules"), patch(+ with patch("hermes_cli.main._kill_stale_dashboard_processes",side_effect=AttributeError("module 'hermes_cli.main_dashboard' has no attribute '_loaded_launchd_backend_jobs'"diff --git a/tests/hermes_cli/test_update_stale_module_purge.py b/tests/hermes_cli/test_update_stale_module_purge.pydeleted file mode 100644index 0243ab8c7d4..00000000000--- a/tests/hermes_cli/test_update_stale_module_purge.py+++ /dev/null@@ -1,349 +0,0 @@-"""Tests for _purge_stale_hermes_modules — the class fix for stale-sys.modules breaking the gateway auto-restart after `hermes update`.--Field failure (2026-08-20, Teknium's Linux box): `hermes update` pulled a-checkout where hermes_cli/gateway.py newly imports `line_input` from-hermes_cli.cli_output, but the updater process had cli_output cached from-before that symbol existed. The function-level `from hermes_cli.gateway-import ...` in the restart phase raised ImportError, the whole phase-aborted, and the running gateway kept serving pre-update code.--The old mitigation (_UPDATE_RUNTIME_RELOAD_MODULES) reloaded 3 hardcoded-modules — re-fixed per symptom. The purge evicts EVERY cached module whose-top-level name is a ``.py`` file or package in the checkout root (minus-``tests``) so later imports rebuild a self-consistent module graph from the-updated checkout.-"""--from __future__ import annotations--import importlib-import json-import sys-import types-from unittest.mock import patch--import pytest--from hermes_cli import main as cli_main-from hermes_cli import update_cmd--[email protected](autouse=True)-def _restore_sys_modules():- """Snapshot & restore sys.modules around each test.-- The purge under test evicts real Hermes modules from the cache; later- tests in the same process may hold references to the evicted module- objects (e.g. `patch.object` targets), so put the originals back.-- The eviction also drops the stale submodule attribute a purged module left on its PARENT- package (see `_evict_module`), which `sys.modules` alone does not cover: after the test,- `hermes_cli.X` could hold a freshly imported copy while the cache holds the original, and a- later `patch("hermes_cli.X.fn")` would miss the module the code under test resolves. Restore- the submodule bindings of the checkout-owned packages too — only those, so any other package- global a test leaks still shows up as pollution.- """- from hermes_cli.update_cmd_maint import _stale_purge_prefixes-- snapshot = dict(sys.modules)- owned = _stale_purge_prefixes()- bindings = {- mod: {k: v for k, v in vars(mod).items() if isinstance(v, types.ModuleType)}- for name, mod in snapshot.items()- if mod is not None- and name.split(".", 1)[0] in owned- and "__path__" in vars(mod) # packages only: they carry submodules- }- yield- for name, mod in snapshot.items():- sys.modules[name] = mod- for name in list(sys.modules):- if name not in snapshot:- del sys.modules[name]- for mod, attrs in bindings.items():- current = vars(mod)- for key in [k for k, v in current.items() if isinstance(v, types.ModuleType) and k not in attrs]:- del current[key]- current.update(attrs)---def _fake_module(name: str) -> types.ModuleType:- mod = types.ModuleType(name)- mod.__stale_sentinel__ = True- return mod---def _install_stale_main_dashboard(**attrs) -> types.ModuleType:- """A pre-pull ``main_dashboard`` stand-in, bound the way ``hermes_cli.main``'s eager import- leaves it: in ``sys.modules`` AND as an attribute of the protected ``hermes_cli`` package."""- import hermes_cli-- stale = _fake_module("hermes_cli.main_dashboard")- vars(stale).update(attrs)- sys.modules["hermes_cli.main_dashboard"] = stale- hermes_cli.main_dashboard = stale- return stale---def test_purge_evicts_hermes_prefixed_modules():- victims = [- "hermes_cli.cli_output",- "hermes_cli.gateway",- "gateway.status",- "tools.ansi_strip",- "tui_gateway.server",- "agent.memory_store",- ]- added = []- for name in victims:- if name not in sys.modules:- sys.modules[name] = _fake_module(name)- added.append(name)- try:- cli_main._purge_stale_hermes_modules()- for name in victims:- mod = sys.modules.get(name)- assert mod is None or not getattr(mod, "__stale_sentinel__", False), (- f"{name} survived the purge"- )- finally:- for name in added:- sys.modules.pop(name, None)---def test_purge_protects_executing_modules():- # The updater's own modules must survive — they're running this code.- cli_main._purge_stale_hermes_modules()- assert sys.modules.get("hermes_cli.update_cmd") is update_cmd- assert sys.modules.get("hermes_cli.main") is cli_main- assert "hermes_cli" in sys.modules---def test_purge_preserves_active_update_receipt(tmp_path, monkeypatch):- """A receipt begun before the post-pull purge must still be finalizable."""- import hermes_cli.update_receipt as receipt-- receipt_dir = tmp_path / "update_receipts"- monkeypatch.setattr(receipt, "_receipt_dir", lambda: receipt_dir)- receipt._current = None- post_purge_receipt = receipt- try:- receipt.begin_update_receipt()- receipt.record_step("git_pull", True, "updated checkout")-- cli_main._purge_stale_hermes_modules()- post_purge_receipt = importlib.import_module("hermes_cli.update_receipt")- path = post_purge_receipt.finalize_update_receipt("success")-- assert path is not None and path.is_file()- latest = json.loads((receipt_dir / "latest.json").read_text(encoding="utf-8"))- assert latest["outcome"] == "success"- assert latest["steps"][0]["name"] == "git_pull"- finally:- receipt._current = None- post_purge_receipt._current = None---def test_receipt_write_survives_a_mixed_module_graph(tmp_path, monkeypatch, capsys):- """#112465 / #112558: the activation run wrote NO receipt while the no-op run did. The- receipt is written by the pre-pull interpreter after the purge; resolving the receipt dir- through ``hermes_cli.config`` re-executed the pulled config.py against a stale top-level- ``utils`` (``from utils import file_signature`` → ImportError) and the whole write was- swallowed at debug level. The receipt path must not depend on any purgeable module, and a- write failure must be visible."""- import hermes_cli- import hermes_cli.update_receipt as receipt-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- # Pre-pull world: a `utils` without the symbols the pulled config.py imports, and the- # purged (evicted + unbound) hermes_cli.config so any import of it re-executes source.- real_utils = sys.modules.get("utils")- sys.modules["utils"] = types.ModuleType("utils")- evicted = {k: sys.modules.pop(k) for k in list(sys.modules) if k.startswith("hermes_cli.config")}- stale_attr = vars(hermes_cli).pop("config", None)- receipt._current = None- try:- receipt.begin_update_receipt()- receipt.record_step("git_pull", True)- path = receipt.finalize_update_receipt("partial")- finally:- receipt._current = None- sys.modules.pop("utils", None)- if real_utils is not None:- sys.modules["utils"] = real_utils- for k in [k for k in sys.modules if k.startswith("hermes_cli.config")]:- del sys.modules[k]- sys.modules.update(evicted)- if stale_attr is not None:- hermes_cli.config = stale_attr-- assert path is not None and path.is_file(), "receipt lost to the mixed sys.modules graph"- assert path.parent == tmp_path / "logs" / "update_receipts"- assert json.loads(path.read_text(encoding="utf-8"))["outcome"] == "partial"---def test_receipt_write_failure_is_visible(tmp_path, monkeypatch, capsys):- """A begun-but-unwritten receipt is the run operators must post-mortem; the failure was- logged at DEBUG only, indistinguishable from "no receipt expected" (#112465)."""- import hermes_cli.update_receipt as receipt-- def _boom():- raise OSError("disk says no")-- monkeypatch.setattr(receipt, "_receipt_dir", _boom)- receipt._current = None- try:- receipt.begin_update_receipt()- assert receipt.finalize_update_receipt("success") is None- finally:- receipt._current = None- assert "receipt not written: disk says no" in capsys.readouterr().out---def test_purge_leaves_prefix_lookalikes_alone():- # `gateway_foo` starts with the string prefix "gateway" but is NOT the- # gateway package — the root-segment check must spare it.- lookalikes = ["gatewayd", "toolshed", "agents_external"]- added = []- for name in lookalikes:- if name not in sys.modules:- sys.modules[name] = _fake_module(name)- added.append(name)- try:- cli_main._purge_stale_hermes_modules()- for name in lookalikes:- assert name in sys.modules, f"{name} was wrongly purged"- finally:- for name in added:- sys.modules.pop(name, None)---def test_purge_never_raises_on_weird_sys_modules():- # Entries with None values (import machinery quirk) must not break it.- sys.modules["hermes_cli._purge_test_none"] = None # type: ignore[assignment]- try:- cli_main._purge_stale_hermes_modules()- finally:- sys.modules.pop("hermes_cli._purge_test_none", None)---def test_stale_symbol_scenario_end_to_end():- """Reproduce the field failure shape: a cached module missing a symbol- that freshly-imported code needs — purge, then re-import resolves it."""- name = "hermes_cli.cli_output"- real = sys.modules.get(name)- # Install a stale stand-in WITHOUT line_input (pre-d0132b582 world).- stale = types.ModuleType(name)- sys.modules[name] = stale- try:- # The failure mode: importing the symbol from the stale cache dies.- try:- from hermes_cli.cli_output import line_input # noqa: F401- raised = False- except ImportError:- raised = True- assert raised, "precondition: stale module must lack line_input"-- cli_main._purge_stale_hermes_modules()-- # Post-purge, the import resolves against real on-disk source.- from hermes_cli.cli_output import line_input # noqa: F401- finally:- sys.modules.pop(name, None)- if real is not None:- sys.modules[name] = real---def test_purge_keeps_plan_record_class_identity():- # The pre-update plan is built BEFORE the purge; reconciliation after it filters with- # ``isinstance(r, RuntimeRecord)``. An evicted ``update_inventory`` yields a fresh class,- # every record fails the check, and the plan-vs-execution report goes silently empty.- from hermes_cli.update_inventory import RuntimeRecord as before-- cli_main._purge_stale_hermes_modules()- from hermes_cli.update_inventory import RuntimeRecord as after- assert after is before---def test_stale_top_level_utils_scenario_end_to_end():- """The 2026-09-12 field failure: `hermes update` from a pre-`base_url_origin`- checkout kept the old top-level `utils` cached, and the restart phase's import of- `hermes_cli.gateway` died on `from utils import base_url_origin`."""- stale = types.ModuleType("utils")- real = sys.modules.get("utils")- sys.modules["utils"] = stale- try:- try:- from utils import base_url_origin # noqa: F401- raised = False- except ImportError:- raised = True- assert raised, "precondition: stale utils must lack base_url_origin"-- cli_main._purge_stale_hermes_modules()-- from utils import base_url_origin # noqa: F401- finally:- sys.modules.pop("utils", None)- if real is not None:- sys.modules["utils"] = real---def test_purge_protects_hermes_logging():- # A second copy of hermes_logging starts a second QueueListener over the same log- # files while the first keeps running: its listener/handler state is module-global.- real = sys.modules.get("hermes_logging")- sentinel = _fake_module("hermes_logging")- sys.modules["hermes_logging"] = sentinel- try:- cli_main._purge_stale_hermes_modules()- assert sys.modules.get("hermes_logging") is sentinel- finally:- sys.modules.pop("hermes_logging", None)- if real is not None:- sys.modules["hermes_logging"] = real---def test_purge_drops_stale_package_attribute_so_from_import_rereads_source():- """Field failure #112604: `hermes_cli.main` imports `main_dashboard` at CLI start, so the- updater process holds it as an ATTRIBUTE of the (protected) `hermes_cli` package. Evicting- only the sys.modules entry left `from hermes_cli import main_dashboard` handing the PRE-pull- module to the dashboard cleanup, which then died on a symbol the pull had added- (`AttributeError ... has no attribute '_loaded_launchd_backend_jobs'`).- """- stale = _install_stale_main_dashboard()-- cli_main._purge_stale_hermes_modules()-- assert not hasattr(stale, "_loaded_launchd_backend_jobs")- from hermes_cli import main_dashboard as pulled-- assert pulled is not stale, "call-time import was handed the pre-pull module"- assert getattr(pulled, "__stale_sentinel__", False) is False- assert hasattr(pulled, "_loaded_launchd_backend_jobs")---def test_dashboard_cleanup_survives_a_pre_pull_main_dashboard():- """End-to-end shape of #112604: the post-update dashboard cleanup runs after the purge, and- `_kill_stale_dashboard_processes` resolves its helpers then. With the pre-pull- `main_dashboard` still reachable, the cleanup aborted on- `AttributeError: module 'hermes_cli.main_dashboard' has no attribute- '_loaded_launchd_backend_jobs'` — after the code update had already succeeded.- """- # The pre-pull module DOES scan processes; it only lacks the launchd symbol the pull added,- # so a cleanup handed this module reaches the launchd snapshot line and dies there.- _install_stale_main_dashboard(_find_stale_dashboard_pids=lambda **_kw: [999999])-- cli_main._purge_stale_hermes_modules()-- # The pulled scanner reads the host's process table through `dashboard_procs`; the stale- # stand-in never does. Stubbing the table keeps the test off real processes AND records- # which module the cleanup resolved.- from hermes_cli import dashboard_procs- table_reads = []- with patch.object(dashboard_procs, "_iter_process_table", lambda: table_reads.append(1) or []):- result = dashboard_procs._kill_stale_dashboard_processes("regression")-- assert isinstance(result, dict), "cleanup aborted instead of returning its result"- assert table_reads, "cleanup was handed the pre-pull module instead of the pulled one"diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.pyindex 84058bee17f..858ce17e016 100644--- a/tests/hermes_cli/test_update_yes_flag.py+++ b/tests/hermes_cli/test_update_yes_flag.py@@ -63,7 +63,6 @@ def _make_run_side_effect(class TestUpdateYesConfigMigration:"""--yes auto-answers the config-migration prompt and skips API-key prompts."""- @patch("hermes_cli.update_cmd._reload_config_modules")@patch("hermes_cli.update_cmd._run_migrate_config_fresh")@patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))@patch("hermes_cli.config.get_missing_config_fields", return_value=[])@@ -78,7 +77,6 @@ class TestUpdateYesConfigMigration:_mock_missing_cfg,_mock_version,mock_migrate,- _mock_reload,capsys,):mock_run.side_effect = _make_run_side_effect(@@ -104,7 +102,6 @@ class TestUpdateYesConfigMigration:# The "Would you like to configure them now?" prompt text never appears.assert "Would you like to configure them now?" not in out- @patch("hermes_cli.update_cmd._reload_config_modules")@patch("hermes_cli.update_cmd._run_migrate_config_fresh")@patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))@patch("hermes_cli.config.get_missing_config_fields", return_value=[])@@ -119,7 +116,6 @@ class TestUpdateYesConfigMigration:_mock_missing_cfg,_mock_version,mock_migrate,- _mock_reload,capsys,):"""Regression guard: without --yes, the TTY prompt path still fires."""@@ -164,7 +160,6 @@ class TestUnicodeDecodeErrorInUpdatePrompts:the exception escape and crash `hermes update` mid-flight."""- @patch("hermes_cli.update_cmd._reload_config_modules")@patch("hermes_cli.update_cmd._run_migrate_config_fresh")@patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))@patch("hermes_cli.config.get_missing_config_fields", return_value=[])@@ -179,7 +174,6 @@ class TestUnicodeDecodeErrorInUpdatePrompts:_mock_missing_cfg,_mock_version,mock_migrate,- _mock_reload,capsys,):mock_run.side_effect = _make_run_side_effect(