Skip to content

The agent that grows with you

fix: the stash and churn steps bind the paused gateways' tree gate before writing files

Teknium636fbbd7c431
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 81e559b796a..b0366857461 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -967,11 +967,12 @@ def _resolved_commit(git_cmd, ref: str) -> str:
@contextmanager
-def _checkout_move(token, *targets, paths=()):
+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>``), on a baseline taken at the HEAD it starts from. Without that, a step
+ ``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.
@@ -985,11 +986,12 @@ def _checkout_move(token, *targets, paths=()):
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) else None
+ 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"]
@@ -1007,6 +1009,11 @@ def _checkout_move(token, *targets, paths=()):
_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
@@ -1098,7 +1105,7 @@ def _pull_updates(
_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=lambda target: _checkout_move(_windows_gateway_resume, target))
+ checkout_move=_moves_for(_windows_gateway_resume))
# 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,
@@ -1123,7 +1130,7 @@ 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)
+ input_fn=gw_input_fn, checkout_move=_moves_for(_windows_gateway_resume))
return movement_baseline
@@ -1210,7 +1217,8 @@ 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)
+ auto_stash_ref = _m()._stash_local_changes_if_needed(
+ git_cmd, _m().PROJECT_ROOT, checkout_move=_moves_for(_windows_gateway_resume))
moved_from_sha = None
rollback_branch = None
if not release_tag and not in_place_update and current_branch != branch:
@@ -1228,7 +1236,8 @@ def _prepare_checkout_for_update(
# 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)
+ git_cmd, _m().PROJECT_ROOT, auto_stash_ref, prompt_user=False, input_fn=gw_input_fn,
+ checkout_move=_moves_for(_windows_gateway_resume))
print(f"✗ Branch '{branch}' does not exist locally or on origin.")
if track_result.stderr.strip():
print(f" {track_result.stderr.strip().splitlines()[0]}")
@@ -1284,7 +1293,7 @@ def _prepare_checkout_for_update(
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=lambda target: _checkout_move(_windows_gateway_resume, target))
+ checkout_move=_moves_for(_windows_gateway_resume))
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(
@@ -1389,9 +1398,10 @@ def _record_update_initiator() -> None:
_completion_receipt.record_fact("initiator", "desktop")
-def _prepare_git_command() -> tuple[bool, list, bool]:
+def _prepare_git_command(*, checkout_move=None) -> 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)."""
+ 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."""
git_dir = _m().PROJECT_ROOT / ".git"
use_zip_update = not git_dir.exists()
if use_zip_update and sys.platform != "win32":
@@ -1416,8 +1426,8 @@ def _prepare_git_command() -> 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)
- _normalize_managed_eol(git_cmd, _m().PROJECT_ROOT)
+ _discard_lockfile_churn(git_cmd, _m().PROJECT_ROOT, checkout_move=checkout_move)
+ _normalize_managed_eol(git_cmd, _m().PROJECT_ROOT, checkout_move=checkout_move)
origin_url = _m()._get_origin_url(git_cmd, _m().PROJECT_ROOT)
is_fork = _is_fork(origin_url)
@@ -1520,15 +1530,17 @@ 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) -> None:
- """"Already up to date" path: restore stash/branch, repair the checkout, catch up the fleet.
+ 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.
``sys.exit(1)`` when the repair is incomplete (after gateway exit code + partial receipt)."""
- # 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.
+ # 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.
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)
+ input_fn=gw_input_fn, checkout_move=_moves_for(_windows_gateway_resume))
if _plan.parked_branch_switched:
if _plan.switch_block_reason.startswith("unmerged:"):
_count = _plan.switch_block_reason.split(":", 1)[1]
@@ -1537,8 +1549,6 @@ 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
@@ -1612,7 +1622,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()
+ use_zip_update, git_cmd, is_fork = _prepare_git_command(checkout_move=_moves_for(_windows_gateway_resume))
completion_request = _source_completion_request(
opts, _pre_update_plan, pre_update_snapshot_id, _windows_gateway_resume,
@@ -1731,7 +1741,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)
+ completion_request=completion_request, _windows_gateway_resume=_windows_gateway_resume)
return
if release_sha:
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index 8b5994a77cb..be48874309a 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -412,7 +412,7 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
# 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
# very commit counted above.
- with (checkout_move or (lambda _target: nullcontext()))(upstream):
+ 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:
print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")
@@ -569,7 +569,12 @@ def _npm_lockfile_owners(repo_root: Path) -> set[Path]:
return owners
-def _discard_lockfile_churn(git_cmd, repo_root):
+def _no_move(*_targets, **_bound):
+ """The ``checkout_move`` of a run with no paused gateways: the step runs unbound."""
+ return nullcontext({})
+
+
+def _discard_lockfile_churn(git_cmd, repo_root, *, checkout_move=None):
"""Restore ``package-lock.json`` files npm rewrote non-deterministically, so the update sees a clean tree
instead of autostashing every run. A lockfile is kept when a manifest it records is dirty: for the root
lock that is the root or ANY workspace ``package.json`` (reverting it under a dirty ``apps/desktop``
@@ -595,11 +600,12 @@ def _discard_lockfile_churn(git_cmd, repo_root):
dirty.append(path)
if not dirty:
return
- _git_run(git_cmd, ["checkout", "--", *dirty], repo_root)
+ with (checkout_move or _no_move)(paths=dirty):
+ _git_run(git_cmd, ["checkout", "--", *dirty], repo_root)
print(f"→ Discarded npm lockfile churn ({len(dirty)} file(s))")
-def _normalize_managed_eol(git_cmd, repo_root):
+def _normalize_managed_eol(git_cmd, repo_root, *, checkout_move=None):
"""Take a managed checkout off ``core.autocrlf=true`` without leaving it dirty.
Git for Windows sets ``autocrlf=true`` system-wide, turning LF files CRLF and breaking ``git checkout``
@@ -644,8 +650,9 @@ def _normalize_managed_eol(git_cmd, repo_root):
return
if eol_only:
# Pathspec via stdin: thousands of paths exceed the Windows argv limit.
- _probe_run("checkout", "--pathspec-from-file=-", "--pathspec-file-nul", "--",
- input="\0".join(sorted(eol_only)), check=False)
+ with (checkout_move or _no_move)(paths=sorted(eol_only)):
+ _probe_run("checkout", "--pathspec-from-file=-", "--pathspec-file-nul", "--",
+ input="\0".join(sorted(eol_only)), check=False)
if _eol_only(): # still dirty: pinning would only surface churn we failed to clear
return
print(f"→ Normalized line-ending churn ({len(eol_only)} file(s))")
diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.py
index b2164955edc..591a32de525 100644
--- a/hermes_cli/update_cmd_stash.py
+++ b/hermes_cli/update_cmd_stash.py
@@ -83,9 +83,11 @@ def _print_first_line(text: str) -> None:
print(f" {text.strip().splitlines()[0]}")
-def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[str]:
+def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path, *, checkout_move=None) -> Optional[str]:
+ """Stash local changes before the update moves the checkout; the stash commit, or None when clean.
+ ``checkout_move`` binds the push (and its cleanup reset) to the paused gateways' tree gate."""
global _pending_autostash
- from hermes_cli.update_cmd_git import _git_run
+ from hermes_cli.update_cmd_git import _git_run, _no_move
_pending_autostash = None
status = _git_run(git_cmd, ["status", "--porcelain", "-z"], cwd, check=True)
if not status.stdout.strip():
@@ -110,6 +112,17 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st
stash_name = datetime.now(timezone.utc).strftime(f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S")
print("→ Local changes detected — stashing before update...")
prev_stash = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd).stdout.strip()
+ with (checkout_move or _no_move)(revert=True): # push and reset put every tracked change back to HEAD
+ stash_ref = _push_stash(git_cmd, cwd, stash_name, prev_stash)
+ _pending_autostash = (
+ stash_ref, len([entry for entry in status.stdout.split("\0") if entry]))
+ return stash_ref
+
+
+def _push_stash(git_cmd: list[str], cwd: Path, stash_name: str, prev_stash: str) -> str:
+ """``git stash push``; the stash commit. Raises when nothing was saved; resets tracked leftovers
+ when a push saved everything but could not clean up."""
+ from hermes_cli.update_cmd_git import _git_run
push = _git_run(git_cmd, ["stash", "push", "--include-untracked", "-m", stash_name], cwd)
_print_nonempty(push.stdout)
stash_probe = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd)
@@ -132,8 +145,6 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st
# A partially-failed push also skips cleanup of TRACKED modifications; they'd break the following
# pull. Safe to reset: all is in the stash.
_reset_hard(git_cmd, cwd)
- _pending_autostash = (
- stash_ref, len([entry for entry in status.stdout.split("\0") if entry]))
return stash_ref
@@ -324,10 +335,11 @@ def _restored_python_paths(git_cmd: list[str], cwd: Path) -> tuple[str, ...] | N
def _reject_unsafe_stash_restore(
git_cmd: list[str], cwd: Path, stash_ref: str, preexisting_untracked: set[str], failing_target: str,
- detail: str | None,
+ detail: str | None, *, checkout_move=None,
) -> None:
"""Restore the clean updated tree, preserve the stash, and abort the update."""
from hermes_cli.update_cmd import _git_untracked_paths
+ from hermes_cli.update_cmd_git import _no_move
print()
print("✗ Restored local changes made the Hermes agent unexecutable.")
print(f" Health check failed: {failing_target}")
@@ -340,8 +352,9 @@ def _reject_unsafe_stash_restore(
current_untracked = _git_untracked_paths(git_cmd, cwd)
restored_untracked = current_untracked - preexisting_untracked if current_untracked is not None else set()
- reset = _git_quiet(git_cmd, ["reset", "--hard", "HEAD"], cwd)
- clean = _git_quiet(git_cmd, ["clean", "-fd", "--", *sorted(restored_untracked)], cwd) if restored_untracked else None
+ with (checkout_move or _no_move)(revert=True):
+ reset = _git_quiet(git_cmd, ["reset", "--hard", "HEAD"], cwd)
+ clean = _git_quiet(git_cmd, ["clean", "-fd", "--", *sorted(restored_untracked)], cwd) if restored_untracked else None
cleanup_ok = current_untracked is not None and _ok(reset) and (not restored_untracked or _ok(clean))
if cleanup_ok:
cleanup_ok = _ok(_git_quiet(git_cmd, ["diff", "--quiet", "HEAD", "--"], cwd))
@@ -382,17 +395,21 @@ def _confirm_restore(stash_ref: str, input_fn) -> bool:
return False
-def _apply_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> list[str] | None:
+def _apply_stash(git_cmd: list[str], cwd: Path, stash_ref: str, checkout_move=None) -> list[str] | None:
"""``git stash apply``; the untracked paths the update replaced (empty on a full restore), or
- None (tree reset, stash kept) on conflicts or any failure other than the already-exists class."""
- from hermes_cli.update_cmd_git import _git_run
+ None (tree reset, stash kept) on conflicts or any failure other than the already-exists class.
+ ``checkout_move`` binds the apply (and a conflict's reset) to the paused gateways' tree gate."""
+ from hermes_cli.update_cmd_git import _no_move
print("→ Restoring local changes...")
- restore = _git_run(git_cmd, ["stash", "apply", stash_ref], cwd)
- unmerged = _git_run(git_cmd, ["diff", "--name-only", "--diff-filter=U"], cwd) # conflicts can exist even on rc 0
- conflicted_files = unmerged.stdout.strip()
- if restore.returncode == 0 and not conflicted_files:
+ with (checkout_move or _no_move)(stash_ref) as step:
+ restore, conflicted_files = _apply_stash_step(git_cmd, cwd, stash_ref)
+ # Tracked changes applied in full (the already-exists class refuses only untracked files):
+ # the tree this changed is the restore's result, not a tear.
+ step["whole"] = not conflicted_files and (
+ restore.returncode == 0 or _stash_apply_failed_only_on_existing_untracked(restore.stderr))
+ if step["whole"] and restore.returncode == 0:
return []
- if not conflicted_files and _stash_apply_failed_only_on_existing_untracked(restore.stderr):
+ if step["whole"]:
# Tracked changes applied; git refused to overwrite untracked files that already exist. That is
# harmless only when the occupant IS the stashed copy (undeletable at stash time, #70127). When
# the update added its own file at that path, the stash is the only copy of the user's file.
@@ -409,13 +426,26 @@ def _apply_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> list[str] | N
print(f" • {f}")
print("\nYour stashed changes are preserved — nothing is lost.")
print(f" Stash ref: {stash_ref}")
- _reset_hard(git_cmd, cwd) # conflict markers make hermes unrunnable; changes stay in the stash
print("Working tree reset to clean state.")
print(f"Restore your changes later with: git stash apply {stash_ref}")
_record_stash_disposition("parked", stash_ref, "restore hit conflicts")
return None # code update succeeded; cmd_update continues (deps, skills, gateway)
+def _apply_stash_step(git_cmd: list[str], cwd: Path, stash_ref: str):
+ """``git stash apply`` and its conflicted paths. Any failure but the already-exists class is
+ reset to the clean tree here, inside the bound step: conflict markers make hermes unrunnable,
+ and the changes stay in the stash."""
+ from hermes_cli.update_cmd_git import _git_run
+ restore = _git_run(git_cmd, ["stash", "apply", stash_ref], cwd)
+ unmerged = _git_run(git_cmd, ["diff", "--name-only", "--diff-filter=U"], cwd) # conflicts can exist even on rc 0
+ conflicted_files = unmerged.stdout.strip()
+ if conflicted_files or (restore.returncode != 0
+ and not _stash_apply_failed_only_on_existing_untracked(restore.stderr)):
+ _reset_hard(git_cmd, cwd)
+ return restore, conflicted_files
+
+
def _drop_restored_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> None:
from hermes_cli.update_cmd_git import _git_run
stash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref)
@@ -434,7 +464,8 @@ def _drop_restored_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> None:
def _restore_stashed_changes(
- git_cmd: list[str], cwd: Path, stash_ref: str, prompt_user: bool = False, input_fn=None,
+ git_cmd: list[str], cwd: Path, stash_ref: str, prompt_user: bool = False, input_fn=None, *,
+ checkout_move=None,
) -> bool:
from hermes_cli.update_cmd import _critical_module_import_failures, _git_untracked_paths, _restored_python_paths, _validate_python_files_syntax
if prompt_user and not _confirm_restore(stash_ref, input_fn):
@@ -447,12 +478,13 @@ def _restore_stashed_changes(
_record_stash_disposition("parked", stash_ref, "untracked baseline unknown")
return False
clean_import_failures = _critical_module_import_failures(cwd, report_runtime_errors=True)
- replaced = _apply_stash(git_cmd, cwd, stash_ref)
+ replaced = _apply_stash(git_cmd, cwd, stash_ref, checkout_move)
if replaced is None:
return False # disposition already recorded inside _apply_stash
def reject(failing_target: str, detail) -> None:
- _reject_unsafe_stash_restore(git_cmd, cwd, stash_ref, preexisting_untracked, failing_target, detail)
+ _reject_unsafe_stash_restore(
+ git_cmd, cwd, stash_ref, preexisting_untracked, failing_target, detail, checkout_move=checkout_move)
restored_python = _restored_python_paths(git_cmd, cwd)
if restored_python is None:
diff --git a/tests/gateway/test_update_streaming.py b/tests/gateway/test_update_streaming.py
index 69b76b12b70..f0193e5db6e 100644
--- a/tests/gateway/test_update_streaming.py
+++ b/tests/gateway/test_update_streaming.py
@@ -367,7 +367,7 @@ class TestCmdUpdateGatewayMode:
monkeypatch.setattr(main, "_run_pre_update_backup", lambda args: None)
monkeypatch.setattr(main, "_pause_windows_gateways_for_update", lambda: None)
monkeypatch.setattr("hermes_cli.update_inventory.collect_runtime_inventory", lambda: None)
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (False, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (False, ["git"], False))
monkeypatch.setattr(update_cmd, "run_completion", lambda request: {"exit_code": 0, "receipt": None})
gateway_prompt = MagicMock(return_value="n")
monkeypatch.setattr(update_cmd, "_gateway_prompt", gateway_prompt)
diff --git a/tests/hermes_cli/test_source_channel_integration.py b/tests/hermes_cli/test_source_channel_integration.py
index 10d8704e1df..adbde5a722e 100644
--- a/tests/hermes_cli/test_source_channel_integration.py
+++ b/tests/hermes_cli/test_source_channel_integration.py
@@ -52,7 +52,7 @@ def source(tmp_path, monkeypatch):
monkeypatch.setattr(update_cmd, "_begin_update_receipt_and_plan", lambda *_: None)
monkeypatch.setattr(main, "_run_pre_update_backup", lambda *_: None)
monkeypatch.setattr(main, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (False, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (False, ["git"], False))
return SimpleNamespace(home=home, origin=origin, root=checkout, commits=commits, parser=parser)
@@ -350,7 +350,7 @@ def test_retirement_refuses_to_downgrade_newer_source(
git(source.root.parent, "clone", "--depth=1", source.origin.as_uri(), str(source.root))
if transport == "zip":
(source.root / "pyproject.toml").write_text('[project]\nversion = "1.2.2"\n')
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (True, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (True, ["git"], False))
original = deepcopy(saved(source))
completed = []
monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: completed.append(request))
@@ -380,7 +380,7 @@ def test_tagless_zip_apply_uses_pinned_source_archive(source, monkeypatch, dirty
urls.append(url)
shutil.copyfile(archive, filename)
monkeypatch.setattr(urllib.request, "urlretrieve", download)
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (True, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (True, ["git"], False))
completed = []
monkeypatch.setattr(update_cmd, "_complete_source_update", lambda req: completed.append(deepcopy(req)))
if dirty:
diff --git a/tests/hermes_cli/test_source_release_channels.py b/tests/hermes_cli/test_source_release_channels.py
index 543df7b53d8..caa6c2342d7 100644
--- a/tests/hermes_cli/test_source_release_channels.py
+++ b/tests/hermes_cli/test_source_release_channels.py
@@ -146,7 +146,7 @@ def test_source_check_and_apply_land_on_selected_release(releases, monkeypatch,
monkeypatch.setattr(update_cmd, "_begin_update_receipt_and_plan", lambda *_: None)
monkeypatch.setattr(main, "_run_pre_update_backup", lambda *_: None)
monkeypatch.setattr(main, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (False, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (False, ["git"], False))
applied = []
monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: applied.append(request))
args = SimpleNamespace(branch=None, channel=None, force_venv=True)
diff --git a/tests/hermes_cli/test_update_pause_step_interruptions.py b/tests/hermes_cli/test_update_pause_step_interruptions.py
new file mode 100644
index 00000000000..815862bbdf2
--- /dev/null
+++ b/tests/hermes_cli/test_update_pause_step_interruptions.py
@@ -0,0 +1,131 @@
+"""The stash and churn steps bind the paused gateways' tree gate too (#132338 R3 follow-up).
+
+``git stash push`` / ``stash apply`` and the lockfile-churn ``checkout -- <paths>`` rewrite tracked
+files while the Windows pause holds the gateways. Each now records, before git runs, the HEAD it
+starts from, the tree's dirty bytes and what it may write; a step interrupted mid-write keeps the
+set held instead of being judged against unrelated refs (or, at a moved HEAD, against nothing).
+
+Real git, real update steps, real durable record and gate. The interruption is real too: a git
+wrapper copies the durable record as git starts (what was on disk before the write), runs real git,
+leaves one file half-written and sends the updater SIGINT, as a terminal's Ctrl-C reaches both.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+
+import pytest
+
+from hermes_cli import update_cmd, update_cmd_git, update_cmd_stash
+from hermes_cli import update_pause_record as pause_record
+
+pytestmark = pytest.mark.platforms("posix")
+
+
+def git(root, *args) -> str:
+ return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, text=True).stdout.strip()
+
+
+def commit(root, message, **files) -> str:
+ for name, text in files.items():
+ (root / name).write_text(text, encoding="utf-8")
+ git(root, "add", ".")
+ git(root, "commit", "-qm", message)
+ return git(root, "rev-parse", "HEAD")
+
+
+def repo(tmp_path, monkeypatch):
+ root = tmp_path / "checkout"
+ root.mkdir()
+ git(root, "init", "-q", "-b", "main")
+ git(root, "config", "user.name", "Fixture")
+ git(root, "config", "user.email", "[email protected]")
+ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)
+ monkeypatch.setattr(pause_record, "install_root", lambda: root)
+ a = commit(root, "A", **{"a.py": "A=1\n", "mine.py": "M=1\n", "package-lock.json": "{}\n"})
+ t = commit(root, "T", **{"a.py": "A=2\n"})
+ git(root, "reset", "-q", "--hard", a)
+ # A fetched ref that never touches the files these steps write: what the gate fell back to.
+ git(root, "update-ref", "refs/remotes/origin/main", t)
+ return root, a, t
+
+
+def interrupting_git(tmp_path, match: str, tear) -> list[str]:
+ """A git that, on the *match* subcommand, snapshots the durable record, runs real git, leaves
+ *tear* half-written and interrupts the updater."""
+ wrapper = tmp_path / "git-interrupted"
+ wrapper.write_text(
+ "#!/bin/sh\n"
+ f'case " $* " in *" {match} "*) cp "{pause_record.record_path()}" "{tmp_path / "at-start.json"}"\n'
+ f' "{shutil.which("git")}" "$@"\n'
+ f" printf 'M=' > \"{tear}\"; kill -INT $PPID; sleep 5; exit 130;;\n"
+ f'esac\nexec "{shutil.which("git")}" "$@"\n',
+ encoding="utf-8")
+ wrapper.chmod(0o755)
+ return [str(wrapper)]
+
+
+def pause(root) -> dict:
+ token = pause_record.stamp_tree({"resume_needed": True, "profiles": {"default": 999999}}, root)
+ pause_record.write(token)
+ return token
+
+
+def gate(root) -> bool:
+ return pause_record.tree_is_whole(pause_record.read(pause_record.record_path())["token"], root)[0]
+
+
+def at_start(tmp_path, head) -> dict:
+ """The baseline at *head* in the record as it was on disk the moment git started."""
+ token = pause_record.read(tmp_path / "at-start.json")["token"]
+ return next(b for b in token["baselines"] if b["pre_sha"] == head)
+
+
+def test_an_interrupted_stash_push_stays_held(repo, tmp_path):
+ root, a, _t = repo
+ (root / "mine.py").write_text("M=2 # my edit\n", encoding="utf-8")
+ token = pause(root)
+ with pytest.raises(KeyboardInterrupt):
+ update_cmd_stash._stash_local_changes_if_needed(
+ interrupting_git(tmp_path, "stash push", root / "mine.py"), root,
+ checkout_move=update_cmd._moves_for(token))
+ started = at_start(tmp_path, a)
+ assert "mine.py" in started["move_paths"] and started["dirty_at_pause"] == ["mine.py"]
+ assert gate(root) is False, "a stash push interrupted mid-write was admitted"
+
+
+def test_an_interrupted_lockfile_churn_cleanup_stays_held(repo, tmp_path):
+ root, a, _t = repo
+ (root / "package-lock.json").write_text('{"npm": "rewrote me"}\n', encoding="utf-8")
+ token = pause(root)
+ with pytest.raises(KeyboardInterrupt):
+ update_cmd_git._discard_lockfile_churn(
+ interrupting_git(tmp_path, "checkout --", root / "package-lock.json"), root,
+ checkout_move=update_cmd._moves_for(token))
+ assert at_start(tmp_path, a)["move_paths"] == ["package-lock.json"]
+ assert gate(root) is False, "a lockfile cleanup interrupted mid-write was admitted"
+
+
[email protected]("interrupted", [True, False])
+def test_a_stash_restore_at_the_moved_head_is_gated_from_that_head(repo, tmp_path, interrupted):
+ root, a, t = repo
+ (root / "mine.py").write_text("M=2 # my edit\n", encoding="utf-8")
+ token = pause(root)
+ moves = update_cmd._moves_for(token)
+ stash = update_cmd_stash._stash_local_changes_if_needed(["git"], root, checkout_move=moves)
+ with update_cmd._checkout_move(token, t):
+ git(root, "merge", "-q", "--ff-only", t) # the pull lands whole
+ git_cmd = interrupting_git(tmp_path, "stash apply", root / "mine.py") if interrupted else ["git"]
+ if interrupted:
+ with pytest.raises(KeyboardInterrupt):
+ update_cmd_stash._restore_stashed_changes(git_cmd, root, stash, checkout_move=moves)
+ started = at_start(tmp_path, t)
+ assert started["move_targets"] == [stash] and started["dirty_at_pause"] == []
+ assert gate(root) is False, "a stash restore interrupted mid-write at the moved HEAD was admitted"
+ else:
+ assert update_cmd_stash._restore_stashed_changes(git_cmd, root, stash, checkout_move=moves)
+ assert (root / "mine.py").read_text() == "M=2 # my edit\n"
+ assert gate(root) is True, "a stash restore that applied cleanly held the paused set"
diff --git a/tests/hermes_cli/test_update_venv_holder_retirement.py b/tests/hermes_cli/test_update_venv_holder_retirement.py
index 431fc1461c1..6cc84e480e0 100644
--- a/tests/hermes_cli/test_update_venv_holder_retirement.py
+++ b/tests/hermes_cli/test_update_venv_holder_retirement.py
@@ -100,7 +100,7 @@ def test_command_reaches_checkout_preparation_without_holder_gates(monkeypatch,
monkeypatch.setattr(main, "_is_windows", forbidden)
monkeypatch.setattr(os, "kill", forbidden)
- def prepare_checkout():
+ def prepare_checkout(**_):
reached.append("checkout")
raise ReachedCheckout
diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.py
index 514179e00ad..0d9e699a032 100644
--- a/tests/hermes_cli/test_update_zip_completion.py
+++ b/tests/hermes_cli/test_update_zip_completion.py
@@ -123,7 +123,7 @@ def test_zip_command_migrates_profiles_recovers_snapshot_and_verifies_fleet(
zip_update, monkeypatch, route, gateway_mode,
):
state = zip_update
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (route == "direct", ["git"], False))
monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)
def fail_fetch(*args, **kwargs):
@@ -193,7 +193,7 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon
old_project = (state.root / "pyproject.toml").read_bytes()
original_tree = {p.relative_to(state.root): p.read_bytes()
for p in state.root.rglob("*") if p.is_file()}
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (route == "direct", ["git"], False))
monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)
monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True)
@@ -423,7 +423,7 @@ def test_installed_app_without_a_checkout_build_is_still_rebuilt(zip_update, mon
built = []
monkeypatch.setattr("hermes_cli.source_build.build_update_products",
lambda selected, *, desktop: built.append(desktop))
- monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (True, ["git"], False))
+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda **_: (True, ["git"], False))
monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)
update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), False)