The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(update): join short multi-line statements onto one line (AST-identical, -416 lines)
Teknium60041b787ad7
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex aed2d5f2c66..d2a33746ce1 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)returntry:- 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 == 0fetch_result = Noneif 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/<branch>) 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 = Trueelse: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 killeddiff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.pyindex 09e4f1ac5ea..df9437ae7cd 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(returnhas_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_verneeds_migration = has_new_options or current_ver < latest_verif 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.pyindex 989e0b5448f..f6d90a9acc1 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.executablewith 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 Trueif 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 Trueif 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": [...]} formworkspaces = 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.pyindex 544ba28abf3..dd48f35343d 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 <label>")- print(" launchctl bootstrap gui/$(id -u) "- "~/Library/LaunchAgents/<label>.plist")+ print(" launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/<label>.plist")returnprint(" Skipped units may still be running pre-update code (mixed")print(" sys.modules). Restart them manually, then verify:")@@ -487,9 +478,7 @@ def _restart_macos_launchd_gateways()# --- Current profile ---- _restarted, _failed = _restart_launchd_gateway_after_update(- supervision_verify=True- )+ _restarted, _failed = _restart_launchd_gateway_after_update(supervision_verify=True)restarted_services.extend(_restarted)failed_or_stale_units.extend(_failed)current_label = get_launchd_label()@@ -508,9 +497,7 @@ def _restart_macos_launchd_gateways(graceful_ok = Falseif old_pid is not None and old_pid > 0:print(f" → {label}: draining (up to {int(drain_budget)}s)...")- graceful_ok = _graceful_restart_via_sigusr1(- old_pid, drain_timeout=drain_budget- )+ graceful_ok = _graceful_restart_via_sigusr1(old_pid, drain_timeout=drain_budget)if graceful_ok and _wait_for_launchd_service_pid(label, old_pid=old_pid, timeout=10.0, domain=domain):@@ -571,12 +558,7 @@ def _gateway_service_matches_profile(profile: str, service: object) -> bool:"""name = str(service).removesuffix(".service")if profile == "default":- return name in {- "hermes-gateway",- "ai.hermes.gateway",- "gateway",- "gateway-default",- }+ return name in {"hermes-gateway", "ai.hermes.gateway", "gateway", "gateway-default"}return name in {f"hermes-gateway-{profile}",f"ai.hermes.gateway-{profile}",@@ -740,11 +722,7 @@ def _resolve_manage_cmd(cache: dict, scope_: str, scope_cmd_: list, svc_name_: ssudo_cmd = ["sudo", "-n"] + scope_cmd_ + ["--no-ask-password"]sudo_ok = Falsetry:- _probe = subprocess.run(- ["sudo", "-n", "true"],- capture_output=True,- timeout=5,- )+ _probe = subprocess.run(["sudo", "-n", "true"], capture_output=True, timeout=5)sudo_ok = _probe.returncode == 0if not sudo_ok:# Blanket sudo refused — a targeted NOPASSWD sudoers entry may still work.@@ -807,9 +785,7 @@ def _restart_systemd_gateway_units(# None ⇒ no non-interactive privilege path; avoid manage-units verbs# entirely or polkit prompts inside the captured subprocess.- _manage_cmd = _resolve_manage_cmd(_manage_cmd_cache,- scope, scope_cmd, svc_name- )+ _manage_cmd = _resolve_manage_cmd(_manage_cmd_cache, scope, scope_cmd, svc_name)# Graceful SIGUSR1 first so in-flight runs drain: handler →# request_restart(via_service=True) → drain → exit, Restart=always@@ -852,15 +828,8 @@ def _restart_systemd_gateway_units(return# Passive poll: auto-restart fires after RestartSec regardless of# privileges — primary when _manage_cmd is None, fallback otherwise.- _restart_sec = _service_restart_sec(- scope_cmd,- svc_name,- default=0.0,- )- _post_drain_timeout = max(- 10.0,- _restart_sec + 10.0,- )+ _restart_sec = _service_restart_sec(scope_cmd, svc_name, default=0.0)+ _post_drain_timeout = max(10.0, _restart_sec + 10.0)if _manage_cmd is None and _restart_sec > 5.0:print(f" → {svc_name}: waiting for systemd "@@ -876,9 +845,7 @@ def _restart_systemd_gateway_units(return# Exited but not respawned (older unit without Restart=on-failure /# RestartForceExitStatus=75); fall through to forced restart.- print(- f" ⚠ {svc_name} drained but didn't relaunch — forcing restart"- )+ print(f" ⚠ {svc_name} drained but didn't relaunch — forcing restart")# Forcing needs manage-units privileges; without a non-interactive path# polkit would prompt inside the captured subprocess — skip, instruct.@@ -908,9 +875,7 @@ def _restart_systemd_gateway_units(else:# Retry once — transient startup failures (stale module cache,# import race) often clear; reset-failed so the retry isn't blocked.- print(- f" ⚠ {svc_name} died after restart, retrying..."- )+ print(f" ⚠ {svc_name} died after restart, retrying...")_systemctl_reset_and_restart(_manage_cmd, svc_name)if _wait_for_service_active(scope_cmd,@@ -932,9 +897,7 @@ def _restart_systemd_gateway_units()else:failed_or_stale_units.append(svc_name)- print(- f" ⚠ Failed to restart {svc_name}: {restart.stderr.strip()}"- )+ print(f" ⚠ Failed to restart {svc_name}: {restart.stderr.strip()}")def _on_unit_timeout(svc_name: str, exc: subprocess.TimeoutExpired) -> None:# Isolate to this unit; a scope-wide handler used to abort every@@ -998,9 +961,7 @@ def _restart_manual_gateways(# Exclude just-restarted service PIDs so we don't kill what systemd/launchd spawned.service_pids = _get_service_pids(all_profiles=True)- manual_pids = find_gateway_pids(- exclude_pids=service_pids, all_profiles=True- )+ manual_pids = find_gateway_pids(exclude_pids=service_pids, all_profiles=True)profile_processes = {proc.pid: procfor proc in find_profile_gateway_processes(exclude_pids=service_pids)@@ -1010,9 +971,7 @@ def _restart_manual_gateways(# the unmapped sweep below stops them and lists them under "Restart manually".unrestartable_pids = set()for pid, proc in profile_processes.items():- restart_mode = _prepare_profile_gateway_update_restart(- proc.profile, pid- )+ restart_mode = _prepare_profile_gateway_update_restart(proc.profile, pid)if restart_mode is None:# A bare ``continue`` here left it serving stale modules with no signal.print(@@ -1025,9 +984,7 @@ def _restart_manual_gateways(# SIGUSR1 drain first, SIGTERM fallback if unsupported/over budget — the# watcher relaunches either way. The helper announces its choice first# because a silent full-budget wait reads as a hung update.- drained = _drain_or_signal_gateway_for_update(- pid, _drain_budget, proc.profile- )+ drained = _drain_or_signal_gateway_for_update(pid, _drain_budget, proc.profile)if not drained:with suppress(ProcessLookupError, PermissionError):os.kill(pid, _signal.SIGTERM)@@ -1057,10 +1014,7 @@ def _restart_manual_gateways(print(f" ✓ Restarting manual gateway profile(s): {names}")if externally_supervised_profiles:names = ", ".join(externally_supervised_profiles)- print(- " ✓ Handed gateway profile(s) back to their external "- f"supervisor: {names}"- )+ print(f" ✓ Handed gateway profile(s) back to their external supervisor: {names}")unmapped_count = (len(killed_pids)- len(relaunched_profiles)@@ -1070,9 +1024,7 @@ def _restart_manual_gateways(print(f" → Stopped {unmapped_count} manual gateway process(es)")print(" Restart manually: hermes gateway run")if unmapped_count > 1:- print(- " (or: hermes -p <profile> gateway run for each profile)"- )+ print(" (or: hermes -p <profile> gateway run for each profile)")def _force_kill_stuck_gateways(killed_pids, *, find_gateway_pids, _get_service_pids):@@ -1082,17 +1034,12 @@ def _force_kill_stuck_gateways(killed_pids, *, find_gateway_pids, _get_service_pwith _best_effort('Post-restart survivor sweep failed: %s'):_time.sleep(3.0)_service_pids_after = _get_service_pids(all_profiles=True)- _surviving = find_gateway_pids(- exclude_pids=_service_pids_after,- all_profiles=True,- )+ _surviving = find_gateway_pids(exclude_pids=_service_pids_after, all_profiles=True)# Only PIDs we already tried to kill; newer ones are left alone._stuck = [pid for pid in _surviving if pid in killed_pids]if _stuck:print()- print(- f" ⚠ {len(_stuck)} gateway process(es) ignored SIGTERM — force-killing"- )+ print(f" ⚠ {len(_stuck)} gateway process(es) ignored SIGTERM — force-killing")from gateway.status import (get_process_start_time as _get_process_start_time,terminate_pid as _terminate_pid,@@ -1168,9 +1115,7 @@ def _recover_after_restart_phase_abort(# serve/dashboard still the SAME pre-update process is live on old code# (unreachable by `gateway restart`): recovery may not claim success while one# remains, and must never kill one (manual/Desktop serves have no relaunch authority).- _stale_runtime_rows = _surviving_pre_update_serve_runtimes(- _pre_update_plan- )+ _stale_runtime_rows = _surviving_pre_update_serve_runtimes(_pre_update_plan)_recovery_result["stale_runtimes"] = _stale_runtime_rows# Only systemd-VERIFIED outcomes claim coverage; a relaunch that merely exited 0# ("relaunch_attempted") was never observed and must not clear incomplete.@@ -1187,12 +1132,8 @@ def _recover_after_restart_phase_abort(if getattr(runtime, "kind", None) == "gateway"and isinstance(getattr(runtime, "profile", None), str)]- _planned_gateway_profiles = {- runtime.profile for runtime in _planned_gateway_runtimes- }- _covered_gateway_profiles = (- _already_restarted_profiles | _recovery_verified- )+ _planned_gateway_profiles = {runtime.profile for runtime in _planned_gateway_runtimes}+ _covered_gateway_profiles = _already_restarted_profiles | _recovery_verified_recovery_complete = _abort_recovery_is_complete(planned_gateway_profiles=_planned_gateway_profiles,covered_gateway_profiles=_covered_gateway_profiles,diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex 9ef49a1eced..b4bee112ad2 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -139,9 +139,7 @@ def _assess_parked_branch_switch(cherry = _git_run(git_cmd, ["cherry", f"origin/{target_branch}"], cwd)if cherry.returncode != 0:return False, "unverifiable"- unmerged = [- line for line in cherry.stdout.splitlines() if line.startswith("+")- ]+ unmerged = [line for line in cherry.stdout.splitlines() if line.startswith("+")]if unmerged:# Safe (checkout keeps commits); reason tells caller to print the loud notice.return True, f"unmerged:{len(unmerged)}"@@ -170,10 +168,7 @@ def _print_parked_branch_skip_warning(elif reason == "disabled":why = "updates.auto_switch_parked_branch is set to false in config.yaml"else:- why = (- f"the branch state could not be verified against "- f"origin/{target_branch}"- )+ why = f"the branch state could not be verified against origin/{target_branch}"bar = "=" * 68print()@@ -189,10 +184,7 @@ def _print_parked_branch_skip_warning(print(" To resolve, inspect the branch and switch back yourself:")print(f" git -C {cwd} status")print(f" git -C {cwd} checkout {target_branch} && hermes update")- print(- " (commit or stash your work on the branch first if you want to "- "keep it)"- )+ print(" (commit or stash your work on the branch first if you want to keep it)")print(bar)@@ -378,9 +370,7 @@ def _sync_with_upstream_if_needed(if response in {"", "y", "yes"}:print("→ Adding upstream remote...")if _add_upstream_remote(git_cmd, cwd):- print(- " ✓ Added upstream: https://github.com/NousResearch/hermes-agent.git"- )+ print(" ✓ Added upstream: https://github.com/NousResearch/hermes-agent.git")has_upstream = Trueelse:print(" ✗ Failed to add upstream remote. Skipping upstream sync.")@@ -408,9 +398,7 @@ def _sync_with_upstream_if_needed(return Falseorigin_ahead = _count_commits_between(git_cmd, cwd, "upstream/main", "origin/main")- upstream_ahead = _count_commits_between(- git_cmd, cwd, "origin/main", "upstream/main"- )+ upstream_ahead = _count_commits_between(git_cmd, cwd, "origin/main", "upstream/main")if origin_ahead < 0 or upstream_ahead < 0:print(" ✗ Could not compare branches. Skipping upstream sync.")@@ -440,9 +428,7 @@ def _sync_with_upstream_if_needed(**_no_prompt_git_kwargs(),)except subprocess.CalledProcessError:- print(- " ✗ Failed to pull from upstream. You may need to resolve conflicts manually."- )+ print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")return Falseprint(" ✓ Updated from upstream")@@ -451,9 +437,7 @@ def _sync_with_upstream_if_needed(if _sync_fork_with_upstream(git_cmd, cwd):print(" ✓ Fork synced with upstream")else:- print(- " ℹ Got updates from upstream but couldn't push to fork (no write access?)"- )+ print(" ℹ Got updates from upstream but couldn't push to fork (no write access?)")print(" Your local repo is updated, but your fork on GitHub may be behind.")return True@@ -532,9 +516,7 @@ def _portable_git_candidates() -> list:candidates = []with suppress(Exception):for root in (get_default_hermes_root(), Path(get_hermes_home())):- candidates.append(- root / "git" / "mingw64" / "libexec" / "git-core" / "git.exe"- )+ candidates.append(root / "git" / "mingw64" / "libexec" / "git-core" / "git.exe")return candidates@@ -581,10 +563,7 @@ def _ensure_non_trampoline_git(git_cmd: list) -> list:"git binary — the update will fall back to the ZIP path.")return git_cmd- print(- f"⚠ Detected a broken git trampoline; switching to real git at "- f"{real_git}"- )+ print(f"⚠ Detected a broken git trampoline; switching to real git at {real_git}")return [str(real_git)] + list(git_cmd[1:])diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex f333f2f94e3..0e3dc7fb629 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -22,22 +22,12 @@ 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",-)+_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.-_STALE_PURGE_PREFIXES = (- "hermes_cli",- "gateway",- "tools",- "tui_gateway",- "agent",-)+_STALE_PURGE_PREFIXES = "hermes_cli", "gateway", "tools", "tui_gateway", "agent"#: Modules EXECUTING the update survive the purge: evicting them buys nothing (running frames@@ -82,9 +72,7 @@ def _purge_stale_hermes_modules() -> None:if _m().sys.modules.pop(name, None) is not None:purged.append(name)if purged:- logger.debug(- "Purged %d stale Hermes module(s) after checkout update", len(purged)- )+ logger.debug("Purged %d stale Hermes module(s) after checkout update", len(purged))def _reload_updated_runtime_modules() -> None:@@ -135,9 +123,7 @@ def _print_curator_first_run_notice() -> None:)print(" Preview now: hermes curator run --dry-run")print(" Pause it: hermes curator pause")- print(- " Docs: https://hermes-agent.nousresearch.com/docs/user-guide/features/curator"- )+ print(" Docs: https://hermes-agent.nousresearch.com/docs/user-guide/features/curator")def _print_fts_optimize_available_notice() -> None:@@ -279,10 +265,7 @@ def _print_curator_recent_run_notice() -> None:print(f"ℹ Skill curator — last run {when}")for line in summary.splitlines():print(f" {line}")- print(- " (This message shows once per curator run. "- "View anytime: hermes curator status)"- )+ print(" (This message shows once per curator run. View anytime: hermes curator status)")with suppress(Exception):state["last_run_summary_shown_at"] = last_run_at@@ -327,11 +310,7 @@ def _reload_process_scan_modules() -> None:importlib.reload(mod)except Exception as exc:# warning, not debug: a failed reload surfaces as ImportError seconds later.- logger.warning(- "Could not reload %s for post-update cleanup: %s",- mod_name,- exc,- )+ logger.warning("Could not reload %s for post-update cleanup: %s", mod_name, exc)def _finish_dashboard_update_cleanup(@@ -475,13 +454,9 @@ def _print_update_summary(if node_failures or not desktop_build_ok or not sqlite_runtime_ok:parts = []if node_failures:- parts.append(- f"Node.js dependencies for {', '.join(node_failures)} did not refresh"- )+ parts.append(f"Node.js dependencies for {', '.join(node_failures)} did not refresh")if not desktop_build_ok:- parts.append(- "the desktop app was not rebuilt and is still on the previous build"- )+ parts.append("the desktop app was not rebuilt and is still on the previous build")if not sqlite_runtime_ok and sqlite_info is not None:parts.append(f"SQLite {sqlite_info.sqlite_version_string} still has the "@@ -538,9 +513,7 @@ def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:"handles (or restart Hermes) and retry.")return False- restored = verify_sqlite_integrity(- state_path, check_header=True, run_pragma=True- )+ restored = verify_sqlite_integrity(state_path, check_header=True, run_pragma=True)return bool(restored.get("valid"))@@ -555,11 +528,7 @@ def _verify_and_restore_one_state_db(home: Path, *, label: str) -> None:returnok = verify_sqlite_integrity(state_path, check_header=True, run_pragma=True)if ok.get("valid"):- logger.debug(- "Post-update state.db integrity OK (%s): %s",- label,- ok.get("message"),- )+ logger.debug("Post-update state.db integrity OK (%s): %s", label, ok.get("message"))returnprint()print(@@ -576,29 +545,20 @@ def _verify_and_restore_one_state_db(home: Path, *, label: str) -> None:snap_state = snap_dir / "state.db"if not snap_state.exists():continue- snap_ok = verify_sqlite_integrity(- snap_state, check_header=True, run_pragma=True- )+ snap_ok = verify_sqlite_integrity(snap_state, check_header=True, run_pragma=True)if not snap_ok.get("valid"):continuetry:if _restore_state_db_from_snapshot(state_path, snap_state):- print(- f" ✓ Auto-restored from snapshot {snap_dir.name} ({label})"- )+ print(f" ✓ Auto-restored from snapshot {snap_dir.name} ({label})")else:- print(- " ✗ Auto-restore FAILED — restored copy also failed "- "integrity"- )+ print(" ✗ Auto-restore FAILED — restored copy also failed integrity")except OSError as exc:print(f" ✗ Auto-restore file copy failed: {exc}")returnprint(" ⚠ No valid pre-update snapshot found for this home")except Exception as exc:- logger.debug(- "Post-update state.db guard (%s) failed: %s", label, exc- )+ logger.debug("Post-update state.db guard (%s) failed: %s", label, exc)def _verify_and_restore_state_dbs_post_update() -> None:@@ -622,15 +582,10 @@ def _print_bundled_skills_sync_report() -> None:if result["copied"]:print(f" + {len(result['copied'])} new: {', '.join(result['copied'])}")if result.get("updated"):- print(- f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}"- )+ print(f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}")if result.get("user_modified"):print(f" ~ {len(result['user_modified'])} user-modified (kept)")- print(- " → see them: hermes skills list-modified "- "(diff/reset to resume updates)"- )+ print(" → see them: hermes skills list-modified (diff/reset to resume updates)")if result.get("cleaned"):print(f" − {len(result['cleaned'])} removed from manifest")if result.get("relocated"):@@ -684,9 +639,7 @@ def _ensure_fhs_path_guard() -> None:return # already on PATH, nothing to dopath_line = 'export PATH="/usr/local/bin:$PATH"'- path_comment = (- "# Hermes Agent — ensure /usr/local/bin is on PATH " "(RHEL non-login shells)"- )+ path_comment = "# Hermes Agent — ensure /usr/local/bin is on PATH (RHEL non-login shells)"wrote_any = Falsefor candidate in (".bashrc", ".bash_profile"):cfg = Path(home) / candidate@@ -775,9 +728,7 @@ def _resolve_pre_update_backup_mode(args) -> str:cfg = load_config()except Exception as exc:- logger.debug(- "Could not load config for pre-update backup: %s", exc- )+ logger.debug("Could not load config for pre-update backup: %s", exc)cfg = {}updates_cfg = cfg.get("updates", {}) if isinstance(cfg, dict) else {}@@ -794,9 +745,7 @@ def _resolve_pre_update_backup_mode(args) -> str:return "full"if mode == "quick":return "quick"- logger.warning(- "Unknown updates.pre_update_backup value %r — using 'quick'", raw- )+ logger.warning("Unknown updates.pre_update_backup value %r — using 'quick'", raw)return "quick"@@ -848,9 +797,7 @@ def _run_pre_update_backup(args) -> Optional[str]:)if not _integrity.get("valid"):_msg = _integrity.get("message", "unknown error")- print(- f" ⚠ state.db integrity check FAILED after snapshot: {_msg}"- )+ print(f" ⚠ state.db integrity check FAILED after snapshot: {_msg}")_snap_root = _quick_snapshot_root(_get_home())_snap_state = _snap_root / snapshot_id / "state.db"if _snap_state.exists():@@ -858,21 +805,15 @@ def _run_pre_update_backup(args) -> Optional[str]:_snap_state, check_header=True, run_pragma=True)if _snap_ok.get("valid"):- print(- " ✓ Snapshot copy is valid — continuing update."- )- print(- " If state.db is lost after update it will be auto-restored."- )+ print(" ✓ Snapshot copy is valid — continuing update.")+ print(" If state.db is lost after update it will be auto-restored.")else:print(" ✗ Snapshot copy ALSO failed integrity — ""the source was already corrupted before the backup.")else:- print(- " ⚠ Snapshot does not contain state.db (was skipped or too large)."- )+ print(" ⚠ Snapshot does not contain state.db (was skipped or too large).")print()if snapshot_id:print(f"◆ Pre-update snapshot: {snapshot_id}")@@ -887,10 +828,7 @@ def _run_pre_update_backup(args) -> Optional[str]:max_file_size=_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,)if _sibling_snaps:- print(- f"◆ Sibling profile snapshot(s): "- + ", ".join(sorted(_sibling_snaps))- )+ print(f"◆ Sibling profile snapshot(s): " + ", ".join(sorted(_sibling_snaps)))_record_update_step("sibling_profile_snapshots",True,@@ -911,9 +849,7 @@ def _run_pre_update_backup(args) -> Optional[str]:try:from hermes_cli.backup import create_pre_update_backupexcept Exception as exc:- print(- f"⚠ Pre-update backup: could not load backup module ({exc}); continuing update."- )+ print(f"⚠ Pre-update backup: could not load backup module ({exc}); continuing update.")print()return snapshot_id@@ -975,9 +911,7 @@ def _sweep_bytecode_after_update(branch: str) -> None:from hermes_cli.update_cmd import _mremoved = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)if removed:- print(- f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}"- )+ print(f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}")_m()._record_bytecode_fingerprint()_m()._refresh_bootstrap_cache_scripts(branch)@@ -1136,9 +1070,7 @@ def _run_post_update_maintenance(_update_cfg = (load_config() or {}).get("updates", {})if isinstance(_update_cfg, dict):- refresh_cua_driver = bool(- _update_cfg.get("refresh_cua_driver", True)- )+ refresh_cua_driver = bool(_update_cfg.get("refresh_cua_driver", True))if (refresh_cua_driverdiff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.pyindex 867992c8d86..5ed3dcbf0d2 100644--- a/hermes_cli/update_cmd_stash.py+++ b/hermes_cli/update_cmd_stash.py@@ -29,9 +29,7 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[stfrom datetime import datetime, timezone- stash_name = datetime.now(timezone.utc).strftime(- f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S"- )+ stash_name = datetime.now(timezone.utc).strftime(f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S")print("→ Local changes detected — stashing before update...")prev_stash = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd).stdout.strip()push = _git_run(git_cmd, ["stash", "push", "--include-untracked", "-m", stash_name], cwd)@@ -39,9 +37,7 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[stprint(push.stdout.strip())stash_probe = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd)stash_ref = stash_probe.stdout.strip()- stash_created = (- stash_probe.returncode == 0 and bool(stash_ref) and stash_ref != prev_stash- )+ stash_created = stash_probe.returncode == 0 and bool(stash_ref) and stash_ref != prev_stashif push.returncode != 0:if stash_created:@@ -59,11 +55,7 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st)# A partially-failed push also skips cleanup of TRACKED modifications;# they'd break the following pull. Safe to reset: all is in the stash.- subprocess.run(- git_cmd + ["reset", "--hard", "HEAD"],- cwd=cwd,- capture_output=True,- )+ subprocess.run(git_cmd + ["reset", "--hard", "HEAD"], cwd=cwd, capture_output=True)else:# No entry created: changes NOT saved — bail before touching HEAD.print("✗ Could not stash local changes — update aborted.")@@ -115,9 +107,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:stash_list = _git_run(git_cmd, ["stash", "list", "--format=%gd %s"], cwd)if stash_list.returncode != 0:return 0- cutoff = datetime.now(timezone.utc) - timedelta(- days=_AUTOSTASH_WARN_AGE_DAYS- )+ cutoff = datetime.now(timezone.utc) - timedelta(days=_AUTOSTASH_WARN_AGE_DAYS)marker = _AUTOSTASH_NAME_PREFIXstale: list[tuple[str, str]] = []for line in stash_list.stdout.splitlines():@@ -127,9 +117,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:continuestamp = subject[pos + len(marker):][:15] # "YYYYMMDD-HHMMSS"try:- stash_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(- tzinfo=timezone.utc- )+ stash_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(tzinfo=timezone.utc)except ValueError:continue # age unknown — leave it alone rather than guessif stash_time < cutoff:@@ -156,9 +144,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:def _print_stash_cleanup_guidance(stash_ref: str, stash_selector: Optional[str] = None) -> None:- print(- " Check `git status` first so you don't accidentally reapply the same change twice."- )+ print(" Check `git status` first so you don't accidentally reapply the same change twice.")print(" Find the saved entry with: git stash list --format='%gd %H %s'")if stash_selector:print(f" Remove it with: git stash drop {stash_selector}")@@ -216,10 +202,7 @@ def _git_untracked_paths(git_cmd: list[str], cwd: Path) -> set[str] | None:except (OSError, subprocess.SubprocessError):result = Noneif result is None or result.returncode != 0:- print(- " ⚠ Could not enumerate untracked files while validating the "- "restored stash."- )+ print(" ⚠ Could not enumerate untracked files while validating the restored stash.")return Nonereturn {path for path in result.stdout.split("\0") if path}@@ -276,9 +259,7 @@ def _reject_unsafe_stash_restore(else set())try:- reset = subprocess.run(- git_cmd + ["reset", "--hard", "HEAD"], cwd=cwd, capture_output=True- )+ reset = subprocess.run(git_cmd + ["reset", "--hard", "HEAD"], cwd=cwd, capture_output=True)except (OSError, subprocess.SubprocessError):reset = None@@ -340,9 +321,7 @@ def _restore_stashed_changes(prompt_suffix = "[y/N]" if remote_prompt else "[Y/n]"print()print("⚠ Local changes were stashed before updating.")- print(- " Restoring them may reapply local customizations onto the updated codebase."- )+ print(" Restoring them may reapply local customizations onto the updated codebase.")print(" Review the result afterward if Hermes behaves unexpectedly.")print(f"Restore local changes now? {prompt_suffix}")if input_fn is not None:@@ -364,9 +343,7 @@ def _restore_stashed_changes(print(" The stash was not restored because its cleanup baseline is unknown.")print(f" Restore manually with: git stash apply {stash_ref}")return False- clean_import_failures = _critical_module_import_failures(- cwd, report_runtime_errors=True- )+ clean_import_failures = _critical_module_import_failures(cwd, report_runtime_errors=True)print("→ Restoring local changes...")restore = _git_run(git_cmd, ["stash", "apply", stash_ref], cwd)@@ -400,11 +377,7 @@ def _restore_stashed_changes(print(f" Stash ref: {stash_ref}")# Always reset: conflict markers make hermes unrunnable; changes stay in the stash.- subprocess.run(- git_cmd + ["reset", "--hard", "HEAD"],- cwd=cwd,- capture_output=True,- )+ subprocess.run(git_cmd + ["reset", "--hard", "HEAD"], cwd=cwd, capture_output=True)print("Working tree reset to clean state.")print(f"Restore your changes later with: git stash apply {stash_ref}")# Don't exit: code update succeeded; cmd_update continues (deps, skills, gateway).@@ -420,9 +393,7 @@ def _restore_stashed_changes("restored Python source discovery","could not determine which restored Python files require validation",)- syntax_ok, failing_path, syntax_error = _validate_python_files_syntax(- cwd, restored_python- )+ syntax_ok, failing_path, syntax_error = _validate_python_files_syntax(cwd, restored_python)if not syntax_ok:_reject_unsafe_stash_restore(git_cmd,@@ -433,9 +404,7 @@ def _restore_stashed_changes(syntax_error,)- restored_import_failures = _critical_module_import_failures(- cwd, report_runtime_errors=True- )+ restored_import_failures = _critical_module_import_failures(cwd, report_runtime_errors=True)changed_import_failure = next(((module, error)@@ -457,9 +426,7 @@ def _restore_stashed_changes(stash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref)if stash_selector is None:- print(- "⚠ Local changes were restored, but Hermes couldn't find the stash entry to drop."- )+ print("⚠ Local changes were restored, but Hermes couldn't find the stash entry to drop.")print(" The stash was left in place. You can remove it manually after checking the result.")@@ -467,9 +434,7 @@ def _restore_stashed_changes(else:drop = _git_run(git_cmd, ["stash", "drop", stash_selector], cwd)if drop.returncode != 0:- print(- "⚠ Local changes were restored, but Hermes couldn't drop the saved stash entry."- )+ print("⚠ Local changes were restored, but Hermes couldn't drop the saved stash entry.")if drop.stdout.strip():print(drop.stdout.strip())if drop.stderr.strip():diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex e21493de737..2933ccbdf4c 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -270,9 +270,7 @@ def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) ->Labels come from the parsed SUBCOMMAND, never substring: a standalone ``hermes dashboard`` must not becalled the Desktop backend, ``--preserve-cache`` must not match "serve". Unknown argv gets no hint."""- lines = [- "✗ Other Hermes processes are running from this install's venv:",- ]+ lines = ["✗ Other Hermes processes are running from this install's venv:"]hint_by_subcommand = {"serve": " ← Hermes backend (if the Desktop app is open, close it)","dashboard": " ← hermes dashboard (stop it: hermes dashboard stop, or close that terminal)",@@ -285,15 +283,9 @@ def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) ->if len(matches) > 6:lines.append(f" ... and {len(matches) - 6} more")lines.append("")- lines.append(- " On Windows these keep native extension files (.pyd) locked, so the"- )- lines.append(- " dependency update would fail partway and leave a broken install."- )- lines.append(- " Close the Hermes desktop app / other Hermes terminals, then re-run:"- )+ lines.append(" On Windows these keep native extension files (.pyd) locked, so the")+ lines.append(" dependency update would fail partway and leave a broken install.")+ lines.append(" Close the Hermes desktop app / other Hermes terminals, then re-run:")lines.append(" hermes update")lines.append(" (or use `hermes update --force-venv` to proceed anyway at your own risk)")return "\n".join(lines)@@ -381,11 +373,7 @@ def _refuse_gateway_ancestor_tree_kill(try:from hermes_cli.gateway import _is_pid_ancestor_of_current_process- ancestors = [- int(pid)- for pid in pids- if _is_pid_ancestor_of_current_process(int(pid))- ]+ ancestors = [int(pid) for pid in pids if _is_pid_ancestor_of_current_process(int(pid))]except Exception as exc:logger.debug("Could not inspect gateway ancestry before tree-kill: %s", exc)return False@@ -398,10 +386,7 @@ def _refuse_gateway_ancestor_tree_kill("✗ Refusing to stop the gateway process tree because this updater "f"is running inside it (gateway PID(s): {rendered}).")- print(- " On Windows, taskkill /T would terminate the updater before the "- "update can run."- )+ print(" On Windows, taskkill /T would terminate the updater before the update can run.")print(" From a chat platform, use `/update` instead.")print(" Otherwise, run `hermes update` from a separate terminal.")return True@@ -502,9 +487,7 @@ def _relaunch_stopped_serves(token: dict) -> None:def _is_backend_argv(argv_low: str) -> bool:"""Whether a lower-cased argv is a Desktop backend (``hermes_cli.main`` running ``serve``/``dashboard``)."""- return "hermes_cli.main" in argv_low and (- " serve" in argv_low or " dashboard" in argv_low- )+ return "hermes_cli.main" in argv_low and (" serve" in argv_low or " dashboard" in argv_low)def _live_argv_low(psutil, pid, cmdline: str) -> str | None:@@ -668,19 +651,13 @@ def _stop_process_trees(expected_start_time = get_process_start_time(pid)try:if expected_start_time is None:- logger.debug(- "Skipping taskkill of PID %s: process identity unavailable",- pid,- )+ logger.debug("Skipping taskkill of PID %s: process identity unavailable", pid)continueif not pid_is_hermes(pid,expected_start_time=expected_start_time,):- logger.debug(- "Skipping taskkill of non-Hermes or changed PID %s",- pid,- )+ logger.debug("Skipping taskkill of non-Hermes or changed PID %s", pid)continuesubprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"],@@ -776,9 +753,7 @@ def _stop_windows_gateway_service(f"Windows service {name} is not stably running before stop: {current_status}")if current_service_pid != int(expected_service_identity[0]):- raise RuntimeError(- f"Windows service {name} SCM process identity changed before stop"- )+ raise RuntimeError(f"Windows service {name} SCM process identity changed before stop")for label, identity in (("service", expected_service_identity),("gateway", expected_gateway_identity),@@ -793,24 +768,18 @@ def _stop_windows_gateway_service(f"Windows {label} process identity is unavailable before stop") from excif abs(current - float(create_time)) > 0.001:- raise RuntimeError(- f"Windows {label} process identity changed before stop"- )+ raise RuntimeError(f"Windows {label} process identity changed before stop")if expected_service_identity is not None and expected_gateway_identity is not None:service_pid = int(expected_service_identity[0])gateway_pid = int(expected_gateway_identity[0])try:- ancestor_pids = {- int(parent.pid) for parent in psutil.Process(gateway_pid).parents()- }+ ancestor_pids = {int(parent.pid) for parent in psutil.Process(gateway_pid).parents()}except Exception as exc:raise RuntimeError("Windows gateway ancestry is unavailable before service stop") from excif service_pid not in ancestor_pids:- raise RuntimeError(- f"Windows gateway is no longer owned by service {name}"- )+ raise RuntimeError(f"Windows gateway is no longer owned by service {name}")result = subprocess.run(["sc.exe", "stop", name],capture_output=True,@@ -985,10 +954,7 @@ def _pause_windows_gateway_services(service_gateways, token: dict, profiles: dicfor service in service_gatewaysif str(service.name) in paused_services}- print(- " ✓ Paused Windows gateway service(s): "- + ", ".join(paused_services)- )+ print(" ✓ Paused Windows gateway service(s): " + ", ".join(paused_services))return tokenexcept Exception as exc:restore_names = []@@ -1034,26 +1000,18 @@ def _pause_windows_gateways_for_update() -> dict | None:find_windows_gateway_services,)except Exception as exc:- raise RuntimeError(- f"Could not prepare Windows gateway pause for update: {exc}"- ) from exc+ raise RuntimeError(f"Could not prepare Windows gateway pause for update: {exc}") from exctry:profile_process_list = find_profile_gateway_processes(strict=True)profile_processes = {proc.pid: proc for proc in profile_process_list}except Exception as exc:- raise RuntimeError(- f"Could not map Windows gateway PIDs to profiles: {exc}"- ) from exc+ raise RuntimeError(f"Could not map Windows gateway PIDs to profiles: {exc}") from exctry:- service_gateways = find_windows_gateway_services(- profile_processes=profile_process_list- )+ service_gateways = find_windows_gateway_services(profile_processes=profile_process_list)except Exception as exc:- raise RuntimeError(- f"Could not determine Windows gateway service ownership: {exc}"- ) from exc+ raise RuntimeError(f"Could not determine Windows gateway service ownership: {exc}") from excservice_gateway_pids = {int(service.gateway_pid) for service in service_gateways}try:@@ -1067,9 +1025,7 @@ def _pause_windows_gateways_for_update() -> dict | None:))except Exception as exc:- raise RuntimeError(- f"Could not discover Windows gateway PIDs before update: {exc}"- ) from exc+ raise RuntimeError(f"Could not discover Windows gateway PIDs before update: {exc}") from excif not running_pids:return _windows_cold_start_plan()@@ -1094,9 +1050,7 @@ def _pause_windows_gateways_for_update() -> dict | None:if ack and (ack.get("pausing") or ack.get("already_stopping")):socket_acks.append(ack)except Exception as exc:- logger.debug(- "Socket pause unavailable for gateway %s: %s", pid, exc- )+ logger.debug("Socket pause unavailable for gateway %s: %s", pid, exc)# Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be# recovered (NoSuchProcess). The launcher keeps ``.pyd`` mapped and would trip the@@ -1112,18 +1066,13 @@ def _pause_windows_gateways_for_update() -> dict | None:# A socket-paused gateway drains its ACTIVE TURN first; honor its declared# budget (+ teardown grace) so it isn't force-killed mid-turn.with suppress(Exception):- declared = max(- float(a.get("drain_timeout") or 0.0) for a in socket_acks- )+ declared = max(float(a.get("drain_timeout") or 0.0) for a in socket_acks)drain_timeout = max(drain_timeout, declared + 10.0)print(f" → {len(socket_acks)} gateway(s) ACKed socket pause; "f"waiting up to {int(drain_timeout)}s for graceful exit")- survivors = _m()._wait_for_windows_update_gateway_exit(- mapped_pids,- timeout=drain_timeout,- )+ survivors = _m()._wait_for_windows_update_gateway_exit(mapped_pids, timeout=drain_timeout)unmapped_pids = [pidfor pid in running_pids@@ -1147,11 +1096,7 @@ def _pause_windows_gateways_for_update() -> dict | None:for pid in sorted(set(survivors).union(unmapped_pids).union(launcher_pids)):with suppress(ProcessLookupError, PermissionError, OSError):pid_int = int(pid)- terminate_pid(- pid_int,- force=True,- expected_start_time=get_process_start_time(pid_int),- )+ terminate_pid(pid_int, force=True, expected_start_time=get_process_start_time(pid_int))force_killed.append(pid_int)if profiles:@@ -1161,9 +1106,7 @@ def _pause_windows_gateways_for_update() -> dict | None:if unmapped_pids:respawnable = sum(1 for u in unmapped if u.get("argv"))- print(- f" → Stopped {len(unmapped_pids)} gateway process(es) without profile mapping"- )+ print(f" → Stopped {len(unmapped_pids)} gateway process(es) without profile mapping")if respawnable < len(unmapped_pids):# No recoverable cmdline (psutil missing, access denied, gone): manual restart.print(" Restart manually after update: hermes gateway run")@@ -1192,24 +1135,18 @@ def _cold_start_windows_gateway_after_update() -> bool:from hermes_cli import gateway_windowsfrom hermes_cli.gateway import find_gateway_pidsexcept Exception as exc:- raise RuntimeError(- f"Could not load Windows gateway cold-start helpers: {exc}"- ) from exc+ raise RuntimeError(f"Could not load Windows gateway cold-start helpers: {exc}") from exc# Re-check liveness right before spawning: autostart may have brought one up. Don't double-start.try:if list(find_gateway_pids(all_profiles=True)):return Trueexcept Exception as exc:- raise RuntimeError(- f"Could not re-check gateway liveness before cold-start: {exc}"- ) from exc+ raise RuntimeError(f"Could not re-check gateway liveness before cold-start: {exc}") from exctry:if _desktop_owns_gateway_lifecycle():- logger.debug(- "Skipping Windows gateway cold-start: Desktop owns gateway lifecycle"- )+ logger.debug("Skipping Windows gateway cold-start: Desktop owns gateway lifecycle")return Trueexcept Exception as exc:raise RuntimeError(@@ -1226,9 +1163,7 @@ def _cold_start_windows_gateway_after_update() -> bool:raise RuntimeError("Windows gateway cold-start did not return a process ID")ready_pids = gateway_windows._wait_for_gateway_ready()if not ready_pids:- raise RuntimeError(- f"Windows gateway cold-start PID {pid} did not become ready"- )+ raise RuntimeError(f"Windows gateway cold-start PID {pid} did not become ready")print()print("✓ Gateway started via cold-start after update "@@ -1237,9 +1172,7 @@ def _cold_start_windows_gateway_after_update() -> bool:# Persist vouched PIDs so a death AFTER updater exit (Job Object teardown) is# reported by the next CLI invocation. Best-effort.with suppress(Exception):- gateway_windows._write_start_attestation(- ready_pids, "cold-start after update"- )+ gateway_windows._write_start_attestation(ready_pids, "cold-start after update")return True@@ -1352,10 +1285,7 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:token["restarted_services"] = verified_restartsif restarted_services:print()- print(- " ✓ Restarted Windows gateway service(s): "- + ", ".join(restarted_services)- )+ print(" ✓ Restarted Windows gateway service(s): " + ", ".join(restarted_services))profiles = token.get("profiles") or {}unmapped = token.get("unmapped") or []@@ -1374,9 +1304,7 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:launch_detached_profile_gateway_restart,)except Exception as exc:- raise RuntimeError(- f"Could not load Windows gateway restart helper: {exc}"- ) from exc+ raise RuntimeError(f"Could not load Windows gateway restart helper: {exc}") from excrelaunched = []failed_profiles = {}@@ -1433,12 +1361,8 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:try:from hermes_cli import gateway_windowsexcept Exception as exc:- raise RuntimeError(- f"Could not load Windows gateway liveness helpers: {exc}"- ) from exc- ready_pids = gateway_windows._wait_for_gateway_ready(- timeout_s=30.0, all_profiles=True- )+ raise RuntimeError(f"Could not load Windows gateway liveness helpers: {exc}") from exc+ ready_pids = gateway_windows._wait_for_gateway_ready(timeout_s=30.0, all_profiles=True)if not ready_pids:token["profiles"] = dict(profiles)token["unmapped"] = list(unmapped)@@ -1452,15 +1376,11 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:"Job Object during updater teardown, #48820.)")print(" Recover with: hermes gateway restart")- raise RuntimeError(- "Windows gateway relaunch after update was not verified alive"- )+ raise RuntimeError("Windows gateway relaunch after update was not verified alive")# Persist vouched PIDs so a death AFTER updater exit is reported by the# next CLI invocation. Best-effort.with suppress(Exception):- gateway_windows._write_start_attestation(- ready_pids, "post-update relaunch"- )+ gateway_windows._write_start_attestation(ready_pids, "post-update relaunch")token["resume_needed"] = False@@ -1470,9 +1390,7 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:if unmapped_relaunched:if not relaunched:print()- print(- f" ✓ Restarting {unmapped_relaunched} unmapped Windows gateway process(es)"- )+ print(f" ✓ Restarting {unmapped_relaunched} unmapped Windows gateway process(es)")def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume, gateway_mode: bool):@@ -1485,10 +1403,7 @@ def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume,except Exception as _windows_resume_exc:outcome.incomplete = Trueoutcome.phase_errors.append(str(_windows_resume_exc))- print(- " ⚠ Windows gateway service restart incomplete: "- f"{_windows_resume_exc}"- )+ print(f" ⚠ Windows gateway service restart incomplete: {_windows_resume_exc}")if gateway_mode:_write_gateway_update_exit_code(False)@@ -1498,9 +1413,7 @@ def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume,for _win_profile in _windows_gateway_resume.get("relaunched_profiles") or []:if _win_profile not in outcome.relaunched_profiles:outcome.relaunched_profiles.append(_win_profile)- windows_restarted = list(- _windows_gateway_resume.get("restarted_services") or []- )+ windows_restarted = list(_windows_gateway_resume.get("restarted_services") or [])for service_name in windows_restarted:if service_name not in outcome.restarted_services:outcome.restarted_services.append(service_name)@@ -1547,9 +1460,7 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatewif _refuse_gateway_ancestor_tree_kill(_gateway_holders, gateway_mode=gateway_mode):- _m()._resume_windows_gateways_after_update(- _windows_gateway_resume- )+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)sys.exit(2)# Gateways the pause machinery owns (respawned in the pause->guard window or# unmapped spawn path): stop and re-check; post-update resume brings them back.@@ -1568,9 +1479,7 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatewexpected_start_time=get_process_start_time(pid_int),)except Exception as exc:- logger.debug(- "Could not stop leftover gateway %s: %s", _pid, exc- )+ logger.debug("Could not stop leftover gateway %s: %s", _pid, exc)_time.sleep(1.0)_venv_holders = _m()._detect_venv_python_processes()if _venv_holders:@@ -1608,23 +1517,12 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew"backend(s) hold the venv; stopping them for the update ""(they will be relaunched on their recorded endpoints)")- _m()._stop_process_trees(- [int(e["pid"]) for e in _serve_entries]- )- _serve_resume_token = {- "pending": True,- "entries": _serve_entries,- }- _record_update_step(- "serve_pause",- True,- f"stopped={len(_serve_entries)}",- )+ _m()._stop_process_trees([int(e["pid"]) for e in _serve_entries])+ _serve_resume_token = {"pending": True, "entries": _serve_entries}+ _record_update_step("serve_pause", True, f"stopped={len(_serve_entries)}")import atexit as _serve_atexit- _serve_atexit.register(- _m()._relaunch_stopped_serves, _serve_resume_token- )+ _serve_atexit.register(_m()._relaunch_stopped_serves, _serve_resume_token)_time.sleep(1.0)_venv_holders = _m()._detect_venv_python_processes()if _venv_holders:diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 30c033b6c81..68fedce164d 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -140,15 +140,13 @@ def _zip_overlay_block_reason(# swap, so they must not cause a false refusal. Everything else — including ignored files — blocks.lines = [line for line in lines if not _is_zip_preserved_entry_status_line(line)]if ignore_staging_artifacts:- lines = [- line for line in lines if not _is_zip_staging_artifact_status_line(line)- ]+ lines = [line for line in lines if not _is_zip_staging_artifact_status_line(line)]if lines:return "the working tree has uncommitted changes or untracked files"return None-_ZIP_STAGING_ARTIFACT_SUFFIXES = (".hermes-update-staging", ".hermes-update-old")+_ZIP_STAGING_ARTIFACT_SUFFIXES = ".hermes-update-staging", ".hermes-update-old"# Single source of truth for entries the ZIP swap preserves — used by the dirty-tree filter and the swap loop.@@ -166,9 +164,7 @@ def _is_zip_preserved_entry_status_line(line: str) -> bool:is_rename = any(code in "RC" for code in status)paths = payload.split(" -> ") if is_rename else [payload]for path in paths:- top_level = (- path.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]- )+ top_level = path.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]if top_level not in _ZIP_PRESERVED_TOP_LEVEL:return Falsereturn True@@ -177,9 +173,7 @@ def _is_zip_preserved_entry_status_line(line: str) -> bool:def _is_zip_staging_artifact_status_line(line: str) -> bool:"""True when a porcelain status line is our own two-phase-swap artifact."""payload = line[3:] if len(line) >= 3 else line- top_level = (- payload.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]- )+ top_level = payload.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]return top_level.endswith(_ZIP_STAGING_ARTIFACT_SUFFIXES)@@ -233,9 +227,7 @@ def _download_and_swap_zip(branch: str, zip_url: str) -> None:# Unix mode lives in the upper 16 bits of external_attr; mask to the file-type bits.mode = (member.external_attr >> 16) & 0o170000if _stat.S_ISLNK(mode):- raise ValueError(- f"ZIP contains unsupported symlink member: {member.filename}"- )+ raise ValueError(f"ZIP contains unsupported symlink member: {member.filename}")zf.extractall(tmp_dir)# GitHub ZIPs extract to hermes-agent-<branch>/@@ -284,9 +276,7 @@ def _download_and_swap_zip(branch: str, zip_url: str) -> None:# it deletes the build and breaks the shortcut. Graft the live release dir in BEFORE the swap.if item == "apps":live_release = os.path.join(dst, "desktop", "release")- staged_release = os.path.join(- staged[-1][0], "desktop", "release"- )+ staged_release = os.path.join(staged[-1][0], "desktop", "release")if os.path.isdir(live_release) and not os.path.exists(staged_release):@@ -416,10 +406,7 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo# prevent. Refuse rather than lie.branch = _m()._resolve_update_branch(args)if branch != "main":- print(- f"✗ --branch={branch} is not supported on the Windows ZIP-fallback "- "update path."- )+ print(f"✗ --branch={branch} is not supported on the Windows ZIP-fallback " "update path.")print(" This path runs when git file I/O is broken on the system. ""Either resolve the git-side breakage (typically an antivirus "@@ -428,9 +415,7 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo)_m().sys.exit(1)_abort_zip_update_if_dirty_tree()- zip_url = (- f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip"- )+ zip_url = f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip"_download_and_swap_zip(branch, zip_url)@@ -447,9 +432,7 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo# Verify the tree imports (catches the parse-OK-but-skewed tree an interrupted copy leaves). Runs# *after* the dep reinstall so a genuinely-new third-party requirement isn't misreported as a partial# copy. No SHA to roll back to — surface a concrete recovery step instead of success over a bricked install.- 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("✗ Update left the install in an unimportable state:")@@ -495,7 +478,5 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boowith _best_effort('Update receipt finalize (zip path) failed: %s'):from hermes_cli.update_receipt import finalize_update_receipt- finalize_update_receipt(- "success" if update_complete and not node_failures else "partial"- )+ finalize_update_receipt("success" if update_complete and not node_failures else "partial")return update_complete