Skip to content

The agent that grows with you

refactor(hermes_cli): update_cmd — _apply_pulled_update/_repair_venv_on_current_checkout phase helpers, _base_git_cmd/_tip_shas/_current_branch_name/_pip_install_prefix/_finalize_receipt, early-return guards, print joins

Tekniume3114710400b
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index d61d12d1999..8c8fb7c342d 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1,9 +1,8 @@
"""Hermes update pipeline: dispatchers (``_cmd_update_impl``/``_cmd_update_check``) + git plumbing.
Each concern lives in ``update_cmd_<concern>.py`` and is re-imported here so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and stays monkeypatchable). Imports are
-one-way: main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at call
-time (no cycle, main-side test patches stay effective).
+``hermes_cli.update_cmd.<name>`` keeps resolving (and stays monkeypatchable). Imports are one-way:
+main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at call time.
"""
import logging
@@ -127,12 +126,9 @@ def _updates_config() -> dict:
def _no_prompt_git_kwargs() -> dict:
- """``subprocess.run`` kwargs for network git: GitHub answers anonymous fetches with 401 during
- outages and git would block forever on ``Username for ...``; disable only the *prompt*
- (credential helpers/askpass still run) so it fails fast into ``_classify_fetch_failure``."""
- env = dict(os.environ)
- env["GIT_TERMINAL_PROMPT"] = "0"
- env["GCM_INTERACTIVE"] = "Never"
+ """``subprocess.run`` kwargs for network git: a 401 (GitHub outage) would block forever on
+ ``Username for ...``; disable only the *prompt* (credential helpers still run) so it fails fast."""
+ env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "Never"}
return {"stdin": subprocess.DEVNULL, "env": env}
@@ -169,9 +165,9 @@ def _capture_head_sha(git_cmd, cwd) -> str | None:
return None
-def _validate_python_files_syntax(
- root, relpaths) -> tuple[bool, str | None, str | None]:
- """Compile *relpaths* under *root* without writing bytecode into the tree."""
+def _validate_python_files_syntax(root, relpaths) -> tuple[bool, str | None, str | None]:
+ """Compile *relpaths* under *root*; the .pyc goes to a temp dir, not ``__pycache__/`` (no
+ race with test workers, no stale pyc for another interpreter)."""
import py_compile
import tempfile
root = Path(root)
@@ -191,9 +187,7 @@ def _validate_python_files_syntax(
def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]:
- """Compile ``_UPDATE_CRITICAL_FILES`` -> ``(ok, failing_path, error_message)``. The .pyc goes
- to a temp dir, not ``__pycache__/`` (no race with test workers, no stale pyc for another
- interpreter)."""
+ """Compile ``_UPDATE_CRITICAL_FILES`` -> ``(ok, failing_path, error_message)``."""
return _validate_python_files_syntax(root, _UPDATE_CRITICAL_FILES)
@@ -204,9 +198,7 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0)
import uuid as _uuid
from hermes_constants import get_hermes_home # noqa: F811 (deliberate: constants variant)
home = get_hermes_home()
- prompt_path = home / ".update_prompt.json"
- response_path = home / ".update_response"
-
+ prompt_path, response_path = home / ".update_prompt.json", home / ".update_response"
response_path.unlink(missing_ok=True)
payload = {"prompt": prompt_text, "default": default, "id": str(_uuid.uuid4())}
@@ -254,8 +246,7 @@ def _called_process_error_is_git(exc: subprocess.CalledProcessError) -> bool:
return name in {"git", "git.exe"}
-def _called_process_error_is_python_dep_install(
- exc: subprocess.CalledProcessError) -> bool:
+def _called_process_error_is_python_dep_install(exc: subprocess.CalledProcessError) -> bool:
"""True when the failed subprocess was a uv/pip (or ensurepip) install."""
parts = [part.lower() for part in _called_process_error_cmd_parts(exc)]
if not parts:
@@ -318,8 +309,7 @@ def _should_zip_fallback_on_update_error(exc: BaseException) -> bool:
and _called_process_error_is_git(exc))
-def _print_called_process_error_tail(
- exc: subprocess.CalledProcessError, *, limit: int = 12) -> None:
+def _print_called_process_error_tail(exc: subprocess.CalledProcessError, *, limit: int = 12) -> None:
"""Print a captured stderr/stdout tail when the failing call recorded one."""
blob = exc.stderr or exc.stdout or ""
if isinstance(blob, bytes):
@@ -366,9 +356,8 @@ def _write_lazy_refresh_incomplete_marker() -> None:
_write_marker_file(_m()._lazy_refresh_marker_path(), label="lazy-refresh-incomplete")
-def _format_concurrent_instances_message(
- matches: list[tuple[int, str]], scripts_dir: Path) -> str:
- """Build a human-readable explanation + remediation hint for the user."""
+def _format_concurrent_instances_message(matches: list[tuple[int, str]], scripts_dir: Path) -> str:
+ """Explanation + remediation hint for the Windows concurrent-hermes.exe gate."""
shim = scripts_dir / "hermes.exe"
lines = [
"✗ Another hermes.exe is running:",
@@ -399,12 +388,7 @@ def _classify_concurrent_instance(pid: int) -> str:
"gateway" is exactly what the pause/restart machinery stops; "unknown" gates as non-gateway."""
try:
import psutil # noqa: PLC0415
- except Exception:
- return "unknown"
-
- try:
- proc = psutil.Process(int(pid))
- cmdline_list = proc.cmdline()
+ cmdline_list = psutil.Process(int(pid)).cmdline()
except Exception:
return "unknown"
@@ -412,8 +396,7 @@ def _classify_concurrent_instance(pid: int) -> str:
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]]:
+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."""
return [(pid, name) for pid, name in matches if _classify_concurrent_instance(pid) != "gateway"]
@@ -445,12 +428,10 @@ def _run_logged_subprocess(cmd, *, cwd=None, env=None):
def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
"""``hermes update --check``: fetch and report without installing. ``branch_explicit`` is
- True iff --branch was passed; installs that can't honor it (Docker) print a notice
- instead of silently dropping the flag."""
+ True iff --branch was passed (Docker installs print a notice instead of dropping the flag)."""
# Same marker-first admission gate as the apply path, so --check never reports git
# state for an install whose real update mechanism is an image pull.
- from hermes_cli.update_contract import (
- evaluate_update_admission, record_refusal_receipt)
+ from hermes_cli.update_contract import evaluate_update_admission, record_refusal_receipt
refusal = evaluate_update_admission(_m().PROJECT_ROOT)
if refusal is not None:
@@ -463,14 +444,11 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
print("✗ Not a git repository — cannot check for updates.")
sys.exit(1)
- git_cmd = ["git"]
- if sys.platform == "win32":
- git_cmd = ["git", "-c", "windows.appendAtomically=false"]
+ git_cmd = _base_git_cmd()
# Interrupted fetches leave .git/*.lock behind ("File exists" forever); self-heal first.
from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs
- cleared = clear_stale_git_locks(_m().PROJECT_ROOT)
- for lock_path in cleared:
+ for lock_path in clear_stale_git_locks(_m().PROJECT_ROOT):
print(f" (removed stale git lock: {lock_path})")
# Aborted fetches also strand tmp_pack_* debris (has reached 6 GB and corrupted the
# pack dir); same age+process safety contract as the locks.
@@ -482,8 +460,7 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
# upstream only for main (a fork's other branches have no upstream counterpart). Installer
# checkouts are shallow: a plain fetch would unshallow them and rev-list would report a
# bogus huge "behind" count, so fetch --depth 1 and report presence-only.
- is_shallow = (
- _git_run(git_cmd, ["rev-parse", "--is-shallow-repository"]).stdout.strip() == "true")
+ is_shallow = _is_shallow_checkout(git_cmd)
depth_args = ["--depth", "1"] if is_shallow else []
# Probe locally for an 'upstream' remote before a network fetch non-forks always fail.
@@ -511,8 +488,7 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
if is_shallow:
# No history across the shallow boundary: compare tip SHAs, then recover the
# exact count via the GitHub compare API (complete graph).
- head_sha = _git_run(git_cmd, ["rev-parse", "HEAD"]).stdout.strip()
- target_sha = _git_run(git_cmd, ["rev-parse", compare_branch]).stdout.strip()
+ head_sha, target_sha = _tip_shas(git_cmd, compare_branch)
if head_sha and target_sha and head_sha == target_sha:
print("✓ Already up to date.")
return
@@ -525,31 +501,89 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
_print_update_check_result(int(rev_result.stdout.strip()), compare_branch)
+def _base_git_cmd() -> list[str]:
+ """``git`` argv; Windows adds ``-c windows.appendAtomically=false`` (git can fail "unable to
+ write loose object file: Invalid argument" on non-atomic appends)."""
+ if sys.platform == "win32":
+ return ["git", "-c", "windows.appendAtomically=false"]
+ return ["git"]
+
+
+def _is_shallow_checkout(git_cmd) -> bool:
+ return _git_run(git_cmd, ["rev-parse", "--is-shallow-repository"]).stdout.strip() == "true"
+
+
+def _tip_shas(git_cmd, target_ref: str) -> tuple[str, str]:
+ """``(HEAD sha, <target_ref> sha)`` as printed by rev-parse ("" when unresolvable)."""
+ return tuple(_git_run(git_cmd, ["rev-parse", ref]).stdout.strip() for ref in ("HEAD", target_ref))
+
+
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.")
return
if behind is not None:
- commits_word = "commit" if behind == 1 else "commits"
- print(f"⚕ Update available: {behind} {commits_word} behind {compare_branch}.")
+ print(f"⚕ Update available: {behind} {'commit' if behind == 1 else 'commits'} behind {compare_branch}.")
else:
print(f"⚕ Update available (behind {compare_branch}).")
from hermes_cli.config import recommended_update_command
print(f" Run '{recommended_update_command()}' to install.")
-def _repair_current_checkout(
- *,
- assume_yes,
- gateway_mode,
- pre_update_snapshot_id,
- desktop_dir,
- had_desktop_app_before_update,
- active_lazy_features,
- active_tool_dependencies,
- upstream_checked,
+def _repair_venv_on_current_checkout(
+ *, assume_yes, gateway_mode, pre_update_snapshot_id, desktop_dir,
+ had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,
_windows_gateway_resume) -> bool:
+ """Reinstall ``.[all]`` + lazy/tool deps into an unhealthy (or handed-off) venv; returns
+ whether the checkout can be reported complete."""
+ # Self-lock deferral: the repair rewrites the venv too (same mapped-extension hazard).
+ _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)
+ _write_update_incomplete_marker()
+ from hermes_cli.managed_uv import ensure_uv
+ repair_uv = ensure_uv()
+ # Venv gone entirely (repair interrupted after the old one was moved aside): recreate.
+ venv_python_missing = not (
+ venv_python_path(_m().PROJECT_ROOT / "venv", windows=_m()._is_windows())).exists()
+ if venv_python_missing and repair_uv:
+ print("→ Recreating virtual environment...")
+ subprocess.run([repair_uv, "venv", "venv"], cwd=_m().PROJECT_ROOT, check=False)
+ repair_prefix, repair_env = _pip_install_prefix(repair_uv)
+ _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 not healthy_after:
+ print(f"⚠ Venv still unhealthy after repair: {detail_after}")
+ print(" Close all Hermes windows/gateways and re-run: hermes update")
+ return False
+ print("✓ Dependencies repaired!")
+ _check_and_apply_config_migration(
+ assume_yes=assume_yes, gateway_mode=gateway_mode, pre_update_snapshot_id=pre_update_snapshot_id)
+ # The hand-off child never reaches the commits-pulled rebuild; do it here.
+ if _rebuild_desktop_after_update(desktop_dir, had_desktop_app_before_update=had_desktop_app_before_update):
+ return _print_verified_update_completion("✓ Update complete!")
+ _print_update_completion(
+ "⚠ Update partially complete — the desktop app was not rebuilt and is still on the previous build.")
+ return False
+
+
+def _pip_install_prefix(uv_bin) -> tuple[list[str], dict | None]:
+ """``(install prefix, env)``: ``uv pip`` isolated from third-party UV env vars (so a foreign
+ UV_PYTHON_INSTALL_DIR can't hijack it), else ``sys.executable -m pip`` (avoids PEP 668 errors)."""
+ if uv_bin:
+ from hermes_cli.managed_uv import managed_python_env
+ env = managed_python_env()
+ env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
+ return [uv_bin, "pip"], env
+ return [sys.executable, "-m", "pip"], None
+
+
+def _repair_current_checkout(
+ *, assume_yes, gateway_mode, pre_update_snapshot_id, desktop_dir,
+ had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,
+ upstream_checked, _windows_gateway_resume) -> bool:
"""Already-up-to-date path: keep the managed runtime current, repair a broken venv.
Returns whether the checkout can be reported complete."""
# "No new commits" != safe interpreter: uv can keep the same CPython patch while
@@ -566,7 +600,6 @@ def _repair_current_checkout(
# The Windows shim hand-off child is current BY DESIGN; its one job is the pending sync,
# not venv health — without this it would print "Already up to date!" and skip it.
handed_off_sync = os.environ.get(_m()._UPDATE_REEXEC_ENV) == "1"
- current_checkout_complete = True
if handed_off_sync:
print("→ Finishing the dependency install handed off by hermes.exe...")
elif not healthy:
@@ -574,60 +607,19 @@ def _repair_current_checkout(
print(f" {detail}")
print("→ Repairing Python dependencies...")
if handed_off_sync or not healthy:
- # Self-lock deferral: the repair rewrites the venv too (same mapped-extension hazard).
- _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)
- _write_update_incomplete_marker()
- from hermes_cli.managed_uv import ensure_uv
- repair_uv = ensure_uv()
- # Venv gone entirely (repair interrupted after the old one was moved aside): recreate.
- venv_python_missing = not (
- venv_python_path(_m().PROJECT_ROOT / "venv", windows=_m()._is_windows())).exists()
- if venv_python_missing and repair_uv:
- print("→ Recreating virtual environment...")
- 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
- repair_prefix, repair_env = [repair_uv, "pip"], managed_python_env()
- repair_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
- else:
- 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:
- print("✓ Dependencies repaired!")
- _check_and_apply_config_migration(
- assume_yes=assume_yes,
- gateway_mode=gateway_mode,
- pre_update_snapshot_id=pre_update_snapshot_id)
- # The hand-off child never reaches the commits-pulled rebuild; do it here.
- if _rebuild_desktop_after_update(
- desktop_dir, had_desktop_app_before_update=had_desktop_app_before_update):
- current_checkout_complete = _print_verified_update_completion("✓ Update complete!")
- else:
- current_checkout_complete = False
- _print_update_completion(
- "⚠ Update partially complete — the desktop app was "
- "not rebuilt and is still on the previous build.")
- else:
- current_checkout_complete = False
- print(f"⚠ Venv still unhealthy after repair: {detail_after}")
- print(" Close all Hermes windows/gateways and re-run: hermes update")
+ current_checkout_complete = _repair_venv_on_current_checkout(
+ assume_yes=assume_yes, gateway_mode=gateway_mode,
+ 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,
+ _windows_gateway_resume=_windows_gateway_resume)
else:
current_checkout_complete = _repair_node_deps_on_current_checkout(
- _print_verified_update_completion,
- assume_yes=assume_yes,
- gateway_mode=gateway_mode,
+ _print_verified_update_completion, assume_yes=assume_yes, gateway_mode=gateway_mode,
pre_update_snapshot_id=pre_update_snapshot_id,
completion_message=(
- "✓ Already up to date!"
- if upstream_checked
+ "✓ Already up to date!" if upstream_checked
else "✓ Up to date with your fork (official repo not checked)."),
had_desktop_app_before_update=had_desktop_app_before_update)
if runtime_repaired is not None and not _m()._is_windows():
@@ -643,8 +635,8 @@ def _repair_current_checkout(
def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:
"""Fast-forward failed: merge on a custom branch (local commits survive) or reset --hard on the
same branch (rescue ref first when histories share no ancestor). ``sys.exit(1)`` on failure."""
- # 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.
+ # 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()
if _cur_branch and _cur_branch != branch:
print(
@@ -652,96 +644,77 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:
f"merging origin/{branch} instead of resetting so local commits survive...")
# Best-effort safety tag as a recovery anchor.
_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:
+ if _git_run(git_cmd, ["merge", "--no-edit", f"origin/{branch}"]).returncode != 0:
_git_run(git_cmd, ["merge", "--abort"])
- print(
- "✗ Merge conflict between local commits and upstream — "
- "update stopped, nothing was changed.")
- print(
- f" Resolve manually: cd {_m().PROJECT_ROOT} && " f"git merge origin/{branch}")
+ print("✗ Merge conflict between local commits and upstream — update stopped, nothing was changed.")
+ print(f" Resolve manually: cd {_m().PROJECT_ROOT} && git merge origin/{branch}")
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
- # 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 = 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
- # SHA suffix so two updates in the same second get distinct refs.
- rescue_ref = (
- f"refs/hermes-update-backups/orphan-{branch}-"
- f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}"
- f"-{pre_pull_sha[:12]}")
- update_ref_result = _git_run(git_cmd, ["update-ref", rescue_ref, pre_pull_sha])
- if update_ref_result.returncode == 0:
- print(
- " ⚠ Local history shares no common ancestor with "
- f"origin/{branch} (orphan divergence) — backed up "
- f"current HEAD to {rescue_ref} before resetting. "
- f"This backup expires after "
- f"{_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days.")
- else:
- # update-ref failure is intentionally non-fatal, but never claim a backup exists.
- print(
- " ⚠ Local history shares no common ancestor with "
- f"origin/{branch} (orphan divergence) — attempted "
- f"to back up current HEAD to {rescue_ref} before "
- "resetting, but the backup write failed "
- f"(pre-reset SHA was {pre_pull_sha}).")
- _prune_orphan_rescue_refs(git_cmd, _m().PROJECT_ROOT, branch)
- print(" ⚠ Fast-forward not possible (history diverged), resetting to match remote...")
- reset_result = _git_run(git_cmd, ["reset", "--hard", f"origin/{branch}"])
- if reset_result.returncode != 0:
- 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}")
- sys.exit(1)
+ return
+ # Same branch: a true upstream force-push/rebase; local changes are stashed, so 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 = 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
+ # SHA suffix so two updates in the same second get distinct refs.
+ rescue_ref = (
+ f"refs/hermes-update-backups/orphan-{branch}-"
+ f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{pre_pull_sha[:12]}")
+ head = f" ⚠ Local history shares no common ancestor with origin/{branch} (orphan divergence) — "
+ if _git_run(git_cmd, ["update-ref", rescue_ref, pre_pull_sha]).returncode == 0:
+ print(
+ f"{head}backed up current HEAD to {rescue_ref} before resetting. "
+ f"This backup expires after {_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days.")
+ else:
+ # update-ref failure is intentionally non-fatal, but never claim a backup exists.
+ print(
+ f"{head}attempted to back up current HEAD to {rescue_ref} before resetting, "
+ f"but the backup write failed (pre-reset SHA was {pre_pull_sha}).")
+ _prune_orphan_rescue_refs(git_cmd, _m().PROJECT_ROOT, branch)
+ print(" ⚠ Fast-forward not possible (history diverged), resetting to match remote...")
+ reset_result = _git_run(git_cmd, ["reset", "--hard", f"origin/{branch}"])
+ if reset_result.returncode != 0:
+ 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}")
+ sys.exit(1)
def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha) -> None:
"""Post-pull syntax guard: roll back to *pre_pull_sha* and ``sys.exit(1)`` when a critical
file no longer compiles (a bad admin-merge past CI must not brick the CLI)."""
- # 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)
- if not syntax_ok:
- print()
- print("✗ Pulled code has a syntax error in a critical file:")
- print(f" {failing_path}")
- if syntax_error:
- # py_compile errors can be multi-line; show enough for the SyntaxError text.
- for line in str(syntax_error).splitlines()[:6]:
- print(f" {line}")
- if pre_pull_sha:
- print()
- print(f"→ Rolling back to {pre_pull_sha[:10]}...")
- rollback_result = _git_run(git_cmd, ["reset", "--hard", pre_pull_sha])
- if rollback_result.returncode == 0:
- print(" ✓ Rollback complete — your install is unchanged.")
- print(" Try ``hermes update`` again later once a fix lands.")
- else:
- print(" ✗ Rollback failed. Recover manually with:")
- print(f" cd {_m().PROJECT_ROOT} && git reset --hard {pre_pull_sha}")
- if rollback_result.stderr.strip():
- print(f" ({rollback_result.stderr.strip().splitlines()[0]})")
+ if syntax_ok:
+ return
+ print()
+ print("✗ Pulled code has a syntax error in a critical file:")
+ print(f" {failing_path}")
+ # py_compile errors can be multi-line; show enough for the SyntaxError text.
+ for line in str(syntax_error).splitlines()[:6] if syntax_error else ():
+ print(f" {line}")
+ print()
+ if pre_pull_sha:
+ print(f"→ Rolling back to {pre_pull_sha[:10]}...")
+ rollback_result = _git_run(git_cmd, ["reset", "--hard", pre_pull_sha])
+ if rollback_result.returncode == 0:
+ print(" ✓ Rollback complete — your install is unchanged.")
+ print(" Try ``hermes update`` again later once a fix lands.")
else:
- print()
- print(" Could not capture pre-pull SHA — recover manually with:")
- print(f" cd {_m().PROJECT_ROOT} && git reflog && git reset --hard <prev-sha>")
- sys.exit(1)
+ print(" ✗ Rollback failed. Recover manually with:")
+ print(f" cd {_m().PROJECT_ROOT} && git reset --hard {pre_pull_sha}")
+ if rollback_result.stderr.strip():
+ print(f" ({rollback_result.stderr.strip().splitlines()[0]})")
+ else:
+ print(" Could not capture pre-pull SHA — recover manually with:")
+ print(f" cd {_m().PROJECT_ROOT} && git reflog && git reset --hard <prev-sha>")
+ sys.exit(1)
def _pull_updates(
- git_cmd,
- branch,
- auto_stash_ref,
- *,
- prompt_for_restore,
- gw_input_fn,
- discard_local_changes,
+ git_cmd, branch, auto_stash_ref, *, prompt_for_restore, gw_input_fn, discard_local_changes,
keep_stash):
"""Fast-forward onto ``origin/<branch>`` and settle the autostash. Divergence by shape:
custom branch -> merge, same branch -> reset, orphan history -> rescue ref first; a
@@ -752,12 +725,9 @@ def _pull_updates(
try:
# merge --ff-only the already-fetched ref instead of `git pull`, which would do a
# SECOND network fetch; identical in effect given the fresh tracking ref.
- pull_result = _git_run(git_cmd, ["merge", "--ff-only", f"origin/{branch}"])
- if pull_result.returncode != 0:
+ if _git_run(git_cmd, ["merge", "--ff-only", f"origin/{branch}"]).returncode != 0:
_reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha)
-
_rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha)
-
update_succeeded = True
finally:
if auto_stash_ref is not None:
@@ -773,10 +743,7 @@ def _pull_updates(
_m()._park_stashed_changes(auto_stash_ref)
else:
_m()._restore_stashed_changes(
- git_cmd,
- _m().PROJECT_ROOT,
- auto_stash_ref,
- prompt_user=prompt_for_restore,
+ git_cmd, _m().PROJECT_ROOT, auto_stash_ref, prompt_user=prompt_for_restore,
input_fn=gw_input_fn)
return pre_pull_sha
@@ -806,59 +773,41 @@ def _apply_parked_branch_guard(
touch nothing, warn, ``sys.exit(1)`` with the code update SKIPPED (also when the target is
missing). Returns ``(parked_branch_switched, in_place_update, switch_block_reason)``.
"""
- switch_block_reason = None # only meaningful when parked_branch_switched
- parked_branch_switched = False
- in_place_update = False
- if current_branch != branch and current_branch != "HEAD":
- switch_safe, switch_block_reason = _m()._assess_parked_branch_switch(
- git_cmd, _m().PROJECT_ROOT, current_branch, branch)
- if not switch_safe:
- _m()._print_parked_branch_skip_warning(
- git_cmd, _m().PROJECT_ROOT, current_branch, branch, switch_block_reason)
- print()
- print(
- "⚠ Update finished — code update SKIPPED"
- f"{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")
- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
- sys.exit(1)
- if switch_block_reason.startswith("unmerged:"):
- _in_place_configured = False
- with _best_effort('Could not read updates.parked_branch_strategy: %s'):
- _in_place_configured = (
- _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}"])
- if verify_ref.returncode != 0:
- print(f"✗ Branch '{branch}' does not exist locally or on origin.")
- sys.exit(1)
- in_place_update = True
- print(
- f" ℹ On branch '{current_branch}' — updating it in place from "
- f"origin/{branch} (no branch switch; local commits preserved).")
- else:
- parked_branch_switched = True
- _m()._print_parked_branch_kept_notice(
- current_branch, branch, switch_block_reason.split(":", 1)[1])
- else:
- parked_branch_switched = True
- print(
- f" ⚠ Checkout was parked on '{current_branch}' "
- f"(fully merged) — switching back to {branch}...")
- return parked_branch_switched, in_place_update, switch_block_reason
+ if current_branch == branch or current_branch == "HEAD":
+ return False, False, None
+ switch_safe, switch_block_reason = _m()._assess_parked_branch_switch(
+ git_cmd, _m().PROJECT_ROOT, current_branch, branch)
+ if not switch_safe:
+ _m()._print_parked_branch_skip_warning(
+ git_cmd, _m().PROJECT_ROOT, current_branch, branch, switch_block_reason)
+ print()
+ print(f"⚠ Update finished — code update SKIPPED{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")
+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
+ sys.exit(1)
+ if not switch_block_reason.startswith("unmerged:"):
+ print(f" ⚠ Checkout was parked on '{current_branch}' (fully merged) — switching back to {branch}...")
+ return True, False, switch_block_reason
+ _in_place_configured = False
+ with _best_effort('Could not read updates.parked_branch_strategy: %s'):
+ _in_place_configured = (
+ _updates_config().get("parked_branch_strategy", "switch") == "update_in_place")
+ if not _in_place_configured or switch_branch:
+ _m()._print_parked_branch_kept_notice(
+ current_branch, branch, switch_block_reason.split(":", 1)[1])
+ return True, False, switch_block_reason
+ # --branch typos used to surface via the checkout failing, which this path skips.
+ if _git_run(git_cmd, ["rev-parse", "--verify", "--quiet", f"origin/{branch}"]).returncode != 0:
+ print(f"✗ Branch '{branch}' does not exist locally or on origin.")
+ sys.exit(1)
+ print(
+ f" ℹ On branch '{current_branch}' — updating it in place from "
+ f"origin/{branch} (no branch switch; local commits preserved).")
+ return False, True, switch_block_reason
def _prepare_checkout_for_update(
- git_cmd,
- branch,
- current_branch,
- *,
- is_fork,
- assume_yes,
- gateway_mode,
- gw_input_fn,
- switch_branch,
- _windows_gateway_resume):
+ git_cmd, branch, current_branch, *, is_fork, assume_yes, gateway_mode, gw_input_fn,
+ switch_branch, _windows_gateway_resume):
"""Parked-branch guard, land on the target, stash, count new commits. Exits when the
checkout is unsafe to move or the target is missing. ``commit_count`` is 0 when up to
date, -1 when tips differ but the shallow count is unrecoverable."""
@@ -866,28 +815,22 @@ def _prepare_checkout_for_update(
git_cmd, branch, current_branch, switch_branch=switch_branch,
_windows_gateway_resume=_windows_gateway_resume)
- if not in_place_update and current_branch != branch:
- if current_branch == "HEAD":
- 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:
- track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])
- if track_result.returncode != 0:
- # Restore the stash before bailing so the user isn't stranded.
- if auto_stash_ref is not None:
- _m()._restore_stashed_changes(
- git_cmd,
- _m().PROJECT_ROOT,
- auto_stash_ref,
- prompt_user=False,
- input_fn=gw_input_fn)
- print(f"✗ Branch '{branch}' does not exist locally or on origin.")
- if track_result.stderr.strip():
- print(f" {track_result.stderr.strip().splitlines()[0]}")
- sys.exit(1)
- else:
- auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)
+ if not in_place_update and current_branch == "HEAD" != branch:
+ 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)
+ if (
+ not in_place_update and current_branch != branch
+ and _git_run(git_cmd, ["checkout", branch]).returncode != 0):
+ track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])
+ if track_result.returncode != 0:
+ # Restore the stash before bailing so the user isn't stranded.
+ if auto_stash_ref is not None:
+ _m()._restore_stashed_changes(
+ git_cmd, _m().PROJECT_ROOT, auto_stash_ref, prompt_user=False, input_fn=gw_input_fn)
+ print(f"✗ Branch '{branch}' does not exist locally or on origin.")
+ if track_result.stderr.strip():
+ print(f" {track_result.stderr.strip().splitlines()[0]}")
+ sys.exit(1)
prompt_for_restore = (
auto_stash_ref is not None
@@ -900,13 +843,10 @@ def _prepare_checkout_for_update(
result = _git_run(git_cmd, ["rev-list", f"HEAD..origin/{branch}", "--count"], check=True)
commit_count = int(result.stdout.strip())
- apply_is_shallow = (
- _git_run(git_cmd, ["rev-parse", "--is-shallow-repository"]).stdout.strip() == "true")
+ apply_is_shallow = _is_shallow_checkout(git_cmd)
if commit_count > 0 and apply_is_shallow:
from hermes_cli.banner import _github_compare_behind
- head_sha = _git_run(git_cmd, ["rev-parse", "HEAD"]).stdout.strip()
- target_sha = _git_run(git_cmd, ["rev-parse", f"origin/{branch}"]).stdout.strip()
- counted = _github_compare_behind(head_sha, target_sha)
+ counted = _github_compare_behind(*_tip_shas(git_cmd, f"origin/{branch}"))
# counted == 0 means local-ahead: falls through to the up-to-date path.
commit_count = counted if counted is not None else -1
@@ -966,10 +906,8 @@ def _resolve_update_options(args, gateway_mode: bool) -> _UpdateOptions:
# Interactive terminals always stash-and-ask; only non-interactive updates consult
# updates.non_interactive_local_changes (auto-restore vs discard).
- _non_interactive_update = (
- gateway_mode or assume_yes or not (sys.stdin.isatty() and sys.stdout.isatty()))
discard_local_changes = False
- if _non_interactive_update:
+ if gateway_mode or assume_yes or not (sys.stdin.isatty() and sys.stdout.isatty()):
# 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()
@@ -994,9 +932,7 @@ def _begin_update_receipt_and_plan(args):
# nothing). Re-read AFTER the restart phase to reconcile — the plan is the worklist.
_pre_update_plan = None
with _best_effort('Update plan phase failed: %s'):
- from hermes_cli.update_inventory import (
- collect_runtime_inventory, record_plan_in_receipt)
-
+ from hermes_cli.update_inventory import collect_runtime_inventory, record_plan_in_receipt
_pre_update_plan = collect_runtime_inventory()
record_plan_in_receipt(_pre_update_plan)
if _pre_update_plan.runtimes:
@@ -1009,36 +945,27 @@ def _begin_update_receipt_and_plan(args):
# paused/restarted by the update instead; anything else still aborts.
if _m()._is_windows() and not getattr(args, "force", False):
scripts_dir = _m()._venv_scripts_dir()
- 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)
- if non_gateway:
- print(_format_concurrent_instances_message(non_gateway, scripts_dir))
- sys.exit(2)
+ concurrent = _m()._detect_concurrent_hermes_instances(scripts_dir) if scripts_dir is not None else []
+ non_gateway = _m()._filter_non_gateway_concurrent_instances(concurrent) if concurrent else []
+ if non_gateway:
+ print(_format_concurrent_instances_message(non_gateway, scripts_dir))
+ sys.exit(2)
return _pre_update_plan
def _prepare_git_command() -> tuple[bool, list, bool]:
"""Return ``(use_zip_update, git_cmd, is_fork)``; ``sys.exit(1)`` when not a git repo
on a non-Windows host (Windows falls back to ZIP: broken git file I/O, AV, NTFS filters)."""
- use_zip_update = False
git_dir = _m().PROJECT_ROOT / ".git"
+ use_zip_update = not git_dir.exists()
+ if use_zip_update and sys.platform != "win32":
+ print("✗ Not a git repository. Please reinstall:")
+ print(" curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash")
+ sys.exit(1)
- if not git_dir.exists():
- if sys.platform == "win32":
- use_zip_update = True
- else:
- print("✗ Not a git repository. Please reinstall:")
- 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).
- 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"])
+ git_cmd = _base_git_cmd()
+ if sys.platform == "win32" and 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)
@@ -1079,9 +1006,8 @@ def _verify_head_after_pull(
# HEAD must be on the target or "Code updated!" is a lie; an IN-PLACE update is the one
# legitimate exception (origin/<target> merged INTO the checked-out branch).
- post_pull_branch = _git_run(git_cmd, ["rev-parse", "--abbrev-ref", "HEAD"]).stdout.strip()
- if (
- not in_place_update and post_pull_branch and post_pull_branch not in {branch, "HEAD"}):
+ post_pull_branch = _current_branch_name(git_cmd)
+ if not in_place_update and post_pull_branch and post_pull_branch not in {branch, "HEAD"}:
print()
print(
f"✗ Update pulled origin/{branch}, but the checkout is on "
@@ -1094,6 +1020,11 @@ def _verify_head_after_pull(
return post_pull_sha
+def _current_branch_name(git_cmd, *, check: bool = False) -> str:
+ """``rev-parse --abbrev-ref HEAD`` (literal "HEAD" when detached)."""
+ return _git_run(git_cmd, ["rev-parse", "--abbrev-ref", "HEAD"], check=check).stdout.strip()
+
+
def _handle_update_called_process_error(
e, args, gateway_mode: bool, had_desktop_app_before_update: bool) -> None:
"""Git/installer failure: ZIP-fallback when safe, else report and ``sys.exit(1)``."""
@@ -1118,27 +1049,21 @@ def _handle_update_called_process_error(
print(
' venv\\Scripts\\python.exe -c '
'"from hermes_cli.main import main; main()" update --yes')
- with suppress(Exception):
- from hermes_cli.update_receipt import finalize_update_receipt
- finalize_update_receipt("failed")
+ _finalize_receipt("failed", 'Update receipt finalize failed: %s')
sys.exit(1)
+def _finalize_receipt(status: str, debug_message: str) -> None:
+ """Best-effort ``finalize_update_receipt(status)``; the receipt must never break an update."""
+ with _best_effort(debug_message):
+ from hermes_cli.update_receipt import finalize_update_receipt
+ finalize_update_receipt(status)
+
+
def _finish_already_up_to_date(
- git_cmd,
- branch: str,
- current_branch: str,
- _plan,
- *,
- assume_yes: bool,
- gateway_mode: bool,
- gw_input_fn,
- pre_update_snapshot_id,
- desktop_dir,
- had_desktop_app_before_update: bool,
- active_lazy_features,
- active_tool_dependencies,
- _windows_gateway_resume) -> None:
+ git_cmd, branch: str, current_branch: str, _plan, *, assume_yes: bool, gateway_mode: bool,
+ gw_input_fn, pre_update_snapshot_id, desktop_dir, had_desktop_app_before_update: bool,
+ active_lazy_features, active_tool_dependencies, _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)."""
_invalidate_update_cache()
@@ -1153,13 +1078,10 @@ def _finish_already_up_to_date(
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 "
- f"commit(s) kept on '{current_branch}'.")
+ f" ✓ Checkout was parked on '{current_branch}' — switched back to {branch}; "
+ f"{_count} unmerged commit(s) kept on '{current_branch}'.")
else:
- print(
- f" ✓ Checkout was parked on '{current_branch}' (fully "
- f"merged) — switched back to {branch}.")
+ print(f" ✓ Checkout was parked on '{current_branch}' (fully merged) — switched back to {branch}.")
elif current_branch not in {branch, "HEAD"}:
_git_run(git_cmd, ["checkout", current_branch])
@@ -1177,18 +1099,71 @@ def _finish_already_up_to_date(
if not current_checkout_complete:
if gateway_mode:
_write_gateway_update_exit_code(False)
- with _best_effort('Update receipt finalize (current checkout) failed: %s'):
- from hermes_cli.update_receipt import finalize_update_receipt
- finalize_update_receipt("partial")
+ _finalize_receipt("partial", 'Update receipt finalize (current checkout) failed: %s')
sys.exit(1)
+def _apply_pulled_update(
+ git_cmd, branch, pre_pull_sha, _plan, opts, *, gateway_mode, is_fork, desktop_dir,
+ had_desktop_app_before_update, pre_update_snapshot_id, _pre_update_plan,
+ _windows_gateway_resume) -> None:
+ """Post-pull phase: verify HEAD, sync Python/Node/web/Desktop, maintenance, fleet restart."""
+ _invalidate_update_cache()
+ post_pull_sha = _verify_head_after_pull(
+ 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
+ # current. Distinct from ``.update-incomplete`` (venv/install repair).
+ _write_fleet_restart_pending_marker(expected_sha=post_pull_sha or "")
+ # Stale .pyc would ImportError on gateway restart when new source references new names.
+ _sweep_bytecode_after_update(branch)
+
+ if is_fork and branch == "main":
+ _m()._sync_with_upstream_if_needed(
+ git_cmd, _m().PROJECT_ROOT, assume_yes=opts.assume_yes, input_fn=opts.gw_input_fn)
+
+ # .[all], falling back to base + extras individually so one broken extra doesn't strip
+ # the rest; the ownership preflight refuses first on foreign-owned (sudo-pip) venv files.
+ _sync_python_dependencies_after_pull(
+ git_cmd, branch, pre_pull_sha, active_lazy_features=opts.active_lazy_features,
+ active_tool_dependencies=opts.active_tool_dependencies,
+ _windows_gateway_resume=_windows_gateway_resume)
+
+ node_failures = _update_node_dependencies()
+ _m()._build_web_ui(_m().PROJECT_ROOT / "web")
+ desktop_build_ok = _rebuild_desktop_after_update(
+ desktop_dir, had_desktop_app_before_update=had_desktop_app_before_update)
+
+ print()
+ print(f"✓ Code updated!{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")
+
+ update_complete = _run_post_update_maintenance(
+ assume_yes=opts.assume_yes, gateway_mode=gateway_mode,
+ 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=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), so
+ # the marker would never land and the new gateway's watcher would time out spuriously.
+ if gateway_mode:
+ _write_gateway_update_exit_code(update_complete)
+
+ _restart = _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode)
+ _resume_windows_gateways_and_merge_outcome(_restart, _windows_gateway_resume, gateway_mode)
+ _verify_fleet_after_update(
+ _restart, _pre_update_plan=_pre_update_plan, _windows_gateway_resume=_windows_gateway_resume,
+ node_failures=node_failures, update_complete=update_complete)
+
+
def _cmd_update_impl(args, gateway_mode: bool):
- """Body of ``cmd_update`` — kept separate so the wrapper can always
- restore stdio even on ``sys.exit``."""
+ """Body of ``cmd_update`` — kept separate so the wrapper can always restore stdio even on
+ ``sys.exit``. Self-lock deferral deliberately does NOT run here (pre-fetch it stranded users
+ on the OLD checkout in an exit-2 loop); it runs right before the dependency sync."""
opts = _resolve_update_options(args, gateway_mode)
- active_lazy_features = opts.active_lazy_features
- active_tool_dependencies = opts.active_tool_dependencies
gw_input_fn, assume_yes = opts.gw_input_fn, opts.assume_yes
print("⚕ Updating Hermes Agent...")
@@ -1200,8 +1175,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
# the post-update cron-jobs safety net.
pre_update_snapshot_id = _m()._run_pre_update_backup(args)
_record_update_step(
- "pre_update_backup",
- pre_update_snapshot_id is not None,
+ "pre_update_backup", pre_update_snapshot_id is not None,
f"snapshot={pre_update_snapshot_id}" if pre_update_snapshot_id else "disabled or failed")
_windows_gateway_resume = _m()._pause_windows_gateways_for_update()
@@ -1215,10 +1189,6 @@ def _cmd_update_impl(args, gateway_mode: bool):
if _m()._is_windows() and not getattr(args, "force_venv", False):
_clear_windows_venv_holders_or_exit(args, gateway_mode, _windows_gateway_resume)
- # Self-lock deferral deliberately does NOT run here (pre-fetch it stranded users on the OLD
- # checkout and made every Windows update an exit-2 loop); it runs right before the
- # dependency sync via _abort_dependency_sync_if_self_locked().
-
# After every fail-closed venv guard, before either path can remove the release tree.
desktop_dir = _m().PROJECT_ROOT / "apps" / "desktop"
had_desktop_app_before_update = _desktop_app_present(desktop_dir)
@@ -1257,10 +1227,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
_print_fetch_failure(fetch_result.stderr)
sys.exit(1)
- # literal "HEAD" when detached
- result = _git_run(git_cmd, ["rev-parse", "--abbrev-ref", "HEAD"], check=True)
- current_branch = result.stdout.strip()
-
+ current_branch = _current_branch_name(git_cmd, check=True)
_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=opts.switch_branch,
@@ -1273,8 +1240,8 @@ def _cmd_update_impl(args, gateway_mode: bool):
gateway_mode=gateway_mode, gw_input_fn=gw_input_fn,
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,
+ active_lazy_features=opts.active_lazy_features,
+ active_tool_dependencies=opts.active_tool_dependencies,
_windows_gateway_resume=_windows_gateway_resume)
return
@@ -1289,61 +1256,12 @@ def _cmd_update_impl(args, gateway_mode: bool):
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=_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
- # current. Distinct from ``.update-incomplete`` (venv/install repair).
- _write_fleet_restart_pending_marker(expected_sha=post_pull_sha or "")
-
- # Stale .pyc would ImportError on gateway restart when new source references new names.
- _sweep_bytecode_after_update(branch)
-
- if is_fork and branch == "main":
- _m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
-
- # .[all], falling back to base + extras individually so one broken extra doesn't strip
- # the rest; the ownership preflight refuses first on foreign-owned (sudo-pip) venv files.
- _sync_python_dependencies_after_pull(
- git_cmd, branch, pre_pull_sha, active_lazy_features=active_lazy_features,
- active_tool_dependencies=active_tool_dependencies,
- _windows_gateway_resume=_windows_gateway_resume)
-
- node_failures = _update_node_dependencies()
- _m()._build_web_ui(_m().PROJECT_ROOT / "web")
-
- desktop_build_ok = _rebuild_desktop_after_update(
- desktop_dir, had_desktop_app_before_update=had_desktop_app_before_update)
-
- print()
- print(f"✓ Code updated!{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")
-
- update_complete = _run_post_update_maintenance(
- assume_yes=assume_yes, gateway_mode=gateway_mode,
- pre_update_snapshot_id=pre_update_snapshot_id,
+ _apply_pulled_update(
+ git_cmd, branch, pre_pull_sha, _plan, opts, gateway_mode=gateway_mode,
+ is_fork=is_fork, desktop_dir=desktop_dir,
had_desktop_app_before_update=had_desktop_app_before_update,
- node_failures=node_failures, desktop_build_ok=desktop_build_ok,
- 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), so
- # the marker would never land and the new gateway's watcher would time out spuriously.
- if gateway_mode:
- _write_gateway_update_exit_code(update_complete)
-
- _restart = _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode)
- _resume_windows_gateways_and_merge_outcome(_restart, _windows_gateway_resume, gateway_mode)
- _verify_fleet_after_update(
- _restart, _pre_update_plan=_pre_update_plan,
- _windows_gateway_resume=_windows_gateway_resume, node_failures=node_failures,
- update_complete=update_complete)
-
+ pre_update_snapshot_id=pre_update_snapshot_id, _pre_update_plan=_pre_update_plan,
+ _windows_gateway_resume=_windows_gateway_resume)
except _shim_quarantine_error_type() as e:
# Strict quarantine refused BEFORE any installer ran — defer via marker, exit 2, no ZIP.
_refuse_update_for_contended_shims(e)
diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.py
index ef8f8ad7126..de8dfc670ac 100644
--- a/tests/hermes_cli/test_update_self_lock.py
+++ b/tests/hermes_cli/test_update_self_lock.py
@@ -251,7 +251,7 @@ def test_pre_fetch_flow_has_no_self_lock_preflight():
assert "_m()._abort_dependency_sync_if_self_locked" not in pre_fetch
# ... and it must still guard the dependency sync after the code swap
# (the sync itself lives in _sync_python_dependencies_after_pull).
- post_fetch = src[fetch_idx:]
+ post_fetch = src[fetch_idx:] + inspect.getsource(update_cmd._apply_pulled_update)
assert "_sync_python_dependencies_after_pull(" in post_fetch
sync_src = inspect.getsource(update_cmd._sync_python_dependencies_after_pull)
assert "_m()._abort_dependency_sync_if_self_locked" in sync_src