The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): dedupe update_cmd/update_cmd_deps — _updates_config, _print_update_check_result, unified uv/pip repair+sync branches, _git_run for raw git calls, _probe_failure/_clip/_npm_lock_cache_file
Teknium882b655f21d1
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 218cdb93f59..6f3ffd41743 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -124,6 +124,14 @@ def _m():return main+def _updates_config() -> dict:+ """The ``updates:`` config section (``{}`` when absent/malformed); may raise on config errors."""+ from hermes_cli.config import load_config++ section = (load_config() or {}).get("updates", {})+ return section if isinstance(section, dict) else {}++def _no_prompt_git_kwargs() -> dict:"""``subprocess.run`` kwargs for network git calls: GitHub answers anonymous fetches with401 during outages and git would then block forever on ``Username for ...``; disable only@@ -267,12 +275,8 @@ def _called_process_error_is_python_dep_install(if not parts:return Falseexe = os.path.basename(parts[0].replace("\\", "/"))- if "ensurepip" in parts:- return True- if "install" in parts and (- "pip" in parts or exe in {"pip", "pip.exe", "pip3", "pip3.exe", "uv", "uv.exe"}):- return True- return False+ return "ensurepip" in parts or ("install" in parts and (+ "pip" in parts or exe in {"pip", "pip.exe", "pip3", "pip3.exe", "uv", "uv.exe"}))def _format_update_failure_stage(exc: subprocess.CalledProcessError) -> str:@@ -345,19 +349,14 @@ def _print_called_process_error_tail(def _invalidate_update_cache():"""Delete the update-check cache for ALL profiles: the repo is shared, so one profile'supdate makes every profile current and a stale "commits behind" banner would linger."""- homes = []default_home = get_default_hermes_root()- homes.append(default_home)profiles_root = default_home / "profiles"+ homes = [default_home]if profiles_root.is_dir():- for entry in profiles_root.iterdir():- if entry.is_dir():- homes.append(entry)+ homes += [entry for entry in profiles_root.iterdir() if entry.is_dir()]for home in homes:with suppress(Exception):- cache_file = home / ".update_check"- if cache_file.exists():- cache_file.unlink()+ (home / ".update_check").unlink(missing_ok=True)def _write_marker_file(path: Path, *, label: str) -> None:@@ -385,24 +384,29 @@ def _format_concurrent_instances_message(matches: list[tuple[int, str]], scripts_dir: Path) -> str:"""Build a human-readable explanation + remediation hint for the user."""shim = scripts_dir / "hermes.exe"- lines = ["✗ Another hermes.exe is running:"]- for pid, name in matches:- lines.append(f" PID {pid} {name}")- lines.append("")- lines.append(f" Updating now would fail to overwrite {shim} because")- lines.append(" Windows blocks REPLACE on a running executable.")- lines.append("")- lines.append(" Close Hermes Desktop, exit any open `hermes` REPLs, and")- lines.append(" stop the gateway (`hermes gateway stop`) before retrying.")- lines.append("")+ lines = [+ "✗ Another hermes.exe is running:",+ *(f" PID {pid} {name}" for pid, name in matches),+ "",+ f" Updating now would fail to overwrite {shim} because",+ " Windows blocks REPLACE on a running executable.",+ "",+ " Close Hermes Desktop, exit any open `hermes` REPLs, and",+ " stop the gateway (`hermes gateway stop`) before retrying.",+ "",+ ]if matches:pid_args = " ".join(f"/PID {pid}" for pid, _ in matches)- lines.append(" If you've already closed everything and these PIDs are")- lines.append(" stale, terminate them directly, then retry the update:")- lines.append(f" taskkill {pid_args} /F")- lines.append("")- lines.append(" Override with `hermes update --force` if you've already")- lines.append(" confirmed those processes will not write to the venv.")+ lines += [+ " If you've already closed everything and these PIDs are",+ " stale, terminate them directly, then retry the update:",+ f" taskkill {pid_args} /F",+ "",+ ]+ lines += [+ " Override with `hermes update --force` if you've already",+ " confirmed those processes will not write to the venv.",+ ]return "\n".join(lines)@@ -426,21 +430,14 @@ def _classify_concurrent_instance(pid: int) -> str:from hermes_cli._scan_venv_blockers import _is_pausable_gateway # noqa: PLC0415- cmdline = " ".join(cmdline_list or [])- if _is_pausable_gateway(cmdline):- return "gateway"- return "non-gateway"+ return "gateway" if _is_pausable_gateway(" ".join(cmdline_list or [])) else "non-gateway"def _filter_non_gateway_concurrent_instances(matches: list[tuple[int, str]]) -> list[tuple[int, str]]:"""Drop gateway matches (the pause + post-update restart machinery handles them);anything else (TUI, Desktop backend child, another REPL) has no pause path, so the gate aborts."""- non_gateway: list[tuple[int, str]] = []- for pid, name in matches:- if _classify_concurrent_instance(pid) != "gateway":- non_gateway.append((pid, name))- return non_gateway+ return [(pid, name) for pid, name in matches if _classify_concurrent_instance(pid) != "gateway"]def _log_only_write(text: str) -> None:@@ -512,19 +509,13 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):_git_run(git_cmd, ["rev-parse", "--is-shallow-repository"]).stdout.strip() == "true")depth_args = ["--depth", "1"] if is_shallow else []- 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- fetch_result = None- if has_upstream_remote:- print("→ Fetching from upstream...")- fetch_result = _git_run(git_cmd, ["fetch"] + depth_args + ["upstream", branch], network=True)- if fetch_result is not None and fetch_result.returncode == 0:- compare_branch = f"upstream/{branch}"- else:- print("→ Fetching from origin...")- fetch_result = _git_run(git_cmd, ["fetch"] + depth_args + ["origin", branch], network=True)- compare_branch = f"origin/{branch}"+ # Probe locally for an 'upstream' remote before a network fetch non-forks always fail.+ fetch_result = None+ if branch == "main" and _git_run(git_cmd, ["remote", "get-url", "upstream"]).returncode == 0:+ print("→ Fetching from upstream...")+ fetch_result = _git_run(git_cmd, ["fetch"] + depth_args + ["upstream", branch], network=True)+ if fetch_result is not None and fetch_result.returncode == 0:+ compare_branch = f"upstream/{branch}"else:print("→ Fetching from origin...")fetch_result = _git_run(git_cmd, ["fetch"] + depth_args + ["origin", branch], network=True)@@ -547,33 +538,30 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):target_sha = _git_run(git_cmd, ["rev-parse", compare_branch]).stdout.strip()if head_sha and target_sha and head_sha == target_sha:print("✓ Already up to date.")- else:- from hermes_cli.banner import _github_compare_behind- from hermes_cli.config import recommended_update_command-- counted = _github_compare_behind(head_sha, target_sha)- if counted == 0: # local-ahead, not behind- print("✓ Already up to date.")- return- if counted is not None:- commits_word = "commit" if counted == 1 else "commits"- print(f"⚕ Update available: {counted} {commits_word} behind {compare_branch}.")- else:- print(f"⚕ Update available (behind {compare_branch}).")- print(f" Run '{recommended_update_command()}' to install.")+ return+ from hermes_cli.banner import _github_compare_behind++ # counted == 0 means local-ahead, not behind; None means the API could not count.+ _print_update_check_result(_github_compare_behind(head_sha, target_sha), compare_branch)returnrev_result = _git_run(git_cmd, ["rev-list", f"HEAD..{compare_branch}", "--count"], check=True)- behind = int(rev_result.stdout.strip())+ _print_update_check_result(int(rev_result.stdout.strip()), compare_branch)++def _print_update_check_result(behind: int | None, compare_branch: str) -> None:+ """Report ``--check``'s verdict: up to date, N commits behind, or behind by an unknown count."""if behind == 0:print("✓ Already up to date.")- else:+ return+ if behind is not None:commits_word = "commit" if behind == 1 else "commits"print(f"⚕ Update available: {behind} {commits_word} behind {compare_branch}.")- from hermes_cli.config import recommended_update_command+ else:+ print(f"⚕ Update available (behind {compare_branch}).")+ from hermes_cli.config import recommended_update_command- print(f" Run '{recommended_update_command()}' to install.")+ print(f" Run '{recommended_update_command()}' to install.")def _repair_current_checkout(@@ -628,21 +616,16 @@ def _repair_current_checkout(# Isolated from third-party UV env vars, like the other dependency syncs.from hermes_cli.managed_uv import managed_python_env- repair_env = managed_python_env()+ repair_prefix, repair_env = [repair_uv, "pip"], managed_python_env()repair_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")- _m()._install_python_dependencies_with_optional_fallback(- [repair_uv, "pip"], env=repair_env, group="all")- _m()._refresh_active_lazy_features(- [repair_uv, "pip"], env=repair_env, features=active_lazy_features)- _m()._restore_active_tool_dependencies(- active_tool_dependencies, [repair_uv, "pip"], env=repair_env)else:- _m()._install_python_dependencies_with_optional_fallback(- [sys.executable, "-m", "pip"], group="all")- _m()._refresh_active_lazy_features(- [sys.executable, "-m", "pip"], features=active_lazy_features)- _m()._restore_active_tool_dependencies(- active_tool_dependencies, [sys.executable, "-m", "pip"])+ repair_prefix, repair_env = [sys.executable, "-m", "pip"], None+ _m()._install_python_dependencies_with_optional_fallback(+ repair_prefix, env=repair_env, group="all")+ _m()._refresh_active_lazy_features(+ repair_prefix, env=repair_env, features=active_lazy_features)+ _m()._restore_active_tool_dependencies(+ active_tool_dependencies, repair_prefix, env=repair_env)_m()._clear_update_incomplete_marker()healthy_after, detail_after = _venv_core_imports_healthy()if healthy_after:@@ -696,18 +679,10 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:f" ⚠ Checkout is on custom branch '{_cur_branch}' — "f"merging origin/{branch} instead of resetting so local commits survive...")# Best-effort safety tag as a recovery anchor.- subprocess.run(- git_cmd- + ["tag", f"pre-update-{_time.strftime('%Y%m%d-%H%M%S')}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- check=False)+ _git_run(git_cmd, ["tag", f"pre-update-{_time.strftime('%Y%m%d-%H%M%S')}"])merge_result = _git_run(git_cmd, ["merge", "--no-edit", f"origin/{branch}"])if merge_result.returncode != 0:- subprocess.run(- git_cmd + ["merge", "--abort"], cwd=_m().PROJECT_ROOT, capture_output=True,- check=False,- )+ _git_run(git_cmd, ["merge", "--abort"])print("✗ Merge conflict between local commits and upstream — ""update stopped, nothing was changed.")@@ -720,8 +695,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:# reset. Orphan divergence (no common ancestor: corrupted HEAD, re-init) would# lose the whole local graph, so park pre_pull_sha behind a rescue ref first.merge_base_result = _git_run(git_cmd, ["merge-base", "HEAD", f"origin/{branch}"])- has_common_ancestor = bool(- merge_base_result.returncode == 0 and merge_base_result.stdout.strip())+ has_common_ancestor = merge_base_result.returncode == 0 and merge_base_result.stdout.strip()if not has_common_ancestor and pre_pull_sha:from datetime import datetime as _dt, timezone@@ -882,13 +856,8 @@ def _apply_parked_branch_guard(if switch_block_reason.startswith("unmerged:"):_in_place_configured = Falsewith _best_effort('Could not read updates.parked_branch_strategy: %s'):- from hermes_cli.config import load_config as _load_cfg-- _upd_cfg = (_load_cfg() or {}).get("updates", {})_in_place_configured = (- isinstance(_upd_cfg, dict)- and _upd_cfg.get("parked_branch_strategy", "switch")- == "update_in_place")+ _updates_config().get("parked_branch_strategy", "switch") == "update_in_place")if _in_place_configured and not switch_branch:# --branch typos used to surface via the checkout failing, which this path skips.verify_ref = _git_run(git_cmd, ["rev-parse", "--verify", "--quiet", f"origin/{branch}"])@@ -1035,17 +1004,10 @@ def _resolve_update_options(args, gateway_mode: bool) -> _UpdateOptions:gateway_mode or assume_yes or not (sys.stdin.isatty() and sys.stdout.isatty()))discard_local_changes = Falseif _non_interactive_update:- try:- from hermes_cli.config import load_config-- _update_cfg = (load_config() or {}).get("updates", {})- if isinstance(_update_cfg, dict):- _mode = str(_update_cfg.get("non_interactive_local_changes", "stash")).lower()- discard_local_changes = _mode == "discard"- except Exception as exc:- # A config read failure must never change the safe default.- logger.debug("Could not read updates.non_interactive_local_changes: %s", exc)- discard_local_changes = False+ # A config read failure must never change the safe default.+ with _best_effort("Could not read updates.non_interactive_local_changes: %s"):+ _mode = str(_updates_config().get("non_interactive_local_changes", "stash")).lower()+ discard_local_changes = _mode == "discard"return _UpdateOptions(active_lazy_features=active_lazy_features,active_tool_dependencies=active_tool_dependencies, pre_update_version=pre_update_version,@@ -1108,22 +1070,11 @@ def _prepare_git_command() -> tuple[bool, list, bool]:sys.exit(1)# Windows git can fail "unable to write loose object file: Invalid argument" (fs atomicity).- if sys.platform == "win32" and git_dir.exists():- subprocess.run(- [- "git",- "-c",- "windows.appendAtomically=false",- "config",- "windows.appendAtomically",- "false"],- cwd=_m().PROJECT_ROOT,- check=False,- capture_output=True)-git_cmd = ["git"]if sys.platform == "win32":git_cmd = ["git", "-c", "windows.appendAtomically=false"]+ if git_dir.exists():+ _git_run(git_cmd, ["config", "windows.appendAtomically", "false"])# A broken Git-for-Windows trampoline refuses every call with a "BUG (fork bomb)" guard;# swap in a real binary up front so git survives instead of degrading to ZIP.git_cmd = _ensure_non_trampoline_git(git_cmd)@@ -1228,25 +1179,17 @@ def _finish_already_up_to_date(_windows_gateway_resume) -> None:""""Already up to date" path: restore stash/branch, repair the checkout, catch up the fleet.``sys.exit(1)`` when the repair is incomplete (after gateway exit code + partial receipt)."""- auto_stash_ref = _plan.auto_stash_ref- parked_branch_switched = _plan.parked_branch_switched- prompt_for_restore = _plan.prompt_for_restore- switch_block_reason = _plan.switch_block_reason- upstream_checked = _plan.upstream_checked_invalidate_update_cache()# Restore stash and switch back if we moved. EXCEPTION: a parked branch verified clean +# fully merged stays on the target — re-parking on the stale branch recreates the incident.- if auto_stash_ref is not None:+ if _plan.auto_stash_ref is not None:_m()._restore_stashed_changes(- git_cmd,- _m().PROJECT_ROOT,- auto_stash_ref,- prompt_user=prompt_for_restore,+ git_cmd, _m().PROJECT_ROOT, _plan.auto_stash_ref, prompt_user=_plan.prompt_for_restore,input_fn=gw_input_fn)- if parked_branch_switched:- if switch_block_reason.startswith("unmerged:"):- _count = switch_block_reason.split(":", 1)[1]+ if _plan.parked_branch_switched:+ if _plan.switch_block_reason.startswith("unmerged:"):+ _count = _plan.switch_block_reason.split(":", 1)[1]print(f" ✓ Checkout was parked on '{current_branch}' — "f"switched back to {branch}; {_count} unmerged "@@ -1263,9 +1206,8 @@ def _finish_already_up_to_date(pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,had_desktop_app_before_update=had_desktop_app_before_update,active_lazy_features=active_lazy_features,- active_tool_dependencies=active_tool_dependencies, upstream_checked=upstream_checked,- _windows_gateway_resume=_windows_gateway_resume,- )+ active_tool_dependencies=active_tool_dependencies, upstream_checked=_plan.upstream_checked,+ _windows_gateway_resume=_windows_gateway_resume)_m()._resume_windows_gateways_after_update(_windows_gateway_resume)# A prior pull may still owe the fleet a restart; catch up here too, BEFORE the exit# gate so a partial outcome can't strand the fleet on stale code.@@ -1286,12 +1228,7 @@ def _cmd_update_impl(args, gateway_mode: bool):opts = _resolve_update_options(args, gateway_mode)active_lazy_features = opts.active_lazy_featuresactive_tool_dependencies = opts.active_tool_dependencies- pre_update_version = opts.pre_update_version- gw_input_fn = opts.gw_input_fn- assume_yes = opts.assume_yes- keep_stash = opts.keep_stash- switch_branch = opts.switch_branch- discard_local_changes = opts.discard_local_changes+ gw_input_fn, assume_yes = opts.gw_input_fn, opts.assume_yesprint("⚕ Updating Hermes Agent...")print()@@ -1368,13 +1305,9 @@ def _cmd_update_impl(args, gateway_mode: bool):_plan = _prepare_checkout_for_update(git_cmd, branch, current_branch, is_fork=is_fork, assume_yes=assume_yes,- gateway_mode=gateway_mode, gw_input_fn=gw_input_fn, switch_branch=switch_branch,- _windows_gateway_resume=_windows_gateway_resume,- )- auto_stash_ref = _plan.auto_stash_ref+ gateway_mode=gateway_mode, gw_input_fn=gw_input_fn, switch_branch=opts.switch_branch,+ _windows_gateway_resume=_windows_gateway_resume)commit_count = _plan.commit_count- in_place_update = _plan.in_place_update- prompt_for_restore = _plan.prompt_for_restoreif commit_count == 0:_finish_already_up_to_date(@@ -1396,17 +1329,15 @@ def _cmd_update_impl(args, gateway_mode: bool):print("→ Pulling updates...")pre_pull_sha = _pull_updates(- git_cmd, branch, auto_stash_ref, prompt_for_restore=prompt_for_restore,- gw_input_fn=gw_input_fn, discard_local_changes=discard_local_changes,- keep_stash=keep_stash,- )+ git_cmd, branch, _plan.auto_stash_ref, prompt_for_restore=_plan.prompt_for_restore,+ gw_input_fn=gw_input_fn, discard_local_changes=opts.discard_local_changes,+ keep_stash=opts.keep_stash)_invalidate_update_cache()post_pull_sha = _verify_head_after_pull(- git_cmd, branch, pre_pull_sha, in_place_update=in_place_update,- _windows_gateway_resume=_windows_gateway_resume,- )+ git_cmd, branch, pre_pull_sha, in_place_update=_plan.in_place_update,+ _windows_gateway_resume=_windows_gateway_resume)# Gateways still serve pre-pull modules until the restart phase; an interrupt before a# completed restart leaves this marker so the next update catches up even when git is@@ -1442,8 +1373,7 @@ def _cmd_update_impl(args, gateway_mode: bool):pre_update_snapshot_id=pre_update_snapshot_id,had_desktop_app_before_update=had_desktop_app_before_update,node_failures=node_failures, desktop_build_ok=desktop_build_ok,- pre_update_version=pre_update_version,- )+ pre_update_version=opts.pre_update_version)# Exit code *before* the restart: under --gateway this process lives in the gateway's# systemd cgroup and the systemctl-restart fallback SIGKILLs it (KillMode=mixed), sodiff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex 2c50bf6b036..eef2c4232d2 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -44,9 +44,7 @@ def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> booltext=True, encoding="utf-8", errors="replace")except OSError:return False- if result.returncode != 0:- return False- return not result.stdout.strip()+ return result.returncode == 0 and not result.stdout.strip()# Modules imported on every startup. Unlike _UPDATE_CRITICAL_FILES (only parsed) these are@@ -108,22 +106,16 @@ def _critical_module_import_failures(encoding="utf-8", errors="replace", timeout=120,)except subprocess.TimeoutExpired:- return {- "critical-module probe": (- "TimeoutExpired", "timed out before reporting import health")}+ return _probe_failure("TimeoutExpired", "timed out before reporting import health")except (OSError, subprocess.SubprocessError):# Can't run the probe — don't block the update on our own tooling.return {}output = result.stdout or ""if marker not in output:- return {- "critical-module probe": (- "ProbeTerminated",- "terminated before reporting import health "- f"(exit code {result.returncode})")}+ return _probe_failure(+ "ProbeTerminated",+ f"terminated before reporting import health (exit code {result.returncode})")try:- import json-failures = json.loads(output.rsplit(marker, 1)[1])if not isinstance(failures, list) or any(not isinstance(item, list)@@ -133,9 +125,12 @@ def _critical_module_import_failures(raise ValueError("invalid import-health payload")return {str(module): (str(kind), str(detail)) for module, kind, detail in failures}except (TypeError, ValueError):- return {- "critical-module probe": ( "MalformedPayload", "reported malformed import health data" )- }+ return _probe_failure("MalformedPayload", "reported malformed import health data")+++def _probe_failure(kind: str, detail: str) -> dict[str, tuple[str, str]]:+ """Failure row for the probe itself (as opposed to a module it imported)."""+ return {"critical-module probe": (kind, detail)}def _validate_critical_modules_import(@@ -280,9 +275,12 @@ def _restore_active_tool_dependencies(if restored:print(f" ✓ {len(restored)} restored: {', '.join(restored)}")for name, reason in failed:- if len(reason) > 200:- reason = reason[:200] + "..."- print(f" ⚠ {name} failed to restore: {reason}")+ print(f" ⚠ {name} failed to restore: {_clip(reason)}")+++def _clip(reason: str, limit: int = 200) -> str:+ """Bound a failure reason for the one-line report."""+ return reason if len(reason) <= limit else reason[:limit] + "..."def _refresh_active_lazy_features(@@ -304,15 +302,13 @@ def _refresh_active_lazy_features(logger.debug("Lazy refresh skipped (import failed): %s", exc)return True- if features is None:+ active = features+ if active is None:try:active = lazy_deps.active_features()except Exception as exc:logger.debug("Lazy refresh skipped (active_features failed): %s", exc)return True- else:- active = features-if not active:return True@@ -350,10 +346,7 @@ def _refresh_active_lazy_features(return Truefor feature, status in failed:- reason = status.split(": ", 1)[-1]- if len(reason) > 200:- reason = reason[:200] + "..."- print(f" ⚠ {feature} failed to refresh: {reason}")+ print(f" ⚠ {feature} failed to refresh: {_clip(status.split(': ', 1)[-1])}")if install_cmd_prefix is None:print(" ⚠ Lazy refresh failed; rerun `hermes update` once resolved.")@@ -521,9 +514,7 @@ def _npm_lockfile_changed(hermes_root: Path) -> bool:*_web_toolchain_roots(web_dir)):return Truetry:- # Key the cache by PROJECT_ROOT so parallel worktrees don't collide.- cache_key = hashlib.sha256(str(_m().PROJECT_ROOT).encode()).hexdigest()[:12]- cache_file = hermes_root / f".npm_lock_hash_{cache_key}"+ cache_file = _npm_lock_cache_file(hermes_root)if not cache_file.exists():return Truereturn cache_file.read_text(encoding="utf-8").strip() != current@@ -531,15 +522,19 @@ def _npm_lockfile_changed(hermes_root: Path) -> bool:return True-def _record_npm_lockfile_hash(hermes_root: Path) -> None:+def _npm_lock_cache_file(hermes_root: Path) -> Path:+ """Per-checkout cache path: keyed by PROJECT_ROOT so parallel worktrees don't collide."""from hermes_cli.update_cmd import _m+ cache_key = hashlib.sha256(str(_m().PROJECT_ROOT).encode()).hexdigest()[:12]+ return hermes_root / f".npm_lock_hash_{cache_key}"+++def _record_npm_lockfile_hash(hermes_root: Path) -> None:digest = _npm_manifests_digest()if digest is None:returntry:- cache_key = hashlib.sha256(str(_m().PROJECT_ROOT).encode()).hexdigest()[:12]- cache_file = hermes_root / f".npm_lock_hash_{cache_key}"- cache_file.write_text(digest, encoding="utf-8")+ _npm_lock_cache_file(hermes_root).write_text(digest, encoding="utf-8")except OSError:logger.debug("Could not write npm lockfile hash cache")@@ -608,12 +603,9 @@ def _update_node_dependencies() -> list[str]:print(" ⚠ Skipped: only a Windows npm is reachable from this WSL shell.")print(" Install Node.js inside the WSL distro (nvm, or your distro's")print(" package manager), then re-run `hermes update`.")- failed = []- if any(- (_m().PROJECT_ROOT / workspace / "package.json").exists()- for workspace in ("ui-tui", "web")):- failed.append("ui-tui, web workspaces")- return failed+ has_workspace = any(+ (_m().PROJECT_ROOT / ws / "package.json").exists() for ws in ("ui-tui", "web"))+ return ["ui-tui, web workspaces"] if has_workspace else []return []from hermes_constants import get_default_hermes_root@@ -662,15 +654,12 @@ def _update_node_dependencies() -> list[str]:if result.returncode == 0:_record_npm_lockfile_hash(shared_hermes_root)print(" ✓ ui-tui, web workspaces installed (desktop skipped)")- failures: list[str] = []- else:- print(" ⚠ npm install failed")- stderr = (result.stderr or "").strip() if result.stderr else ""- if stderr:- print(f" {stderr.splitlines()[-1]}")- failures = _partial_update_failure("ui-tui, web workspaces")-- return failures+ return []+ print(" ⚠ npm install failed")+ stderr = (result.stderr or "").strip()+ if stderr:+ print(f" {stderr.splitlines()[-1]}")+ return _partial_update_failure("ui-tui, web workspaces")def _venv_core_imports_healthy() -> tuple[bool, str]:@@ -789,17 +778,12 @@ def _detect_self_loaded_native_modules() -> list[str]:from hermes_cli.update_cmd import _mif not _m()._is_windows():return []- found = []- for prefix, (display, dist) in _SELF_LOCKING_NATIVE_MODULES.items():- if prefix not in sys.modules:- continue- # Defer ONLY on a CONFIRMED rewrite; unknown fails OPEN (PyYAML is in every process, so- # unknown-as-at-risk always fires). A missed deferral only yields the mid-sync os error 5- # that marker recovery already handles — far less harmful than an update that never runs.- if _m()._dependency_sync_would_rewrite(dist) is not True:- continue- found.append(display)- return sorted(set(found))+ # Defer ONLY on a CONFIRMED rewrite; unknown fails OPEN (PyYAML is in every process, so+ # unknown-as-at-risk always fires). A missed deferral only yields the mid-sync os error 5+ # that marker recovery already handles — far less harmful than an update that never runs.+ return sorted({+ display for prefix, (display, dist) in _SELF_LOCKING_NATIVE_MODULES.items()+ if prefix in sys.modules and _m()._dependency_sync_would_rewrite(dist) is True})def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:@@ -812,14 +796,14 @@ def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:locked = _m()._detect_self_loaded_native_modules()if locked:_m()._defer_update_for_self_lock(locked)- if gateway_resume is not None:- _m()._resume_windows_gateways_after_update(gateway_resume)- sys.exit(2)-- if _m()._reexec_dependency_sync_off_windows_shim():- if gateway_resume is not None:- _m()._resume_windows_gateways_after_update(gateway_resume)- sys.exit(0)+ exit_code = 2+ elif _m()._reexec_dependency_sync_off_windows_shim():+ exit_code = 0+ else:+ return+ if gateway_resume is not None:+ _m()._resume_windows_gateways_after_update(gateway_resume)+ sys.exit(exit_code)def _defer_update_for_self_lock(loaded: list[str]) -> None:@@ -866,7 +850,6 @@ def _rebuild_desktop_after_update(# Check the content-hash stamp IN-PROCESS first (the subprocess spends ~1-3 s importing the# CLI to reach the same check). Update never passes --source, so source_mode=False.# Any pre-check error falls through to the subprocess.- skip_desktop_build = Falsetry:skip_desktop_build = not _m()._desktop_build_needed(desktop_dir, _m().PROJECT_ROOT, source_mode=False)@@ -1031,6 +1014,7 @@ def _sync_python_dependencies_after_pull(uv_bin = ensure_uv()+ # sys.executable -m pip avoids PEP 668 'externally-managed-environment' errors.pip_cmd = [sys.executable, "-m", "pip"]if not uv_bin:uv_bin = _ensure_uv_for_termux(pip_cmd)@@ -1040,34 +1024,26 @@ def _sync_python_dependencies_after_pull(# managed_python_env() isolation so a third-party UV_PYTHON_INSTALL_DIR can't hijack uv.from hermes_cli.managed_uv import managed_python_env- uv_env = managed_python_env()- uv_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")- if _m()._is_termux_env(uv_env):- uv_env.pop("PYTHONPATH", None)- uv_env.pop("PYTHONHOME", None)- install_group = "termux-all"- print(" → Termux detected: using uv + curated termux-all optional profile...")- if not deps_current:- if _m()._is_termux_env(uv_env) and _is_android_python():- print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")- _install_psutil_android_compat([uv_bin, "pip"], env=uv_env)- _m()._install_python_dependencies_with_optional_fallback(- [uv_bin, "pip"], env=uv_env, group=install_group)+ install_prefix, lazy_env = [uv_bin, "pip"], managed_python_env()+ lazy_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")+ termux_note = " → Termux detected: using uv + curated termux-all optional profile..."else:- # sys.executable -m pip avoids PEP 668 'externally-managed-environment' errors.- pip_cmd = [sys.executable, "-m", "pip"]_ensure_venv_pip(pip_cmd, sys.executable)- if _m()._is_termux_env():- install_group = "termux-all"- print(" → Termux detected: using curated termux-all optional profile...")- if not deps_current:- if _m()._is_termux_env() and _is_android_python():- print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")- _install_psutil_android_compat(pip_cmd)- _m()._install_python_dependencies_with_optional_fallback(pip_cmd, group=install_group)-- install_prefix = [uv_bin, "pip"] if uv_bin else pip_cmd- lazy_env = uv_env if uv_bin else None+ install_prefix, lazy_env = pip_cmd, None+ termux_note = " → Termux detected: using curated termux-all optional profile..."+ is_termux = _m()._is_termux_env(lazy_env)+ if is_termux:+ if lazy_env is not None:+ lazy_env.pop("PYTHONPATH", None)+ lazy_env.pop("PYTHONHOME", None)+ install_group = "termux-all"+ print(termux_note)+ if not deps_current:+ if is_termux and _is_android_python():+ print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")+ _install_psutil_android_compat(install_prefix, env=lazy_env)+ _m()._install_python_dependencies_with_optional_fallback(+ install_prefix, env=lazy_env, group=install_group)if deps_current:# Verification normally runs inside the skipped install; run it here so a wrong skip