The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): purge every top-level checkout module, not just five packages
Hubert Nimitanakit29758a4eb256
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 38e36487843..1d2ca471e31 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -97,8 +97,9 @@ from hermes_cli.update_cmd_git import ( # noqa: F401_prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,_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_PREFIXES,- _STALE_PURGE_PROTECTED, _UPDATE_RUNTIME_RELOAD_MODULES, _clear_stale_sqlite_sidecars,+ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,+ _STALE_PURGE_EXCLUDED_TOP_LEVEL, _STALE_PURGE_PREFIXES, _STALE_PURGE_PROTECTED,+ _UPDATE_RUNTIME_RELOAD_MODULES, _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,@@ -106,7 +107,8 @@ from hermes_cli.update_cmd_maint import ( # noqa: F401_print_verified_update_completion, _purge_stale_hermes_modules, _read_project_version,_reload_process_scan_modules, _reload_updated_runtime_modules,_resolve_pre_update_backup_mode, _restore_state_db_from_snapshot,- _run_post_update_maintenance, _run_pre_update_backup, _sweep_bytecode_after_update,+ _run_post_update_maintenance, _run_pre_update_backup, _stale_purge_prefixes,+ _sweep_bytecode_after_update,_update_complete_message, _verify_and_restore_one_state_db,_verify_and_restore_state_dbs_post_update)logger = logging.getLogger(__name__)diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex 78e995d99e1..a5dfe409e39 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -25,13 +25,22 @@ logger = logging.getLogger("hermes_cli.update_cmd")_UPDATE_RUNTIME_RELOAD_MODULES = "hermes_constants", "tools.environments.local", "tools.lazy_deps"-#: Package prefixes whose cached modules go stale when the checkout changes under this-#: process; purged (not reloaded) so any LATER import chain resolves against fresh source.+#: Fallback for the purge's top-level names when the checkout scan below cannot run; the+#: live set comes from ``_stale_purge_prefixes()``._STALE_PURGE_PREFIXES = "hermes_cli", "gateway", "tools", "tui_gateway", "agent"+#: Owned by the checkout but never purged: pytest resolves fixtures through the identity of+#: its own already-imported test modules, and evicting them mid-session breaks that.+_STALE_PURGE_EXCLUDED_TOP_LEVEL = frozenset({"tests"})+#: 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.-_STALE_PURGE_PROTECTED = frozenset({"hermes_cli", "hermes_cli.main", "hermes_cli.hermes_logging"})+#: ``hermes_logging`` is protected for a different reason: its queue listener, handler list and+#: ``_logging_initialized`` flag are module globals, so a fresh copy starts a SECOND+#: QueueListener over the same log files while the first one keeps running.+_STALE_PURGE_PROTECTED = frozenset({+ "hermes_cli", "hermes_cli.main", "hermes_cli.hermes_logging", "hermes_logging",+})#: 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@@ -88,6 +97,26 @@ def _reload_modules(names, *, modules, log) -> None: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`` was the field case.+ """+ from hermes_cli.update_cmd import _m+ names = set(_STALE_PURGE_PREFIXES)+ try:+ 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)+ except OSError as exc:+ logger.debug("Could not scan the checkout for purge prefixes: %s", exc)+ return frozenset(names) - _STALE_PURGE_EXCLUDED_TOP_LEVEL++def _purge_stale_hermes_modules() -> None:"""Evict every cached Hermes module after the checkout changed in-place. Never raises.@@ -100,12 +129,13 @@ def _purge_stale_hermes_modules() -> None: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_PROTECTEDand not name.startswith(_STALE_PURGE_PROTECTED_PREFIX)# Root-package check: startswith() alone also matches unrelated ``gateway_foo``.- and name.split(".", 1)[0] in _STALE_PURGE_PREFIXES+ and name.split(".", 1)[0] in prefixesand modules.pop(name, None) is not None]if purged:diff --git a/tests/hermes_cli/test_update_stale_module_purge.py b/tests/hermes_cli/test_update_stale_module_purge.pyindex 8084c0db08e..cbf4acf52c6 100644--- a/tests/hermes_cli/test_update_stale_module_purge.py+++ b/tests/hermes_cli/test_update_stale_module_purge.py@@ -172,3 +172,81 @@ def test_purge_keeps_plan_record_class_identity():cli_main._purge_stale_hermes_modules()from hermes_cli.update_inventory import RuntimeRecord as afterassert after is before+++def test_purge_prefixes_cover_checkout_top_level_modules():+ # The static tuple listed 5 packages and no top-level module, so `utils`,+ # `hermes_constants` and friends stayed cached through every update.+ prefixes = update_cmd._stale_purge_prefixes()+ for name in ("utils", "hermes_constants", "hermes_bootstrap", "plugins", "providers"):+ assert name in prefixes, f"{name} is not covered by the purge"+ for name in ("hermes_cli", "gateway", "tools", "tui_gateway", "agent"):+ assert name in prefixes+++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_spares_the_tests_package():+ # pytest resolves fixtures through the identity of already-imported test modules.+ sentinel = _fake_module("tests.hermes_cli._purge_probe")+ sys.modules["tests.hermes_cli._purge_probe"] = sentinel+ try:+ cli_main._purge_stale_hermes_modules()+ assert sys.modules.get("tests.hermes_cli._purge_probe") is sentinel+ finally:+ sys.modules.pop("tests.hermes_cli._purge_probe", None)+++def test_purge_prefixes_follow_project_root(tmp_path, monkeypatch):+ # The scan must read main.PROJECT_ROOT, not this module's own __file__: tests and the+ # installer both relocate the checkout, and a divergent root silently purges nothing.+ (tmp_path / "zzz_probe.py").write_text("", encoding="utf-8")+ (tmp_path / "zzz_pkg").mkdir()+ (tmp_path / "zzz_pkg" / "__init__.py").write_text("", encoding="utf-8")+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path)++ prefixes = update_cmd._stale_purge_prefixes()+ assert {"zzz_probe", "zzz_pkg"} <= prefixes+ assert set(update_cmd._STALE_PURGE_PREFIXES) <= prefixes+++def test_purge_prefixes_fall_back_when_root_unreadable(tmp_path, monkeypatch):+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path / "does-not-exist")+ assert update_cmd._stale_purge_prefixes() == frozenset(update_cmd._STALE_PURGE_PREFIXES)