The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(cli): re-export decomposed command modules lazily, ~60ms off every CLI start
Adolaniumee1731b13c9c
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 05c79a16951..f09cde9ec1f 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -436,7 +436,6 @@ from typing import Optionalimport functools as _functools-from hermes_cli.sessions_cmd import cmd_sessions # noqa: F401from hermes_cli.subcommands._shared import add_accept_hooks_flag as _add_accept_hooks_flagfrom hermes_cli.subcommands.cron import build_cron_parserfrom hermes_cli.subcommands.sync import build_sync_parser@@ -4363,13 +4362,168 @@ def _remove_custom_provider(config):_LAZY_MODEL_EXPORTS = ("_PROVIDER_MODELS",)+# The main.py decomposition moved the sessions/update/dashboard command+# implementations into their own modules, but main.py still re-exports their+# surface so argparse wiring and test monkeypatches on hermes_cli.main.<name>+# keep resolving unchanged. Importing those modules eagerly costs ~50ms on+# every `hermes` invocation, including fast paths like `hermes --version`+# that never run a subcommand. Resolve the re-exports through the module+# __getattr__ below instead, so each module is only imported when one of its+# names is actually touched. Monkeypatching keeps working: patch.object sets+# a real module attribute, which shadows __getattr__.+_LAZY_COMMAND_EXPORTS = {+ "hermes_cli.sessions_cmd": (+ "cmd_sessions",+ ),+ "hermes_cli.dashboard_procs": (+ "_detect_concurrent_hermes_instances",+ "_filter_dashboard_respawn_candidates",+ "_kill_stale_dashboard_processes",+ "_scan_dashboard_processes",+ ),+ "hermes_cli.update_cmd": (+ "_add_upstream_remote",+ "_atomic_replace_dir",+ "_capture_active_lazy_features",+ "_capture_active_tool_dependencies",+ "_capture_head_sha",+ "_cmd_update_check",+ "_cmd_update_impl",+ "_cold_start_windows_gateway_after_update",+ "_count_commits_between",+ "_detect_self_loaded_native_modules",+ "_detect_venv_python_processes",+ "_defer_update_for_self_lock",+ "_discard_lockfile_churn",+ "_discard_stashed_changes",+ "_ensure_acp_launcher",+ "_ensure_fhs_path_guard",+ "_ensure_uv_for_termux",+ "_finish_dashboard_update_cleanup",+ "_for_each_systemd_gateway_unit",+ "_format_concurrent_instances_message",+ "_format_time_ago",+ "_format_venv_python_holders_message",+ "_gateway_prompt",+ "_get_origin_url",+ "_has_upstream_remote",+ "_install_psutil_android_compat",+ "_invalidate_update_cache",+ "_is_android_python",+ "_is_fork",+ "_leftover_pausable_gateway_pids",+ "_log_only_write",+ "_mark_skip_upstream_prompt",+ "_npm_bin_exists",+ "_npm_lockfile_changed",+ "_npm_manifest_paths",+ "_npm_manifests_digest",+ "_orphaned_desktop_backend_pids",+ "_pause_windows_gateways_for_update",+ "_print_curator_first_run_notice",+ "_print_curator_recent_run_notice",+ "_print_fts_optimize_available_notice",+ "_print_stash_cleanup_guidance",+ "_print_update_completion",+ "_record_npm_lockfile_hash",+ "_refresh_active_lazy_features",+ "_refresh_active_memory_provider_dependencies",+ "_refresh_bootstrap_cache_scripts",+ "_refresh_windows_gateway_launchers",+ "_reload_updated_runtime_modules",+ "_resolve_pre_update_backup_mode",+ "_resolve_stash_selector",+ "_restart_phase_failure_is_incomplete",+ "_restore_active_tool_dependencies",+ "_restore_stashed_changes",+ "_resume_windows_gateways_after_update",+ "_run_logged_subprocess",+ "_run_pre_update_backup",+ "_should_skip_upstream_prompt",+ "_stash_apply_failed_only_on_existing_untracked",+ "_stash_local_changes_if_needed",+ "_stop_process_trees",+ "_surviving_gateway_pids_after_failed_restart",+ "_sync_fork_with_upstream",+ "_sync_with_upstream_if_needed",+ "_update_node_dependencies",+ "_update_via_zip",+ "_upgrade_pip_before_lazy_refresh",+ "_validate_critical_files_syntax",+ "_validate_critical_modules_import",+ "_venv_core_imports_healthy",+ "_venv_launcher_ancestors",+ "_wait_for_windows_update_gateway_exit",+ "_warn_gateway_restart_phase_aborted",+ "_warn_incomplete_gateway_fleet_restart",+ "_web_build_toolchain_ready",+ "_web_toolchain_roots",+ "_write_lazy_refresh_incomplete_marker",+ "_write_marker_file",+ "_write_update_incomplete_marker",+ "_write_update_planned_stop_marker",+ "_UPDATE_RUNTIME_RELOAD_MODULES",+ "_UPDATE_CRITICAL_FILES",+ "_UPDATE_CRITICAL_MODULES",+ "OFFICIAL_REPO_URLS",+ "OFFICIAL_REPO_URL",+ "SKIP_UPSTREAM_PROMPT_FILE",+ "_PRE_UPDATE_SNAPSHOT_KEEP",+ "_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE",+ ),+}++_LAZY_COMMAND_ATTR_TO_MODULE = {+ attr: module for module, attrs in _LAZY_COMMAND_EXPORTS.items() for attr in attrs+}++# Back-compat alias: some tests and external callers import the old warn-only+# name. The kill behaviour replaced it; resolve to the new name lazily.+_LAZY_COMMAND_ALIASES = {+ "_warn_stale_dashboard_processes": (+ "hermes_cli.dashboard_procs",+ "_kill_stale_dashboard_processes",+ ),+}+++def _self():+ """This module, for attribute access at call time.++ Bare-name global lookups inside this module do not go through the PEP 562+ __getattr__ below, so internal callers of the lazily re-exported names use+ _self().<name> instead. That resolves the lazy re-export on first use and+ keeps monkeypatches on hermes_cli.main.<name> working, exactly like a+ globals lookup did. ``sys`` is imported locally because some tests patch+ this module's ``sys`` attribute.+ """+ import sys as _sys++ return _sys.modules[__name__]++def __getattr__(name):- """Defer the model-catalog import until something actually reads it."""+ """Defer the model-catalog and command-module imports until first read."""if name in _LAZY_MODEL_EXPORTS:from hermes_cli.models import _PROVIDER_MODELS# Cache on the module so subsequent accesses skip the import machinery.globals()[name] = _PROVIDER_MODELSreturn _PROVIDER_MODELS+ module = _LAZY_COMMAND_ATTR_TO_MODULE.get(name)+ if module is not None:+ import importlib++ value = getattr(importlib.import_module(module), name)+ globals()[name] = value+ return value+ alias = _LAZY_COMMAND_ALIASES.get(name)+ if alias is not None:+ import importlib++ module_name, attr = alias+ value = getattr(importlib.import_module(module_name), attr)+ globals()[name] = value+ return valueraise AttributeError(f"module {__name__!r} has no attribute {name!r}")@@ -5182,100 +5336,11 @@ def _clear_bytecode_cache(root: Path) -> int:return removed-# Update pipeline extracted to hermes_cli/update_cmd.py (main.py decomposition,-# mechanical move). Every moved name is re-exported here so the argparse wiring-# and existing test monkeypatches (hermes_cli.main._cmd_update_impl,-# hermes_cli.main._run_pre_update_backup, ...) keep resolving unchanged.-from hermes_cli.update_cmd import ( # noqa: F401- _add_upstream_remote,- _atomic_replace_dir,- _capture_active_lazy_features,- _capture_active_tool_dependencies,- _capture_head_sha,- _cmd_update_check,- _cmd_update_impl,- _cold_start_windows_gateway_after_update,- _count_commits_between,- _detect_self_loaded_native_modules,- _detect_venv_python_processes,- _defer_update_for_self_lock,- _discard_lockfile_churn,- _discard_stashed_changes,- _ensure_acp_launcher,- _ensure_fhs_path_guard,- _ensure_uv_for_termux,- _finish_dashboard_update_cleanup,- _for_each_systemd_gateway_unit,- _format_concurrent_instances_message,- _format_time_ago,- _format_venv_python_holders_message,- _gateway_prompt,- _get_origin_url,- _has_upstream_remote,- _install_psutil_android_compat,- _invalidate_update_cache,- _is_android_python,- _is_fork,- _leftover_pausable_gateway_pids,- _log_only_write,- _mark_skip_upstream_prompt,- _npm_bin_exists,- _npm_lockfile_changed,- _npm_manifest_paths,- _npm_manifests_digest,- _orphaned_desktop_backend_pids,- _pause_windows_gateways_for_update,- _print_curator_first_run_notice,- _print_curator_recent_run_notice,- _print_fts_optimize_available_notice,- _print_stash_cleanup_guidance,- _print_update_completion,- _record_npm_lockfile_hash,- _refresh_active_lazy_features,- _refresh_active_memory_provider_dependencies,- _refresh_bootstrap_cache_scripts,- _refresh_windows_gateway_launchers,- _reload_updated_runtime_modules,- _resolve_pre_update_backup_mode,- _resolve_stash_selector,- _restart_phase_failure_is_incomplete,- _restore_active_tool_dependencies,- _restore_stashed_changes,- _resume_windows_gateways_after_update,- _run_logged_subprocess,- _run_pre_update_backup,- _should_skip_upstream_prompt,- _stash_apply_failed_only_on_existing_untracked,- _stash_local_changes_if_needed,- _stop_process_trees,- _surviving_gateway_pids_after_failed_restart,- _sync_fork_with_upstream,- _sync_with_upstream_if_needed,- _update_node_dependencies,- _update_via_zip,- _upgrade_pip_before_lazy_refresh,- _validate_critical_files_syntax,- _validate_critical_modules_import,- _venv_core_imports_healthy,- _venv_launcher_ancestors,- _wait_for_windows_update_gateway_exit,- _warn_gateway_restart_phase_aborted,- _warn_incomplete_gateway_fleet_restart,- _web_build_toolchain_ready,- _web_toolchain_roots,- _write_lazy_refresh_incomplete_marker,- _write_marker_file,- _write_update_incomplete_marker,- _write_update_planned_stop_marker,- _UPDATE_RUNTIME_RELOAD_MODULES,- _UPDATE_CRITICAL_FILES,- _UPDATE_CRITICAL_MODULES,- OFFICIAL_REPO_URLS,- OFFICIAL_REPO_URL,- SKIP_UPSTREAM_PROMPT_FILE,- _PRE_UPDATE_SNAPSHOT_KEEP,- _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,-)+# Update pipeline lives in hermes_cli/update_cmd.py (main.py decomposition,+# mechanical move). Its names are re-exported lazily through the module-level+# __getattr__ above (see _LAZY_COMMAND_EXPORTS) so argparse wiring and test+# monkeypatches on hermes_cli.main.<name> keep resolving unchanged without+# paying the update_cmd import cost on every CLI invocation.# Stamp file recording the checkout fingerprint the bytecode cache was last# validated against. Lives next to the checkout (NOT in HERMES_HOME) because@@ -7570,22 +7635,17 @@ def cmd_gui(args: argparse.Namespace):sys.exit(launch_result.returncode)-# Dashboard process-hygiene helpers extracted to hermes_cli/dashboard_procs.py-# (main.py decomposition, mechanical move). Re-exported so callers and test-# monkeypatches on hermes_cli.main.<name> keep resolving unchanged.-from hermes_cli.dashboard_procs import ( # noqa: F401- _detect_concurrent_hermes_instances,- _filter_dashboard_respawn_candidates,- _kill_stale_dashboard_processes,- _scan_dashboard_processes,-)+# Dashboard process-hygiene helpers live in hermes_cli/dashboard_procs.py+# (main.py decomposition, mechanical move). Re-exported lazily through the+# module-level __getattr__ above so callers and test monkeypatches on+# hermes_cli.main.<name> keep resolving unchanged.def _find_stale_dashboard_pids(*,exclude_pids: set[int] | None = None,) -> list[int]:"""Return PIDs of stale ``dashboard``/``serve`` processes for update cleanup."""- return [pid for pid, _cmd in _scan_dashboard_processes(exclude_pids=exclude_pids)]+ return [pid for pid, _cmd in _self()._scan_dashboard_processes(exclude_pids=exclude_pids)]def _parse_dashboard_runtime(command: str) -> tuple[str, str, int] | None:@@ -7947,7 +8007,7 @@ def _respawn_dashboard_processes(commands: list[list[str]]) -> list[list[str]]:# Back-compat alias: some tests and any external callers may import the old# warn-only name. The new behaviour (kill stale processes) replaces it.-_warn_stale_dashboard_processes = _kill_stale_dashboard_processes+# Resolved lazily via _LAZY_COMMAND_ALIASES near the module __getattr__.# =========================================================================@@ -9442,7 +9502,7 @@ def cmd_update(args):# --check honors --branch so the "any new commits?" answer matches# what a subsequent `hermes update --branch=<x>` would actually pull.branch = _resolve_update_branch(args)- _cmd_update_check(+ _self()._cmd_update_check(branch=branch,branch_explicit=bool(getattr(args, "branch", None)),)@@ -9473,7 +9533,7 @@ def cmd_update(args):sys.exit(UPDATE_EXIT_CONCURRENT)try:- _cmd_update_impl(args, gateway_mode=gateway_mode)+ _self()._cmd_update_impl(args, gateway_mode=gateway_mode)finally:_update_lock.release()_finalize_update_output(_update_io_state)@@ -10217,7 +10277,7 @@ def _report_dashboard_status() -> int:from gateway.status import _pid_existslive: list[tuple[int, str]] = []- for pid, command in _scan_dashboard_processes():+ for pid, command in _self()._scan_dashboard_processes():runtime = _parse_dashboard_runtime(command)if runtime is None:continue@@ -10531,7 +10591,7 @@ def cmd_dashboard(args):print("No hermes dashboard processes running.")sys.exit(0)# Reuse the same SIGTERM-grace-SIGKILL path used after `hermes update`.- _kill_stale_dashboard_processes(reason="requested via --stop")+ _self()._kill_stale_dashboard_processes(reason="requested via --stop")# _kill_stale_dashboard_processes prints outcomes itself. Exit 0 if# we killed at least one, 1 if they were all unkillable.remaining = _find_stale_dashboard_pids()@@ -12838,10 +12898,13 @@ def main():# cmd_sessions lives in hermes_cli/sessions_cmd.py (main.py decomposition).# sessions_parser is threaded in via functools.partial because the# fallthrough branch calls sessions_parser.print_help() (formerly a- # closure capture of this main()-local).- sessions_parser.set_defaults(- func=_functools.partial(cmd_sessions, sessions_parser=sessions_parser)- )+ # closure capture of this main()-local). The indirection through _self()+ # keeps the sessions_cmd import lazy until the subcommand actually runs+ # and lets monkeypatches on hermes_cli.main.cmd_sessions keep working.+ def _dispatch_sessions(_args, *, sessions_parser=sessions_parser):+ return _self().cmd_sessions(_args, sessions_parser=sessions_parser)++ sessions_parser.set_defaults(func=_dispatch_sessions)# =========================================================================# insights command (parser built in hermes_cli/subcommands/insights.py)diff --git a/tests/hermes_cli/test_lazy_command_exports.py b/tests/hermes_cli/test_lazy_command_exports.pynew file mode 100644index 00000000000..7f2da36c13f--- /dev/null+++ b/tests/hermes_cli/test_lazy_command_exports.py@@ -0,0 +1,66 @@+"""The decomposed command modules stay lazy after `import hermes_cli.main`.++The main.py decomposition re-exports the sessions/update/dashboard command+surface from hermes_cli.main so argparse wiring and monkeypatches keep+resolving. Those re-exports must not import the modules eagerly: every+`hermes` invocation (including `hermes --version`) would pay for update_cmd's+dependency chain (jwt, click, ...) even when no subcommand runs.+"""++import subprocess+import sys+import textwrap++import hermes_cli.main+++def test_importing_main_does_not_import_command_modules():+ code = textwrap.dedent(+ """+ import sys+ import hermes_cli.main # noqa: F401+ loaded = [+ m+ for m in (+ "hermes_cli.update_cmd",+ "hermes_cli.sessions_cmd",+ "hermes_cli.dashboard_procs",+ )+ if m in sys.modules+ ]+ assert not loaded, f"eagerly imported: {loaded}"+ """+ )+ result = subprocess.run(+ [sys.executable, "-c", code],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, result.stderr+++def test_lazy_reexports_resolve_to_real_objects():+ import hermes_cli.dashboard_procs+ import hermes_cli.sessions_cmd+ import hermes_cli.update_cmd++ assert hermes_cli.main.cmd_sessions is hermes_cli.sessions_cmd.cmd_sessions+ assert (+ hermes_cli.main._cmd_update_impl is hermes_cli.update_cmd._cmd_update_impl+ )+ assert (+ hermes_cli.main._scan_dashboard_processes+ is hermes_cli.dashboard_procs._scan_dashboard_processes+ )+ # Back-compat alias resolves to the kill helper.+ assert (+ hermes_cli.main._warn_stale_dashboard_processes+ is hermes_cli.dashboard_procs._kill_stale_dashboard_processes+ )+++def test_lazy_reexports_accept_monkeypatch(monkeypatch):+ sentinel = object()+ monkeypatch.setattr("hermes_cli.main._cmd_update_impl", sentinel)+ assert hermes_cli.main._cmd_update_impl is sentinel