Skip to content

The agent that grows with you

fix(update): make the git/ZIP swap a single crash-safe commit point

Teknium27f197d5ce57
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index 61b0aa0331a..4bf32f7a021 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -431,9 +431,116 @@ def _release_dead_index_lock(git_dir: Path) -> bool:
return True
-def restore_interrupted_pull(project_root: Path | None = None) -> bool:
+# The ZIP update's equivalent of the interrupted-pull marker: a journal in the install root naming
+# every entry the swap stages/renames and whether it existed before, plus an OS lock its owner holds
+# for the whole stage+swap (the kernel drops it with the owner: liveness without pids or ages).
+ZIP_SWAP_JOURNAL = ".hermes-update-zip-swap"
+_ZIP_STAGING_SUFFIX, _ZIP_OLD_SUFFIX = ".hermes-update-staging", ".hermes-update-old"
+
+
+def zip_swap_owner_lock(root: Path, *, wait: float = 0.0):
+ """Yields True while this process owns the ZIP swap lock, False when a live owner holds it."""
+ try:
+ fd = os.open(Path(root) / (ZIP_SWAP_JOURNAL + ".lock"), os.O_RDWR | os.O_CREAT, 0o644)
+ except OSError:
+ yield True # unwritable root: no swap can run there either
+ return
+ try:
+ deadline = time.monotonic() + wait
+ while not _lock_fd(fd, True):
+ if time.monotonic() >= deadline:
+ yield False
+ return
+ time.sleep(0.05)
+ try:
+ yield True
+ finally:
+ _lock_fd(fd, False)
+ finally:
+ os.close(fd)
+
+
+def write_zip_swap_journal(root: Path, phase: str, entries: list) -> None:
+ import json
+
+ journal = Path(root) / ZIP_SWAP_JOURNAL
+ tmp = journal.with_name(journal.name + ".tmp")
+ tmp.write_text(json.dumps({"pid": os.getpid(), "phase": phase, "entries": entries}), encoding="utf-8")
+ os.replace(tmp, journal)
+
+
+def _drop_path(path: Path) -> None:
+ if path.is_dir() and not path.is_symlink():
+ import shutil
+
+ shutil.rmtree(path)
+ elif path.exists() or path.is_symlink():
+ path.unlink()
+
+
+def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:
+ """Finish or roll back a ZIP swap whose owner died; True when the tree changed (relaunch).
+
+ ``committed``: every rename landed, only backups remain -> drop them (finish). ``swapping``: put
+ each moved-aside entry back and remove entries the swap added (roll back to the old tree, which
+ the venv was built for; ``hermes update`` redoes it). ``staging``: nothing live moved -> drop the
+ staging copies. Either way no ``*.hermes-update-staging``/``-old`` sibling is left to wedge the
+ next run's free-space or dirty-tree checks. A live owner (lock held) is never second-guessed.
+ """
+ root = _project_root() if project_root is None else Path(project_root)
+ journal = root / ZIP_SWAP_JOURNAL
+ if not journal.is_file() or _pytest_owns_live_checkout(root):
+ return False
+ with zip_swap_owner_lock(root) as owned:
+ if not owned or not journal.is_file():
+ return False
+ import json
+
+ try:
+ data = json.loads(journal.read_text(encoding="utf-8-sig"))
+ phase, entries = data["phase"], [(str(n), bool(e)) for n, e in data["entries"]]
+ except (OSError, ValueError, KeyError, TypeError):
+ phase, entries = "staging", [] # unreadable: never guess which live entry to move
+ changed = False
+ failed = False
+ for name, existed in reversed(entries):
+ if not name or "/" in name or "\\" in name or name in (".", ".."):
+ continue
+ dst = root / name
+ staging, old = Path(f"{dst}{_ZIP_STAGING_SUFFIX}"), Path(f"{dst}{_ZIP_OLD_SUFFIX}")
+ try:
+ if phase == "swapping":
+ if existed and old.exists():
+ _drop_path(dst)
+ os.rename(old, dst)
+ changed = True
+ elif not existed and dst.exists() and not staging.exists():
+ _drop_path(dst)
+ changed = True
+ elif existed and not dst.exists() and old.exists():
+ os.rename(old, dst) # the backup is the only copy left
+ changed = True
+ for leftover in (staging, old):
+ _drop_path(leftover)
+ except OSError as exc:
+ failed = True
+ print(f"⚠ Could not settle {name} after an interrupted ZIP update: {exc}", file=sys.stderr)
+ if failed:
+ return changed # the journal stays: the next launch retries
+ journal.unlink(missing_ok=True)
+ if changed:
+ print("⚠ A previous ZIP `hermes update` was interrupted mid-swap; the old install was put back. "
+ "`hermes update` updates it again.", file=sys.stderr)
+ return changed
+
+
+def restore_interrupted_pull(project_root: Path | None = None, *, after_failure: bool = False) -> bool:
"""Put back the files a killed ``hermes update`` had half-moved to the new commit.
+ ``after_failure``: the updater itself calls this when git exited non-zero mid-move (a locked or
+ read-only file): same restore, and the marker stays whenever the tree is not verified whole.
+
Returns True when the tree changed under this process: modules it already imported may be the
half-written ones, so the caller must relaunch (``relaunch_after_restore``).
@@ -451,6 +558,8 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:
"""
try:
root = _project_root() if project_root is None else project_root
+ if restore_interrupted_zip_swap(root):
+ return True
marker = interrupted_pull_marker(root)
if not marker.is_file() or _pytest_owns_live_checkout(root):
return False
@@ -461,14 +570,14 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:
return False
if not marker.is_file():
return True # another launch finished while this one started: rerun from its tree
- return _restore_holding_claim(root, marker)
+ return _restore_holding_claim(root, marker, after_failure=after_failure)
except (OSError, subprocess.SubprocessError, ValueError) as exc:
# Never block launch: the import that follows surfaces any real breakage.
print(f"⚠ Could not check for an interrupted `hermes update`: {exc}", file=sys.stderr)
return False
-def _restore_holding_claim(root: Path, marker: Path) -> bool:
+def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = False) -> bool:
global _merge_advice_shown
git_dir = marker.parent
fields = dict(line.partition("=")[::2] for line in marker.read_text(encoding="utf-8-sig").splitlines())
@@ -514,8 +623,9 @@ def _restore_holding_claim(root: Path, marker: Path) -> bool:
return False
restore, added, new_dirs = written
if restore or added:
- print("⚠ A previous `hermes update` was killed while git was writing the new code — "
- f"restoring the checkout to {pre[:10]}...", file=sys.stderr)
+ print(("⚠ git stopped partway through writing the new code — " if after_failure else
+ "⚠ A previous `hermes update` was killed while git was writing the new code — ")
+ + f"restoring the checkout to {pre[:10]}...", file=sys.stderr)
failed = _put_back_paths(git, root, restore, added)
if failed:
# No manual recipe: a reset would also wipe the edits this restore keeps, and the
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.py
index 38d104a2b3a..16db8baafec 100644
--- a/hermes_cli/_update_takeover.py
+++ b/hermes_cli/_update_takeover.py
@@ -24,8 +24,15 @@ def prepare(request: dict) -> tuple[Path, dict[str, str]]:
from pm.client import ensure_tools_for_sync, sync_venv, venv_is_current
from pm.environments import activation_environment, install_state_dir, runtime_facts_path
from hermes_cli._launchers import resolve_store_python
- from hermes_cli.venv_sync import collect_superseded_generations, publish_launchers
-
+ from hermes_cli.venv_sync import (
+ arm_completion, collect_superseded_generations, publish_launchers, refuse_foreign_owned_venv)
+
+ # The historical updater already moved the tree: owe the tail and the fleet restart before the
+ # first slow step, exactly like a current updater's commit point, so a kill from here on leaves
+ # both for the next launch / `hermes update` instead of nothing.
+ refuse_foreign_owned_venv(root)
+ arm_completion(root)
+ _arm_fleet_obligation(root)
correlation = request["update_id"]
with receipt.worker_context(correlation):
# A pre-PM installation has no required-tool facts. A current Python
@@ -53,6 +60,16 @@ def prepare(request: dict) -> tuple[Path, dict[str, str]]:
return python, activation_environment(root)
+def _arm_fleet_obligation(root: Path) -> None:
+ head = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, encoding="utf-8",
+ stdin=subprocess.DEVNULL, timeout=60)
+ sha = head.stdout.strip() if head.returncode == 0 else ""
+ if sha: # an SHA-less record names no code the fleet could be proven current on
+ from hermes_cli.update_cmd_fleet import _write_fleet_restart_pending_marker
+
+ _write_fleet_restart_pending_marker(expected_sha=sha)
+
+
def _record_failure(request: dict, result: Path, code: int, detail: str) -> None:
from hermes_cli import update_receipt
from hermes_constants import get_hermes_home
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index b0366857461..caf752d0854 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -6,7 +6,7 @@ main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at cal
"""
import logging
-from contextlib import contextmanager, nullcontext, suppress
+from contextlib import suppress
import os
import shlex
import shutil # noqa: F401 (tests patch update_cmd.shutil.*; split modules resolve it here)
@@ -29,7 +29,7 @@ from pm.receipt import accept_worker_receipt as _accept_completion_pm_receipt
from hermes_cli import update_receipt as _completion_receipt, update_cmd_config as _completion_config
from hermes_cli._old_updater import stop_for_relaunch
from hermes_cli._early_recovery import git_operation_in_progress, interrupted_pull_marker
-from hermes_cli import update_pause_record as _pause_record
+from hermes_cli import update_cmd_commit as _commit
from hermes_cli import update_cmd_check as _check
# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
@@ -99,7 +99,7 @@ from hermes_cli.update_cmd_git import ( # noqa: F401
_has_upstream_remote, _is_fork, _locate_real_git, _mark_skip_upstream_prompt,
_normalize_managed_eol, _park_detached_head, _portable_git_candidates, _print_fetch_failure,
_print_parked_branch_kept_notice, _print_parked_branch_skip_warning,
- _prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,
+ _prune_orphan_rescue_refs, _push_synced_fork, _should_skip_upstream_prompt, _sync_fork_with_upstream,
_sync_with_upstream_if_needed)
from hermes_cli.update_cmd_maint import ( # noqa: F401
_PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _clear_stale_sqlite_sidecars,
@@ -488,6 +488,9 @@ def _should_zip_fallback_on_update_error(exc: BaseException) -> bool:
isinstance(exc, subprocess.CalledProcessError)
and _m()._is_windows()
and _called_process_error_is_git(exc)
+ # Only from an untouched checkout: the ZIP overlay replaces every top-level entry, so
+ # after git already stashed, switched or half-moved the tree it would bury that state.
+ and _commit.run_checkout_untouched(_m().PROJECT_ROOT)
)
@@ -902,7 +905,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_r
sys.exit(1)
-def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=None, _windows_gateway_resume=None) -> None:
+def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=None) -> 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)."""
syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)
@@ -926,18 +929,23 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
else:
rollback_args = ["reset", "--hard", pre_pull_sha]
print(f"→ Rolling back to {rollback_branch if parked else pre_pull_sha[:10]}...")
- with _checkout_move(_windows_gateway_resume, pre_pull_sha):
+ with _best_effort('Could not write the interrupted-pull marker: %s'):
+ _commit.arm_tree_move(git_cmd, _m().PROJECT_ROOT, pre=_capture_head_sha(git_cmd, _m().PROJECT_ROOT),
+ target=pre_pull_sha, stash=None)
+ rollback_result = _git_run(git_cmd, rollback_args)
+ if rollback_result.returncode != 0 and parked:
+ # The parked branch can be unavailable (e.g. checked out in another worktree): restore
+ # its commit detached so the install still boots the code it ran before.
+ print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")
+ rollback_args = ["checkout", "--detach", pre_pull_sha]
rollback_result = _git_run(git_cmd, rollback_args)
- if rollback_result.returncode != 0 and parked:
- # The parked branch can be unavailable (e.g. checked out in another worktree): restore
- # its commit detached so the install still boots the code it ran before.
- print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")
- rollback_args = ["checkout", "--detach", pre_pull_sha]
- rollback_result = _git_run(git_cmd, rollback_args)
if rollback_result.returncode == 0:
+ interrupted_pull_marker(_m().PROJECT_ROOT).unlink(missing_ok=True)
+ _commit.disarm_commit_obligations() # back on the code this run started from
print(" ✓ Rollback complete — your install is unchanged.")
print(" Try ``hermes update`` again later once a fix lands.")
else:
+ _commit.settle_failed_tree_move(_m().PROJECT_ROOT)
print(" ✗ Rollback failed. Recover manually with:")
print(f" cd {_m().PROJECT_ROOT} && git {shlex.join(rollback_args)}")
if rollback_result.stderr.strip():
@@ -961,111 +969,10 @@ def _update_movement_baseline(git_cmd, pre_pull_sha, pre_sync_sha, rollback_bran
return pre_sync_sha or pre_pull_sha
-def _resolved_commit(git_cmd, ref: str) -> str:
- """The commit *ref* names now, or ``""`` when it names none."""
- return (_git_run(git_cmd, ["rev-parse", "-q", "--verify", f"{ref}^{{commit}}"]).stdout or "").strip()
-
-
-@contextmanager
-def _checkout_move(token, *targets, paths=(), revert=False):
- """Run one checkout-writing git step (switch, merge, reset, upstream sync, rollback, stash) with
- the paused gateways' tree gate bound to it BEFORE git writes a file: the commit(s) it can move
- to and the tracked *paths* it rewrites in place (stash push/apply, ``reset --hard``,
- ``checkout -- <paths>``; *revert*: every tracked change it finds, put back to HEAD), on a
- baseline taken at the HEAD it starts from. Without that, a step
- git leaves half-written at an unmoved HEAD is judged against whatever refs a later fetch left,
- or against no baseline at all once an earlier step moved HEAD. A failed record write raises:
- the step must not run.
-
- The first step from the pause's own HEAD extends the pause's baseline (it knows the edits that
- were already there). A later step gets a baseline of its own, retired once git returns with the
- tree whole: HEAD moved and every file the move wrote holds the new commit, the tree exactly as
- the step found it, or the step reported ``whole`` on the dict this yields (a stash restore that
- applied cleanly changes the tree by design). A move is judged the moment git returns (see
- ``_settle_checkout_move``)."""
- step: dict = {}
- targets = sorted({t for t in targets if t})
- pause_id = (token or {}).get("pause_id")
- root = _pause_record.install_root() if pause_id and (targets or paths or revert) else None
- found = _pause_record.tree_state(root) if root else None
- if found is None: # nothing paused, nothing bound, or not a git checkout: no tree gate to bind
- yield step
- return
- paths = {*paths, *(found["dirty_at_pause"] or [] if revert else ())}
- baselines = token.setdefault("baselines", [])
- move_id = f"{pause_id}@{found['pre_sha']}"
- baseline = next((b for b in baselines if b.get("pre_sha") == found["pre_sha"]
- and b.get("pause_id") in (pause_id, move_id)), None)
- if baseline is None:
- baseline = {"pause_id": move_id, **found}
- baselines.append(baseline)
- for key, bound in (("move_targets", targets), ("move_paths", paths)):
- if bound:
- baseline[key] = sorted({*baseline.get(key, []), *bound})
- _pause_record.write({**token, "resume_needed": True})
- try:
- yield step
- finally:
- _settle_checkout_move(token, baseline, found, root, step)
-
-
-def _moves_for(token):
- """``_checkout_move`` bound to *token*: the ``checkout_move`` the git and stash helpers take."""
- return lambda *targets, **bound: _checkout_move(token, *targets, **bound)
-
-
-def _settle_checkout_move(token: dict, baseline: dict, found: dict, root, step: dict) -> None:
- """Record what the returned step left. A moved HEAD gets its verdict now: git can move HEAD
- past a file it failed to write, and only now are the move's paths untouched by later steps
- (dependency syncs, stash restores). A step's own baseline is retired when the tree is whole."""
- now = _pause_record.tree_state(root)
- moved = now["pre_sha"] != found["pre_sha"]
- torn = _pause_record.torn_by_move(root, found, now["dirty_at_pause"]) if moved else None
- if moved and torn is not None: # unknown stays unjudged: the gate judges it at resume time
- baseline.setdefault("landed", {})[now["pre_sha"]] = torn
- whole = torn == [] if moved else step.get("whole") or all(now[key] == found[key] for key in found)
- if baseline["pause_id"] != token["pause_id"] and whole:
- token["baselines"] = [b for b in token["baselines"] if b is not baseline]
- _pause_record.write({**token, "resume_needed": True})
-
-
-def _move_checkout_to(git_cmd, branch, merge_ref, pre_pull_sha) -> None:
- """The principal pull's one checkout move onto *merge_ref*; exits when it cannot be made."""
- # 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.
- if merge_ref != f"origin/{branch}":
- # Keep detached local commits reachable, too. Named branches are
- # untouched by checkout --detach; an autostash protects dirty files.
- _park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)
- _git_run(git_cmd, ["checkout", "--detach", merge_ref], check=True)
- else:
- merge_result = _git_run(git_cmd, ["merge", "--ff-only", merge_ref])
- if merge_result.returncode != 0:
- ancestry = _git_run(
- git_cmd, ["merge-base", "--is-ancestor", "HEAD", merge_ref])
- if ancestry.returncode == 1:
- _reconcile_diverged_checkout(
- git_cmd, branch, pre_pull_sha, target_ref=merge_ref)
- else:
- print("✗ Fast-forward failed; refusing to reset because history divergence was not proven.")
- detail = (merge_result.stderr or merge_result.stdout or "").strip()
- if detail:
- print(f" {detail}")
- if ancestry.returncode == 0:
- print(f" HEAD is still an ancestor of {merge_ref}.")
- else:
- print(f" Could not verify whether HEAD is an ancestor of {merge_ref}.")
- ancestry_detail = (ancestry.stderr or ancestry.stdout or "").strip()
- if ancestry_detail:
- print(f" {ancestry_detail}")
- print(" Resolve the Git error and re-run `hermes update`; no reset was attempted.")
- sys.exit(1)
-
-
def _pull_updates(
git_cmd, branch, auto_stash_ref, *, prompt_for_restore, gw_input_fn, discard_local_changes,
keep_stash, target_ref=None, pre_sync_sha=None, rollback_branch=None, sync_upstream=False, assume_yes=False,
- in_place_update=False, _windows_gateway_resume=None):
+ in_place_update=False, _windows_gateway_resume=None, expected_sha=None):
"""Fast-forward onto ``origin/<branch>`` and settle the autostash. Divergence by shape:
custom branch -> merge, same branch -> rescue ref then reset; a
post-pull syntax error in a critical file rolls back. Exits on failure; returns the SHA HEAD had to move off."""
@@ -1082,21 +989,57 @@ def _pull_updates(
target_sha = (_git_run(git_cmd, ["rev-parse", f"{merge_ref}^{{commit}}"]).stdout or "").strip()
movement_baseline = _update_movement_baseline(
git_cmd, pre_pull_sha, pre_sync_sha, rollback_branch, target_sha)
+ if expected_sha and target_sha and target_sha != expected_sha:
+ # Channel verification is a precondition: refuse before anything moves.
+ print(f"✗ {merge_ref} resolves to {target_sha[:10]}, not the selected channel commit "
+ f"{expected_sha[:10]}. No update was applied.")
+ sys.exit(1)
+ # The commit point: the tail and the fleet restart are owed BEFORE git writes a file.
+ _commit.arm_commit_obligations(_m().PROJECT_ROOT, target_sha)
with _best_effort('Could not write the interrupted-pull marker: %s'):
- pull_marker.write_text(
- f"pid={os.getpid()}\npre={pre_pull_sha}\ntarget={target_sha}\nstash={auto_stash_ref or ''}\n",
- encoding="utf-8")
+ _commit.arm_tree_move(git_cmd, _m().PROJECT_ROOT, pre=pre_pull_sha, target=target_sha,
+ stash=auto_stash_ref)
try:
try:
- # The paused gateways' tree gate must know this move's target before git writes a file.
- with _checkout_move(_windows_gateway_resume, target_sha):
- _move_checkout_to(git_cmd, branch, merge_ref, pre_pull_sha)
+ # 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.
+ if merge_ref != f"origin/{branch}":
+ # Keep detached local commits reachable, too. Named branches are
+ # untouched by checkout --detach; an autostash protects dirty files.
+ _park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)
+ _git_run(git_cmd, ["checkout", "--detach", merge_ref], check=True)
+ else:
+ merge_result = _git_run(git_cmd, ["merge", "--ff-only", merge_ref])
+ if merge_result.returncode != 0:
+ ancestry = _git_run(
+ git_cmd, ["merge-base", "--is-ancestor", "HEAD", merge_ref])
+ if ancestry.returncode == 1:
+ _reconcile_diverged_checkout(
+ git_cmd, branch, pre_pull_sha, target_ref=merge_ref)
+ else:
+ print("✗ Fast-forward failed; refusing to reset because history divergence was not proven.")
+ detail = (merge_result.stderr or merge_result.stdout or "").strip()
+ if detail:
+ print(f" {detail}")
+ if ancestry.returncode == 0:
+ print(f" HEAD is still an ancestor of {merge_ref}.")
+ else:
+ print(f" Could not verify whether HEAD is an ancestor of {merge_ref}.")
+ ancestry_detail = (ancestry.stderr or ancestry.stdout or "").strip()
+ if ancestry_detail:
+ print(f" {ancestry_detail}")
+ print(" Resolve the Git error and re-run `hermes update`; no reset was attempted.")
+ sys.exit(1)
except KeyboardInterrupt:
raise # Ctrl-C reached git too (same process group): the tree may be torn, keep the marker
except BaseException:
- pull_marker.unlink(missing_ok=True) # git exited on its own (sys.exit on conflict/reset failure)
+ # git exited on its own (sys.exit on conflict/reset failure, a locked or read-only file):
+ # put back what it wrote; the marker stays until the tree is verified whole.
+ if (_commit.settle_failed_tree_move(_m().PROJECT_ROOT)
+ and _capture_head_sha(git_cmd, _m().PROJECT_ROOT) == (pre_sync_sha or pre_pull_sha)):
+ _commit.disarm_commit_obligations()
raise
- pull_marker.unlink(missing_ok=True) # git is done: the tree is whole again
+ pull_marker.unlink(missing_ok=True) # git exited 0: the tree is whole at the target
if sync_upstream:
# Do not let a second mutation hide a failed origin merge or move an
# unexpected branch. Keep local edits parked through the final check.
@@ -1104,15 +1047,16 @@ def _pull_updates(
git_cmd, branch, movement_baseline, in_place_update=in_place_update,
_windows_gateway_resume=_windows_gateway_resume)
_m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn,
- checkout_move=_moves_for(_windows_gateway_resume))
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
# Refuse an unexpected branch before syntax rollback can reset its ref.
_verify_head_after_pull(
git_cmd, branch, movement_baseline, in_place_update=in_place_update,
_windows_gateway_resume=_windows_gateway_resume)
_rollback_if_pulled_syntax_error(
- git_cmd, pre_sync_sha or pre_pull_sha, rollback_branch=rollback_branch,
- _windows_gateway_resume=_windows_gateway_resume)
+ git_cmd, pre_sync_sha or pre_pull_sha, rollback_branch=rollback_branch)
+ if sync_upstream:
+ # Only a validated update is published to the fork (#97052 sync, after the commit point).
+ _push_synced_fork(git_cmd, _m().PROJECT_ROOT)
update_succeeded = True
finally:
if auto_stash_ref is not None:
@@ -1130,10 +1074,59 @@ def _pull_updates(
else:
_m()._restore_stashed_changes(
git_cmd, _m().PROJECT_ROOT, auto_stash_ref, prompt_user=prompt_for_restore,
- input_fn=gw_input_fn, checkout_move=_moves_for(_windows_gateway_resume))
+ input_fn=gw_input_fn)
return movement_baseline
+def _switch_branch_at_commit_point(git_cmd, branch, target_ref, *, pre, stash):
+ """CP0: switch the parked checkout to *branch* under the interrupted-pull marker and the armed
+ obligations, so a kill mid-switch is restored by the next launch like a killed pull."""
+ root = _m().PROJECT_ROOT
+
+ def resolve(ref):
+ return (_git_run(git_cmd, ["rev-parse", "-q", "--verify", f"{ref}^{{commit}}"]).stdout or "").strip()
+
+ attempts = [(["checkout", branch], resolve(branch)),
+ (["checkout", "-B", branch, f"origin/{branch}"], resolve(f"origin/{branch}"))]
+ result = None
+ for args, target in attempts:
+ if not target:
+ result = _git_run(git_cmd, args) # unresolvable: git fails before touching the tree
+ if result.returncode == 0:
+ interrupted_pull_marker(root).unlink(missing_ok=True)
+ return result
+ continue
+ _commit.arm_commit_obligations(root, resolve(target_ref) or target)
+ with _best_effort('Could not write the interrupted-pull marker: %s'):
+ _commit.arm_tree_move(git_cmd, root, pre=pre, target=target, stash=stash)
+ try:
+ result = _git_run(git_cmd, args)
+ except KeyboardInterrupt:
+ raise
+ except BaseException:
+ _commit.settle_failed_tree_move(root)
+ raise
+ if result.returncode == 0:
+ interrupted_pull_marker(root).unlink(missing_ok=True) # git exited 0: whole at *target*
+ return result
+ if not _commit.settle_failed_tree_move(root):
+ return result # torn and unrestorable now: the marker stays for the next launch
+ if _capture_head_sha(git_cmd, root) == pre:
+ _commit.disarm_commit_obligations()
+ return result
+
+
+def _refuse_before_commit_point(git_cmd, target_ref, _windows_gateway_resume) -> None:
+ """Preconditions that used to fail AFTER the swap: refuse with the install untouched."""
+ reason = _commit.preflight_refusal(git_cmd, _m().PROJECT_ROOT, target_ref, _UPDATE_CRITICAL_FILES)
+ if reason is None:
+ return
+ print(reason)
+ print(" No update was applied; your install is unchanged.")
+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
+ sys.exit(1)
+
+
@dataclass
class _CheckoutPlan:
"""What the pre-pull checkout phase decided (see ``_prepare_checkout_for_update``)."""
@@ -1217,8 +1210,7 @@ def _prepare_checkout_for_update(
print(f" ⚠ Currently on detached HEAD — switching to {branch} for update...")
# Before the stash: its refs/stash would contain HEAD until it is dropped.
_park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)
- auto_stash_ref = _m()._stash_local_changes_if_needed(
- git_cmd, _m().PROJECT_ROOT, checkout_move=_moves_for(_windows_gateway_resume))
+ auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)
moved_from_sha = None
rollback_branch = None
if not release_tag and not in_place_update and current_branch != branch:
@@ -1226,18 +1218,13 @@ def _prepare_checkout_for_update(
# Keep the running code AND its branch identity for syntax rollback.
moved_from_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
rollback_branch = current_branch
- # The switch (or its -B fallback) is this update's first tree write: bind both commits first.
- with _checkout_move(_windows_gateway_resume, *(_resolved_commit(git_cmd, ref) for ref in (
- f"refs/heads/{branch}", f"origin/{branch}"))):
- track_result = _git_run(git_cmd, ["checkout", branch])
- if track_result.returncode != 0:
- track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])
+ track_result = _switch_branch_at_commit_point(
+ git_cmd, branch, target_ref, pre=moved_from_sha, stash=auto_stash_ref)
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,
- checkout_move=_moves_for(_windows_gateway_resume))
+ 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]}")
@@ -1292,8 +1279,7 @@ def _prepare_checkout_for_update(
if commit_count == 0 and is_fork and branch == "main" and not release_tag:
pre_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
upstream_checked = _m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn,
- checkout_move=_moves_for(_windows_gateway_resume))
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
post_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
if pre_sync_sha and post_sync_sha and pre_sync_sha != post_sync_sha:
synced_count = _count_commits_between(
@@ -1398,10 +1384,9 @@ def _record_update_initiator() -> None:
_completion_receipt.record_fact("initiator", "desktop")
-def _prepare_git_command(*, checkout_move=None) -> tuple[bool, list, bool]:
+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).
- *checkout_move* binds the churn cleanups' file writes to the paused gateways' tree gate."""
+ on a non-Windows host (Windows falls back to ZIP: broken git file I/O, AV, NTFS filters)."""
git_dir = _m().PROJECT_ROOT / ".git"
use_zip_update = not git_dir.exists()
if use_zip_update and sys.platform != "win32":
@@ -1426,8 +1411,8 @@ def _prepare_git_command(*, checkout_move=None) -> tuple[bool, list, bool]:
# Before stash/branch logic: npm rewrites package-lock.json non-deterministically and
# line-ending churn is machine-made dirt; both would otherwise force an autostash every update.
- _discard_lockfile_churn(git_cmd, _m().PROJECT_ROOT, checkout_move=checkout_move)
- _normalize_managed_eol(git_cmd, _m().PROJECT_ROOT, checkout_move=checkout_move)
+ _discard_lockfile_churn(git_cmd, _m().PROJECT_ROOT)
+ _normalize_managed_eol(git_cmd, _m().PROJECT_ROOT)
origin_url = _m()._get_origin_url(git_cmd, _m().PROJECT_ROOT)
is_fork = _is_fork(origin_url)
@@ -1530,17 +1515,15 @@ def _finalize_receipt(status: str, debug_message: str) -> None:
def _finish_already_up_to_date(
- git_cmd, branch: str, current_branch: str, _plan, *, gw_input_fn, completion_request: dict,
- _windows_gateway_resume=None) -> None:
- """"Already up to date" path: restore stash, repair the checkout, catch up the fleet.
+ git_cmd, branch: str, current_branch: str, _plan, *, gw_input_fn, completion_request: dict) -> 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)."""
- # A parked branch the update switched off stays on the target: re-parking on the stale branch
- # recreates the incident. No other checkout left current_branch (in-place and release updates
- # never switch), so there is nothing to switch back to.
+ # 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 _plan.auto_stash_ref is not None:
_m()._restore_stashed_changes(
git_cmd, _m().PROJECT_ROOT, _plan.auto_stash_ref, prompt_user=_plan.prompt_for_restore,
- input_fn=gw_input_fn, checkout_move=_moves_for(_windows_gateway_resume))
+ input_fn=gw_input_fn)
if _plan.parked_branch_switched:
if _plan.switch_block_reason.startswith("unmerged:"):
_count = _plan.switch_block_reason.split(":", 1)[1]
@@ -1549,6 +1532,8 @@ def _finish_already_up_to_date(
f"{_count} unmerged commit(s) kept on '{current_branch}'.")
else:
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])
if completion_request is not None:
# Same code, same host obligation: an SHA-less arm would REPLACE the standing record
@@ -1622,7 +1607,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
or _m()._desktop_dist_exists(desktop_dir)
or bool(_m()._installed_desktop_apps()))
- use_zip_update, git_cmd, is_fork = _prepare_git_command(checkout_move=_moves_for(_windows_gateway_resume))
+ use_zip_update, git_cmd, is_fork = _prepare_git_command()
completion_request = _source_completion_request(
opts, _pre_update_plan, pre_update_snapshot_id, _windows_gateway_resume,
@@ -1732,6 +1717,8 @@ def _cmd_update_impl(args, gateway_mode: bool):
sys.exit(1)
current_branch = _current_branch_name(git_cmd, check=True)
+ _commit.record_run_start(git_cmd, _m().PROJECT_ROOT)
+ _refuse_before_commit_point(git_cmd, target_ref, _windows_gateway_resume)
_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,
@@ -1741,7 +1728,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
if commit_count == 0:
_finish_already_up_to_date(
git_cmd, branch, current_branch, _plan, gw_input_fn=gw_input_fn,
- completion_request=completion_request, _windows_gateway_resume=_windows_gateway_resume)
+ completion_request=completion_request)
return
if release_sha:
@@ -1761,7 +1748,8 @@ def _cmd_update_impl(args, gateway_mode: bool):
keep_stash=opts.keep_stash, target_ref=target_ref, pre_sync_sha=_plan.pre_sync_sha,
rollback_branch=_plan.rollback_branch,
sync_upstream=is_fork and branch == "main" and not release_sha, assume_yes=assume_yes,
- in_place_update=_plan.in_place_update, _windows_gateway_resume=_windows_gateway_resume)
+ in_place_update=_plan.in_place_update, _windows_gateway_resume=_windows_gateway_resume,
+ expected_sha=completion_request.get("expected_sha"))
_apply_pulled_update(
git_cmd, branch, movement_baseline, _plan,
_windows_gateway_resume=_windows_gateway_resume, completion_request=completion_request)
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
new file mode 100644
index 00000000000..33d14cfe9c2
--- /dev/null
+++ b/hermes_cli/update_cmd_commit.py
@@ -0,0 +1,190 @@
+"""The single commit point of a source ``hermes update``: everything the tree move needs armed first.
+
+Before git (or the ZIP swap) writes the first file of the new code, three things are durable:
+
+* the interrupted-pull marker (``.git/hermes-update-pull``) naming the commit git moves to, for EVERY
+ tree move (branch switch, upstream fork pull, the pull itself) so a launch after any exit that left
+ a torn tree puts the old one back (``_early_recovery.restore_interrupted_pull``);
+* the source-completion tail (``venv_sync.arm_completion``) and the host fleet-restart obligation,
+ so a kill after the move but before the completion child starts still leaves the tail owed to the
+ next launch (``venv_sync.prepare_launch``) and the restart owed to the next ``hermes update``.
+
+Failures before the move are no-ops: ``disarm_commit_obligations`` puts both obligations back the way
+this run found them once the tree is verified at its pre-update commit again.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Optional
+
+from hermes_cli._early_recovery import interrupted_pull_marker, restore_interrupted_pull
+
+# What this run found before it armed anything: {path: bytes or None}. None = nothing armed yet.
+_armed_snapshot: Optional[dict[Path, Optional[bytes]]] = None
+# (git_cmd, (HEAD, branch)) when this run reached its checkout phase.
+_run_start: Optional[tuple[list, tuple[str, str]]] = None
+
+
+def _owns_live_checkout(root: Path) -> bool:
+ from hermes_cli.update_cmd import _m
+
+ return _m()._pytest_owns_live_checkout(root)
+
+
+def _obligation_paths(root: Path) -> list[Path]:
+ from hermes_cli.update_cmd_fleet import _fleet_restart_pending_marker_path
+ from hermes_cli.update_host_obligation import host_obligation_path
+ from hermes_cli.venv_sync import completion_pending_path
+
+ paths = [completion_pending_path(root), _fleet_restart_pending_marker_path()]
+ host = host_obligation_path()
+ if host is not None:
+ paths.append(host)
+ return paths
+
+
+def arm_commit_obligations(root: Path, expected_sha: str) -> None:
+ """Owe the completion tail and the fleet restart for ``expected_sha`` BEFORE the tree moves.
+
+ Idempotent within a run (the first call snapshots what to restore on a no-op failure). An
+ unwritable install state raises: nothing has moved yet, and moving without the obligation is
+ exactly the tail-never-runs state this exists to prevent.
+ """
+ global _armed_snapshot
+ from hermes_cli.update_cmd_fleet import _write_fleet_restart_pending_marker
+ from hermes_cli.venv_sync import arm_completion
+
+ root = Path(root)
+ if _owns_live_checkout(root):
+ return
+ if _armed_snapshot is None:
+ snapshot: dict[Path, Optional[bytes]] = {}
+ for path in _obligation_paths(root):
+ try:
+ snapshot[path] = path.read_bytes()
+ except OSError:
+ snapshot[path] = None
+ _armed_snapshot = snapshot
+ arm_completion(root)
+ _write_fleet_restart_pending_marker(expected_sha=expected_sha or "")
+
+
+def disarm_commit_obligations() -> None:
+ """Restore both obligations to what this run found: the tree never left its pre-update commit."""
+ global _armed_snapshot
+ snapshot, _armed_snapshot = _armed_snapshot, None
+ for path, data in (snapshot or {}).items():
+ try:
+ if data is None:
+ path.unlink(missing_ok=True)
+ else:
+ path.write_bytes(data)
+ except OSError:
+ pass # an owed tail/restart left armed is a retry, never a lost obligation
+
+
+def commit_obligations_armed() -> bool:
+ return _armed_snapshot is not None
+
+
+def arm_tree_move(git_cmd, root: Path, *, pre: str | None, target: str, stash: str | None) -> Path:
+ """Write the interrupted-pull marker for one git tree move (pre -> target)."""
+ marker = interrupted_pull_marker(root)
+ marker.write_text(f"pid={os.getpid()}\npre={pre or ''}\ntarget={target}\nstash={stash or ''}\n",
+ encoding="utf-8")
+ return marker
+
+
+def settle_failed_tree_move(root: Path) -> bool:
+ """Git exited without finishing a tree move: put back what it wrote, keep the marker if we can't.
+
+ True when the tree is verified whole again (at the pre-move commit, or at the target when git got
+ there anyway); False leaves the marker for the next launch's ``restore_interrupted_pull``.
+ """
+ restore_interrupted_pull(Path(root), after_failure=True)
+ return not interrupted_pull_marker(Path(root)).is_file()
+
+
+def target_syntax_error(git_cmd, root: Path, target_ref: str, relpaths) -> tuple[str, str] | None:
+ """``(path, error)`` for the first startup-critical file that does not compile at ``target_ref``.
+
+ Read from the object store, never written to the tree: this runs BEFORE HEAD moves, so a broken
+ release is refused with the install untouched (the post-pull rollback stays as the backstop).
+ """
+ for rel in relpaths:
+ shown = subprocess.run([*git_cmd, "show", f"{target_ref}:{rel}"], cwd=str(root), capture_output=True,
+ stdin=subprocess.DEVNULL, timeout=120)
+ if shown.returncode != 0:
+ continue # absent at the target (or unreadable): the post-pull guard has the last word
+ try:
+ compile(shown.stdout, rel, "exec", dont_inherit=True)
+ except (SyntaxError, ValueError) as exc:
+ return rel, f"{type(exc).__name__}: {exc}"
+ return None
+
+
+def head_and_branch(git_cmd, root: Path) -> tuple[str, str]:
+ def out(*args: str) -> str:
+ cp = subprocess.run([*git_cmd, *args], cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace",
+ stdin=subprocess.DEVNULL, timeout=60)
+ return cp.stdout.strip() if cp.returncode == 0 else ""
+
+ return out("rev-parse", "HEAD"), out("rev-parse", "--abbrev-ref", "HEAD")
+
+
+def checkout_untouched(git_cmd, root: Path, start: tuple[str, str] | None) -> bool:
+ """True when the checkout is exactly where this run found it: same HEAD, same branch, no
+ autostash taken, no tree move armed. Only then may a failed git update fall back to ZIP."""
+ from hermes_cli.update_cmd_stash import _unrestored_autostash_notice
+
+ if start is None or not start[0]:
+ return False
+ if _unrestored_autostash_notice() is not None or interrupted_pull_marker(root).is_file():
+ return False
+ return head_and_branch(git_cmd, root) == start
+
+
+def record_run_start(git_cmd, root: Path) -> None:
+ global _run_start
+ _run_start = (list(git_cmd), head_and_branch(git_cmd, root))
+
+
+def run_checkout_untouched(root: Path) -> bool:
+ """``checkout_untouched`` for this run; True before the checkout phase (nothing can have moved)."""
+ if _run_start is None:
+ return True
+ return checkout_untouched(_run_start[0], Path(root), _run_start[1])
+
+
+def preflight_refusal(git_cmd, root: Path, target_ref: str, critical_files) -> str | None:
+ """Why this update must not start, checked BEFORE the first tree move; ``None`` to proceed.
+
+ * a venv owned by another OS user (the completion child used to refuse only after the swap);
+ * a target whose startup-critical modules do not compile (rollback used to be the only guard).
+ """
+ root = Path(root)
+ if not _owns_live_checkout(root):
+ try:
+ from hermes_cli.venv_sync import refuse_foreign_owned_venv
+
+ refuse_foreign_owned_venv(root)
+ except ImportError:
+ pass
+ except Exception as exc: # pm's refusal carries its own remediation text
+ return f"✗ {exc}"
+ broken = target_syntax_error(git_cmd, root, target_ref, critical_files)
+ if broken is not None:
+ path, error = broken
+ return (f"✗ The update target has a syntax error in a critical file:\n {path}\n "
+ + "\n ".join(error.splitlines()[:6]))
+ return None
+
+
+def reset_for_tests() -> None:
+ global _armed_snapshot, _run_start
+ _armed_snapshot = None
+ _run_start = None
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index be48874309a..c8b75427eb0 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -408,6 +408,15 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
print(" ✓ Fork is up to date with upstream")
return True
print(f"\n→ Fork is {upstream_ahead} commit(s) behind upstream\n→ Pulling from upstream...")
+ # A tree move like the pull itself: the marker and the owed tail are armed before git writes,
+ # and the just-fetched ref is merged (a second `git pull` fetch could move past the marker's target).
+ from hermes_cli import update_cmd_commit as _commit
+ from hermes_cli._early_recovery import interrupted_pull_marker
+ pre = _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd)
+ target = _git_stdout(git_cmd, ["rev-parse", "upstream/main^{commit}"], cwd) or ""
+ _commit.arm_commit_obligations(cwd, target)
+ with suppress(OSError):
+ _commit.arm_tree_move(git_cmd, cwd, pre=pre, target=target, stash=None)
try:
# The fetch above already brought upstream/main: a local fast-forward (no network, so no
# credential helper is started under the checkout lock fd a mutator inherits) to the
@@ -415,9 +424,30 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
with (checkout_move or _no_move)(upstream):
run_git(git_cmd, ["merge", "--ff-only", upstream], cwd=cwd, check=True, **_no_prompt_git_kwargs())
except subprocess.CalledProcessError:
+ if _commit.settle_failed_tree_move(cwd) and _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd) == pre:
+ _commit.disarm_commit_obligations()
print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")
return False
- print(" ✓ Updated from upstream\n→ Syncing fork...")
+ interrupted_pull_marker(cwd).unlink(missing_ok=True)
+ print(" ✓ Updated from upstream")
+ # The fork push waits for a validated update: ``_push_synced_fork`` after the syntax guard.
+ return True
+
+
+def _push_synced_fork(git_cmd: list[str], cwd: Path) -> None:
+ """Publish an upstream sync to the fork's main once the update is validated.
+
+ Pushes only when local HEAD is upstream/main and strictly ahead of origin/main, i.e. this run
+ (or an earlier one whose push failed) fast-forwarded main from upstream.
+ """
+ head = _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd)
+ upstream = _git_stdout(git_cmd, ["rev-parse", "-q", "--verify", "upstream/main^{commit}"], cwd)
+ origin = _git_stdout(git_cmd, ["rev-parse", "-q", "--verify", "origin/main^{commit}"], cwd)
+ if not head or head != upstream or head == origin:
+ return
+ if origin and not _git_ok(git_cmd, ["merge-base", "--is-ancestor", origin, head], cwd):
+ return
+ print("→ Syncing fork...")
if _sync_fork_with_upstream(git_cmd, cwd):
print(" ✓ Fork synced with upstream")
else:
@@ -425,7 +455,6 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
" ℹ Got updates from upstream but couldn't push to fork (no write access?)\n"
" Your local repo is updated, but your fork on GitHub may be behind."
)
- return True
def _has_http_code(stderr: str, *codes: str) -> bool:
diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.py
index c64d6f72693..f9b071496d7 100644
--- a/hermes_cli/update_cmd_zip.py
+++ b/hermes_cli/update_cmd_zip.py
@@ -14,10 +14,18 @@ import sys
from pathlib import Path
from typing import Collection, Optional
+from hermes_cli._early_recovery import (
+ ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap, write_zip_swap_journal, zip_swap_owner_lock)
+
# Log-record parity with the origin module.
logger = logging.getLogger("hermes_cli.update_cmd")
_ZIP_STAGING_ARTIFACT_SUFFIXES = ".hermes-update-staging", ".hermes-update-old"
+# Hermes' own root breadcrumbs: the swap journal + its owner lock, and the update/refresh markers.
+# They are never user work, so the dirty-tree guard must not refuse (and wedge) on them.
+_ZIP_HERMES_ROOT_ARTIFACTS = frozenset({
+ ".hermes-update-zip-swap", ".hermes-update-zip-swap.lock", ".hermes-update-zip-swap.tmp",
+ ".update-incomplete", ".lazy-refresh-incomplete"})
# Single source of truth for entries the ZIP swap preserves — used by the dirty-tree filter and the swap loop.
_ZIP_PRESERVED_TOP_LEVEL = {"venv", ".venv", "node_modules", ".git", ".env"}
@@ -89,7 +97,7 @@ def _discard_staged(staged) -> None:
logger.warning("could not remove staging path %s: %s", staging, exc)
-def _commit_staged_replacements(staged) -> None:
+def _commit_staged_replacements(staged, *, on_committed=None) -> None:
"""Phase 2: swap every staged entry into place, rolling back all on failure.
Per-entry safety wasn't enough: a partway failure over ~90 entries left a mixed-version tree (every
@@ -121,6 +129,8 @@ def _commit_staged_replacements(staged) -> None:
# Keep restoring the rest; a silent failure here turns a recoverable rollback into a mixed tree.
logger.warning("rollback failed for %s: %s", dst, exc)
raise
+ if on_committed is not None:
+ on_committed() # every rename landed: an interrupted cleanup now finishes, never rolls back
for _dst, backup in swapped: # all swaps succeeded — drop the backups (best-effort, never fatal)
if backup:
_remove_path(backup, ignore_errors=True)
@@ -210,7 +220,8 @@ def _is_zip_preserved_entry_status_line(line: str, shipped: Optional[Collection[
def _is_zip_staging_artifact_status_line(line: str) -> bool:
"""True when a porcelain status line is our own two-phase-swap artifact."""
- return _status_top_level(line[3:] if len(line) >= 3 else line).endswith(_ZIP_STAGING_ARTIFACT_SUFFIXES)
+ top = _status_top_level(line[3:] if len(line) >= 3 else line)
+ return top.endswith(_ZIP_STAGING_ARTIFACT_SUFFIXES) or top in _ZIP_HERMES_ROOT_ARTIFACTS
def _abort_zip_update_if_dirty_tree() -> None:
@@ -219,7 +230,9 @@ def _abort_zip_update_if_dirty_tree() -> None:
See #87304.
"""
from hermes_cli.update_cmd import _m
- reason = _zip_overlay_block_reason(_m().PROJECT_ROOT)
+ # Our own staging/backup siblings and breadcrumbs are never user work: counting them refused
+ # every retry after an interrupted swap (the next run's staging clears them per entry).
+ reason = _zip_overlay_block_reason(_m().PROJECT_ROOT, ignore_staging_artifacts=True)
if reason is None:
return
print(f"✗ ZIP fallback refused: {reason}.")
@@ -322,7 +335,57 @@ def _stage_entries(extracted: str, entries: list[str], project_root: str) -> lis
return staged
-def _download_and_swap_zip(branch: str, zip_url: str) -> None:
+def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, target_sha) -> list:
+ """Stage + swap under the ZIP swap journal and its owner lock (``_early_recovery``), so a kill at
+ any point is finished or rolled back by the next launch and no staging/backup sibling leaks."""
+ from hermes_cli import update_cmd_commit as _commit
+ from hermes_cli.update_cmd import _UPDATE_CRITICAL_FILES, _m
+
+ # A previous run killed mid-swap: settle it before staging over its leftovers.
+ restore_interrupted_zip_swap(root)
+ with zip_swap_owner_lock(root, wait=10.0) as owned:
+ if not owned:
+ raise RuntimeError("another `hermes update` is swapping this install right now")
+ journal_entries = [[item, os.path.lexists(os.path.join(root, item))] for item in entries]
+ write_zip_swap_journal(root, "staging", journal_entries)
+ try:
+ staged = _stage_entries(extracted, entries, str(root))
+ except BaseException:
+ (root / ZIP_SWAP_JOURNAL).unlink(missing_ok=True) # _stage_entries dropped its copies
+ raise
+ try:
+ # TOCTOU re-check right before the swap: download + extract + staging can take minutes and
+ # work created meanwhile would be destroyed. Our own staging siblings are filtered out.
+ recheck_reason = _zip_overlay_block_reason(root, ignore_staging_artifacts=True, shipped=entries)
+ if recheck_reason is not None:
+ _discard_staged(staged)
+ (root / ZIP_SWAP_JOURNAL).unlink(missing_ok=True)
+ print(f"✗ ZIP fallback aborted before the swap: {recheck_reason}.")
+ print(" Files appeared in the checkout while the update was downloading; committing the swap would delete them.")
+ print(_STASH_HINT)
+ _m().sys.exit(1)
+ # Pre-commit gate: a target whose startup modules do not compile is refused untouched.
+ for rel in _UPDATE_CRITICAL_FILES:
+ path = os.path.join(extracted, *rel.split("/"))
+ if os.path.isfile(path):
+ with open(path, "rb") as handle:
+ compile(handle.read(), rel, "exec", dont_inherit=True)
+ # The commit point: tail + fleet restart owed before the first live rename.
+ _commit.arm_commit_obligations(root, target_sha or "")
+ write_zip_swap_journal(root, "swapping", journal_entries)
+ _commit_staged_replacements(
+ staged, on_committed=lambda: write_zip_swap_journal(root, "committed", journal_entries))
+ except Exception:
+ # Rollback restored swapped entries but staging copies for the rest remain; drop them or the
+ # retry's up-front free-space check (runs BEFORE per-entry leftover cleanup) fails on our litter.
+ # Safe post-rollback: _discard_staged skips paths that no longer exist.
+ _discard_staged(staged)
+ raise
+ (root / ZIP_SWAP_JOURNAL).unlink(missing_ok=True)
+ return staged
+
+
+def _download_and_swap_zip(branch: str, zip_url: str, target_sha: str | None = None) -> None:
"""Download the source ZIP for *branch* and two-phase swap it into the checkout.
``sys.exit(1)`` on any failure; the install ends fully updated or fully rolled back.
Two-phase: stage every entry (dirs AND top-level files) beside its target, then swap all in with
@@ -343,27 +406,16 @@ def _download_and_swap_zip(branch: str, zip_url: str) -> None:
entries = [i for i in os.listdir(extracted) if i not in _ZIP_PRESERVED_TOP_LEVEL]
project_root = str(_m().PROJECT_ROOT)
_require_staging_space(extracted, entries, project_root)
- staged = _stage_entries(extracted, entries, project_root)
- try:
- # TOCTOU re-check right before the swap: download + extract + staging can take minutes and
- # work created meanwhile would be destroyed. Our own staging siblings are filtered out.
- recheck_reason = _zip_overlay_block_reason(
- _m().PROJECT_ROOT, ignore_staging_artifacts=True, shipped=entries)
- if recheck_reason is not None:
- _discard_staged(staged)
- print(f"✗ ZIP fallback aborted before the swap: {recheck_reason}.")
- print(" Files appeared in the checkout while the update was downloading; committing the swap would delete them.")
- print(_STASH_HINT)
- _m().sys.exit(1)
- _commit_staged_replacements(staged)
- except Exception:
- # Rollback restored swapped entries but staging copies for the rest remain; drop them or the
- # retry's up-front free-space check (runs BEFORE per-entry leftover cleanup) fails on our litter.
- # Safe post-rollback: _discard_staged skips paths that no longer exist.
- _discard_staged(staged)
- raise
+ staged = _journaled_stage_and_swap(extracted, entries, Path(project_root), target_sha)
print(f"✓ Updated {len(staged)} items from ZIP")
except Exception as e:
+ # The swap rolled itself back; a rollback that could not finish leaves the journal, which
+ # this settles now (or the next launch's _early_recovery does) instead of leaking siblings.
+ with suppress(Exception):
+ restore_interrupted_zip_swap(_m().PROJECT_ROOT)
+ if not (Path(_m().PROJECT_ROOT) / ZIP_SWAP_JOURNAL).exists():
+ from hermes_cli import update_cmd_commit as _commit
+ _commit.disarm_commit_obligations() # the old tree is whole again: nothing is owed
print(f"✗ ZIP update failed: {e}")
# Two-phase replace commits all or rolls all back, so no mixed tree here — don't push a needless reinstall.
print(" Your existing install was left in place.")
@@ -406,7 +458,7 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False,
if (not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository)
or any(part in (".", "..") for part in repository.split("/"))):
raise ValueError("ZIP update requires a GitHub owner/repository")
- _download_and_swap_zip(branch, f"https://github.com/{repository}/archive/{ref}.zip")
+ _download_and_swap_zip(branch, f"https://github.com/{repository}/archive/{ref}.zip", target_sha)
completion_request["expected_sha"] = target_sha
completion_request["apply_mode"] = "zip"
_complete_source_update(completion_request)
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index 0480388f2e4..587522b7fbe 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -332,11 +332,10 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:
if refused is not None:
raise RuntimeError("could not join the update's checkout lock "
f"({refused.reason or f'held by process {refused.pid}'})")
- from hermes_cli.venv_sync import (
- arm_completion, collect_superseded_generations, refuse_foreign_owned_venv,
- )
+ from hermes_cli.venv_sync import arm_completion, collect_superseded_generations
- refuse_foreign_owned_venv(root)
+ # The foreign-owned-venv refusal runs in the parent BEFORE the swap (update_cmd_commit
+ # .preflight_refusal); the tail was armed there too, so this re-arm is an idempotent backstop.
arm_completion(root)
from hermes_cli.gitlock import convert_treeless_checkout_first
convert_treeless_checkout_first(root)