From 60041b787ad77250ca9bafc1f5962cc88373a217 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:52:38 -0700 Subject: [PATCH] refactor(update): join short multi-line statements onto one line (AST-identical, -416 lines) --- hermes_cli/update_cmd.py | 93 ++++----------- hermes_cli/update_cmd_config.py | 37 ++---- hermes_cli/update_cmd_deps.py | 70 +++--------- hermes_cli/update_cmd_fleet.py | 107 ++++------------- hermes_cli/update_cmd_git.py | 39 ++----- hermes_cli/update_cmd_maint.py | 122 +++++--------------- hermes_cli/update_cmd_stash.py | 65 +++-------- hermes_cli/update_cmd_windows.py | 190 +++++++------------------------ hermes_cli/update_cmd_zip.py | 39 ++----- 9 files changed, 173 insertions(+), 589 deletions(-) diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py index aed2d5f2c6..d2a33746ce 100644 --- a/hermes_cli/update_cmd.py +++ b/hermes_cli/update_cmd.py @@ -351,11 +351,7 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0) response_path.unlink(missing_ok=True) - payload = { - "prompt": prompt_text, - "default": default, - "id": str(_uuid.uuid4()), - } + payload = {"prompt": prompt_text, "default": default, "id": str(_uuid.uuid4())} tmp = prompt_path.with_suffix(".tmp") tmp.write_text(_json.dumps(payload), encoding="utf-8") tmp.replace(prompt_path) @@ -510,9 +506,7 @@ def _write_marker_file(path: Path, *, label: str) -> None: logger.debug("Skipping %s marker under pytest (live checkout)", label) return try: - path.write_text( - f"started={_time.time()}\npid={os.getpid()}\n", encoding="utf-8" - ) + path.write_text(f"started={_time.time()}\npid={os.getpid()}\n", encoding="utf-8") except OSError as exc: logger.debug("Could not write %s marker: %s", label, exc) @@ -673,10 +667,7 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False): if branch == "main": # Probe locally for an 'upstream' remote before a network fetch non-forks always fail. - has_upstream_remote = ( - _git_run(git_cmd, ["remote", "get-url", "upstream"]).returncode - == 0 - ) + has_upstream_remote = _git_run(git_cmd, ["remote", "get-url", "upstream"]).returncode == 0 fetch_result = None if has_upstream_remote: print("→ Fetching from upstream...") @@ -759,10 +750,7 @@ def _repair_current_checkout( runtime_repairs = [] update_managed_uv(repair_observer=runtime_repairs.append) ensure_uv(repair_observer=runtime_repairs.append) - runtime_repaired = next( - (result for result in runtime_repairs if result.repaired), - None, - ) + runtime_repaired = next((result for result in runtime_repairs if result.repaired), None) # A current checkout does NOT imply a healthy install (a prior sync may have died # partway, e.g. Windows locked .pyd); probe or "Already up to date!" hides a bricked venv. @@ -792,11 +780,7 @@ def _repair_current_checkout( ).exists() if venv_python_missing and repair_uv: print("→ Recreating virtual environment...") - subprocess.run( - [repair_uv, "venv", "venv"], - cwd=_m().PROJECT_ROOT, - check=False, - ) + subprocess.run([repair_uv, "venv", "venv"], cwd=_m().PROJECT_ROOT, check=False) if repair_uv: # Isolated from third-party UV env vars, like the other dependency syncs. from hermes_cli.managed_uv import managed_python_env @@ -842,9 +826,7 @@ def _repair_current_checkout( desktop_dir, had_desktop_app_before_update=had_desktop_app_before_update, ): - current_checkout_complete = _print_verified_update_completion( - "✓ Update complete!" - ) + current_checkout_complete = _print_verified_update_completion("✓ Update complete!") else: current_checkout_complete = False _print_update_completion( @@ -870,9 +852,7 @@ def _repair_current_checkout( ) if runtime_repaired is not None and not _m()._is_windows(): print() - print( - "⚠ Restart required to finish the managed Python runtime repair." - ) + print("⚠ Restart required to finish the managed Python runtime repair.") print( " Any running Hermes gateways, Desktop backends, or other " "long-lived processes still use the previous runtime." @@ -904,10 +884,7 @@ def _pull_updates( if pull_result.returncode != 0: # Diverged. A custom branch (local commits atop origin/) also can't ff, # and reset --hard would discard that work: merge instead, stop on conflict. - _cur_branch = ( - _git_run(git_cmd, ["branch", "--show-current"]).stdout - or "" - ).strip() + _cur_branch = (_git_run(git_cmd, ["branch", "--show-current"]).stdout or "").strip() if _cur_branch and _cur_branch != branch: print( f" ⚠ Checkout is on custom branch '{_cur_branch}' — " @@ -937,9 +914,7 @@ def _pull_updates( f" Resolve manually: cd {_m().PROJECT_ROOT} && " f"git merge origin/{branch}" ) - print( - " Then re-run the update. Local work is untouched." - ) + print(" Then re-run the update. Local work is untouched.") sys.exit(1) else: # Same branch: a true upstream force-push/rebase; local changes are stashed, so @@ -986,15 +961,11 @@ def _pull_updates( print(f"✗ Failed to reset to origin/{branch}.") if reset_result.stderr.strip(): print(f" {reset_result.stderr.strip()}") - print( - f" Try manually: git fetch origin && git reset --hard origin/{branch}" - ) + print(f" Try manually: git fetch origin && git reset --hard origin/{branch}") sys.exit(1) # Post-pull syntax guard: a bad commit past CI (admin-merge) is rolled back so the CLI stays bootable. - syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax( - _m().PROJECT_ROOT - ) + syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT) if not syntax_ok: print() print("✗ Pulled code has a syntax error in a critical file:") @@ -1026,17 +997,11 @@ def _pull_updates( if auto_stash_ref is not None: # No stash restore if the update failed — tree state is unknown. if not update_succeeded: - print( - f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})" - ) + print(f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})") print(" Restore manually with: git stash apply") elif discard_local_changes: # Non-interactive + updates.non_interactive_local_changes: discard. - _m()._discard_stashed_changes( - git_cmd, - _m().PROJECT_ROOT, - auto_stash_ref, - ) + _m()._discard_stashed_changes(git_cmd, _m().PROJECT_ROOT, auto_stash_ref) elif keep_stash: # --keep-stash (desktop updater): leave edits parked rather than re-apply silently. _m()._park_stashed_changes(auto_stash_ref) @@ -1106,9 +1071,7 @@ def _prepare_checkout_for_update( "⚠ Update finished — code update SKIPPED" f"{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}" ) - _m()._resume_windows_gateways_after_update( - _windows_gateway_resume - ) + _m()._resume_windows_gateways_after_update(_windows_gateway_resume) sys.exit(1) if switch_block_reason.startswith("unmerged:"): _in_place_configured = False @@ -1148,10 +1111,7 @@ def _prepare_checkout_for_update( if not in_place_update and current_branch != branch: if current_branch == "HEAD": - print( - f" ⚠ Currently on detached HEAD — switching to {branch} " - "for update..." - ) + print(f" ⚠ Currently on detached HEAD — switching to {branch} " "for update...") auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT) checkout_result = _git_run(git_cmd, ["checkout", branch]) if checkout_result.returncode != 0: @@ -1323,9 +1283,7 @@ def _begin_update_receipt_and_plan(args): record_plan_in_receipt(_pre_update_plan) if _pre_update_plan.runtimes: _n = len(_pre_update_plan.runtimes) - _profiles = ", ".join( - sorted({r.profile for r in _pre_update_plan.runtimes}) - ) + _profiles = ", ".join(sorted({r.profile for r in _pre_update_plan.runtimes})) print(f"→ Fleet: {_n} running service(s) across profiles: {_profiles}") # Windows: another hermes.exe holding the venv shim means WinError 32 spam and a @@ -1336,15 +1294,9 @@ def _begin_update_receipt_and_plan(args): if scripts_dir is not None: concurrent = _m()._detect_concurrent_hermes_instances(scripts_dir) if concurrent: - non_gateway = _m()._filter_non_gateway_concurrent_instances( - concurrent - ) + non_gateway = _m()._filter_non_gateway_concurrent_instances(concurrent) if non_gateway: - print( - _format_concurrent_instances_message( - non_gateway, scripts_dir - ) - ) + print(_format_concurrent_instances_message(non_gateway, scripts_dir)) sys.exit(2) return _pre_update_plan @@ -1360,9 +1312,7 @@ def _prepare_git_command() -> tuple[bool, list, bool]: use_zip_update = True else: print("✗ Not a git repository. Please reinstall:") - print( - " curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash" - ) + print(" curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash") sys.exit(1) # Windows git can fail "unable to write loose object file: Invalid argument" (fs atomicity). @@ -1590,10 +1540,7 @@ def _cmd_update_impl(args, gateway_mode: bool): if _windows_gateway_resume: import atexit as _atexit - _atexit.register( - _m()._resume_windows_gateways_after_update, - _windows_gateway_resume, - ) + _atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume) # Any venv python still running (typically the Desktop `hermes serve` backend) keeps .pyd # locked and would corrupt the sync; refuse rather than race (the app respawns a killed diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.py index 09e4f1ac5e..df9437ae7c 100644 --- a/hermes_cli/update_cmd_config.py +++ b/hermes_cli/update_cmd_config.py @@ -104,9 +104,7 @@ def _migrate_sibling_profile_configs() -> list[tuple[str, int, int]]: if after_ver > current_ver: migrated.append((entry.name, current_ver, after_ver)) except Exception as exc: - logger.debug( - "Config migration for profile %s failed: %s", entry.name, exc - ) + logger.debug("Config migration for profile %s failed: %s", entry.name, exc) finally: reset_hermes_home_override(token) return migrated @@ -154,22 +152,16 @@ def _check_and_apply_config_migration( return has_new_options = bool(missing_env or missing_config) - version_bump_only = ( - not has_new_options and current_ver < latest_ver - ) + version_bump_only = not has_new_options and current_ver < latest_ver needs_migration = has_new_options or current_ver < latest_ver if version_bump_only: # Only the format version changed (defaults merge transparently); prompting # would look like a no-op on yes — apply silently and say what happened. print() - print( - f" ℹ Updating config format (v{current_ver} → v{latest_ver})…" - ) + print(f" ℹ Updating config format (v{current_ver} → v{latest_ver})…") try: - _mig_results = _run_migrate_config_fresh( - interactive=False, quiet=True - ) + _mig_results = _run_migrate_config_fresh(interactive=False, quiet=True) print(" ✓ Config format updated (no new settings to configure)") # quiet=True also mutes steps that RESET/REMOVE a setting; re-surface them so an # unattended update never silently changes config (config_added holds only mutations here). @@ -184,9 +176,7 @@ def _check_and_apply_config_migration( print() # Show WHAT changed, not just a count, for an informed yes/no. if missing_env: - print( - f" ⚠️ {len(missing_env)} new required setting(s) need configuration" - ) + print(f" ⚠️ {len(missing_env)} new required setting(s) need configuration") _print_items(missing_env, "New settings", "name") if missing_config: print(f" ℹ️ {len(missing_config)} new config option(s) available") @@ -194,9 +184,7 @@ def _check_and_apply_config_migration( print() if assume_yes: - print( - " ℹ --yes: auto-applying config migration (skipping API-key prompts)." - ) + print(" ℹ --yes: auto-applying config migration (skipping API-key prompts).") response = "y" elif gateway_mode: response = ( @@ -230,9 +218,7 @@ def _check_and_apply_config_migration( print() # Gateway/--yes/non-interactive can't prompt for API keys; still run the # non-interactive pass so defaults and version bumps land before the gateway restarts. - interactive_migration = not ( - gateway_mode or assume_yes or response == "auto" - ) + interactive_migration = not (gateway_mode or assume_yes or response == "auto") results = _run_migrate_config_fresh(interactive=interactive_migration, quiet=False) if results["env_added"] or results["config_added"]: @@ -251,10 +237,7 @@ def _check_and_apply_config_migration( with _best_effort('Sibling config migration failed: %s'): _migrated_siblings = _migrate_sibling_profile_configs() for _name, _from_ver, _to_ver in _migrated_siblings: - print( - f" ✓ Profile '{_name}': config format updated " - f"(v{_from_ver} → v{_to_ver})" - ) + print(f" ✓ Profile '{_name}': config format updated " f"(v{_from_ver} → v{_to_ver})") # Safety net: migrations/desktop scheduler have emptied or truncated cron/jobs.json; # restore from the pre-update snapshot if jobs went missing. @@ -278,9 +261,7 @@ def _check_and_apply_config_migration( try: from hermes_cli.backup import restore_config_model_settings_if_rewritten - cfg_restore = restore_config_model_settings_if_rewritten( - pre_update_snapshot_id - ) + cfg_restore = restore_config_model_settings_if_rewritten(pre_update_snapshot_id) if cfg_restore: print() print( diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.py index 989e0b5448..f6d90a9acc 100644 --- a/hermes_cli/update_cmd_deps.py +++ b/hermes_cli/update_cmd_deps.py @@ -21,13 +21,7 @@ logger = logging.getLogger("hermes_cli.update_cmd") # Files defining the editable install; a pull touching none of them cannot invalidate it. -_INSTALL_DEFINING_FILES = ( - "pyproject.toml", - "setup.py", - "setup.cfg", - "MANIFEST.in", - "uv.lock", -) +_INSTALL_DEFINING_FILES = "pyproject.toml", "setup.py", "setup.cfg", "MANIFEST.in", "uv.lock" def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool: @@ -59,12 +53,7 @@ def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool # Modules imported on every startup. Unlike _UPDATE_CRITICAL_FILES (only parsed) these are # *imported*, catching cross-module breakage (a name pulled from a sibling no longer exists). -_UPDATE_CRITICAL_MODULES = ( - "hermes_cli.main", - "run_agent", - "model_tools", - "toolsets", -) +_UPDATE_CRITICAL_MODULES = "hermes_cli.main", "run_agent", "model_tools", "toolsets" def _critical_module_import_failures( @@ -116,9 +105,7 @@ def _critical_module_import_failures( try: interpreter = sys.executable with suppress(Exception): - venv_python = venv_python_path( - Path(root) / "venv", windows=_m()._is_windows() - ) + venv_python = venv_python_path(Path(root) / "venv", windows=_m()._is_windows()) if venv_python.exists(): interpreter = str(venv_python) result = subprocess.run( @@ -160,10 +147,7 @@ def _critical_module_import_failures( for item in failures ): raise ValueError("invalid import-health payload") - return { - str(module): (str(kind), str(detail)) - for module, kind, detail in failures - } + return {str(module): (str(kind), str(detail)) for module, kind, detail in failures} except (TypeError, ValueError): return { "critical-module probe": ( @@ -177,9 +161,7 @@ def _validate_critical_modules_import( root, *, report_runtime_errors: bool = False ) -> tuple[bool, str | None, str | None]: """Return the first critical-module import failure, if any.""" - failures = _critical_module_import_failures( - root, report_runtime_errors=report_runtime_errors - ) + failures = _critical_module_import_failures(root, report_runtime_errors=report_runtime_errors) if failures: module = next(iter(failures)) return False, module, failures[module][1] @@ -423,20 +405,14 @@ def _refresh_active_lazy_features( # wiped. Unavailable probes are indeterminate, not healthy — keep the lazy marker. status = _m()._repair_venv_via_import_probes(install_cmd_prefix, env=env) if status == "repaired": - print( - " Lazy backend(s) keep their previous version until refresh succeeds." - ) + print(" Lazy backend(s) keep their previous version until refresh succeeds.") return True if status == "healthy": - print( - " Lazy backend(s) keep their previous version; probed packages look intact." - ) + print(" Lazy backend(s) keep their previous version; probed packages look intact.") print(" Rerun `hermes update` once the upstream issue is resolved.") return True if status == "indeterminate": - print( - " ⚠ Leaving `.lazy-refresh-incomplete` until import probes can confirm health." - ) + print(" ⚠ Leaving `.lazy-refresh-incomplete` until import probes can confirm health.") return False @@ -553,9 +529,7 @@ def _npm_manifest_paths() -> tuple[Path, ...]: root_pkg = _m().PROJECT_ROOT / "package.json" paths = [_m().PROJECT_ROOT / "package-lock.json", root_pkg] with suppress(OSError, json.JSONDecodeError, TypeError): - workspaces = json.loads(root_pkg.read_text(encoding="utf-8")).get( - "workspaces", [] - ) + workspaces = json.loads(root_pkg.read_text(encoding="utf-8")).get("workspaces", []) if isinstance(workspaces, dict): # legacy {"packages": [...]} form workspaces = workspaces.get("packages", []) for pattern in workspaces: @@ -645,9 +619,7 @@ def _repair_node_deps_on_current_checkout( if node_failures: print(f" ⚠ Node.js refresh failed for: {', '.join(node_failures)}") print(" Fix npm and re-run `hermes update`.") - print_completion( - "⚠ Checkout is current, but Node.js dependencies could not be repaired." - ) + print_completion("⚠ Checkout is current, but Node.js dependencies could not be repaired.") return False # Pair with the web build like every other call site; it staleness-checks internally. _m()._build_web_ui(_m().PROJECT_ROOT / "web") @@ -1068,9 +1040,7 @@ def _venv_foreign_owned_paths(venv_root, limit: int = 5) -> list: _scan_dir(venv_root / "bin") # First lib/python*/site-packages (POSIX venv layout). - site_packages = next( - iter(sorted(venv_root.glob("lib/python*/site-packages"))), None - ) + site_packages = next(iter(sorted(venv_root.glob("lib/python*/site-packages"))), None) if site_packages is not None: _scan_dir(site_packages, recurse_dist_info=True) @@ -1125,9 +1095,7 @@ def _sync_python_dependencies_after_pull( # Drop the core-install breadcrumb BEFORE touching the venv so a killed install is finished # by the next launch (``_recover_from_interrupted_install``). Lazy refresh uses its own marker. _write_update_incomplete_marker() - deps_current = _editable_install_is_current( - git_cmd, _m().PROJECT_ROOT, pre_pull_sha - ) + deps_current = _editable_install_is_current(git_cmd, _m().PROJECT_ROOT, pre_pull_sha) if deps_current: print("→ Python dependencies unchanged — skipping reinstall") else: @@ -1181,9 +1149,7 @@ def _sync_python_dependencies_after_pull( if deps_current: # Verification normally runs inside the skipped install; run it here so a wrong skip # self-heals (both verifiers reinstall what they find missing). - _m()._verify_core_dependencies_installed( - install_prefix, env=lazy_env, group=install_group - ) + _m()._verify_core_dependencies_installed(install_prefix, env=lazy_env, group=install_group) _m()._verify_console_scripts_installed(install_prefix, env=lazy_env) # Clear the core breadcrumb before lazy refresh, which uses its own marker so a lazy @@ -1214,20 +1180,14 @@ def _sync_python_dependencies_after_pull( "to finish import-based venv repair." ) - _m()._restore_active_tool_dependencies( - active_tool_dependencies, - install_prefix, - env=lazy_env, - ) + _m()._restore_active_tool_dependencies(active_tool_dependencies, install_prefix, env=lazy_env) # Heal memory-provider bridge packages last — the steps above may have stripped them. _m()._refresh_active_memory_provider_dependencies() # Remaining import failures are real breakage. Warn only — never roll back: `cannot import # name X` is also the stale-bytecode signature, which self-heals next launch. - import_ok, failing_module, import_error = _validate_critical_modules_import( - _m().PROJECT_ROOT - ) + import_ok, failing_module, import_error = _validate_critical_modules_import(_m().PROJECT_ROOT) if not import_ok: print() print(f" ⚠ {failing_module} still fails to import after updating:") diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py index 544ba28abf..dd48f35343 100644 --- a/hermes_cli/update_cmd_fleet.py +++ b/hermes_cli/update_cmd_fleet.py @@ -57,9 +57,7 @@ def _write_fleet_restart_pending_marker(*, expected_sha: str = "") -> None: def _clear_fleet_restart_pending_marker() -> None: """Remove the pull→restart obligation breadcrumb. Never raises.""" from hermes_cli.update_cmd import _m - _m()._clear_marker_file( - _fleet_restart_pending_marker_path(), label="fleet-restart-pending" - ) + _m()._clear_marker_file(_fleet_restart_pending_marker_path(), label="fleet-restart-pending") def _current_checkout_sha() -> str | None: @@ -152,15 +150,9 @@ def _warn_pending_fleet_restart(*, startup: bool = False) -> None: "restart running gateways.", file=stream, ) - print( - " Gateways may still be serving pre-update modules (mixed sys.modules).", - file=stream, - ) + print(" Gateways may still be serving pre-update modules (mixed sys.modules).", file=stream) if startup: - print( - " Run `hermes update` or `hermes gateway restart`.", - file=stream, - ) + print(" Run `hermes update` or `hermes gateway restart`.", file=stream) def _warn_pending_fleet_restart_on_startup() -> None: @@ -390,8 +382,7 @@ def _warn_incomplete_gateway_fleet_restart(failed_units: list) -> None: print(" running pre-update code (mixed sys.modules). Recover with:") print(" hermes gateway status") print(" launchctl list | grep