Skip to content

The agent that grows with you

fix(update): commit-point tree moves bind the paused gateways' tree gate

Teknium0ba1f73ae7b5
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 63222e7578c..48a98e6039d 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -30,6 +30,7 @@ from hermes_cli import update_receipt as _completion_receipt, update_cmd_config
from hermes_cli._old_updater import stop_for_relaunch
from hermes_cli._early_recovery import git_operation_in_progress, interrupted_pull_marker, is_object_id
from hermes_cli import update_cmd_commit as _commit
+from hermes_cli.update_cmd_pause_gate import _checkout_move, _moves_for # noqa: F401 (re-export)
from hermes_cli import update_cmd_check as _check
# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
@@ -911,7 +912,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) -> None:
+def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=None, _windows_gateway_resume=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)."""
pyproject = Path(_m().PROJECT_ROOT) / "pyproject.toml"
@@ -922,11 +923,13 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
else:
syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)
if not syntax_ok:
- _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error, rollback_branch=rollback_branch)
+ _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error, rollback_branch=rollback_branch,
+ _windows_gateway_resume=_windows_gateway_resume)
def _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error, *, rollback_branch=None,
- header="✗ Pulled code has a syntax error in a critical file:") -> NoReturn:
+ header="✗ Pulled code has a syntax error in a critical file:",
+ _windows_gateway_resume=None) -> NoReturn:
"""Restore the checkout to *pre_pull_sha* after a startup file failed the syntax check, then
``sys.exit(1)``."""
print()
@@ -954,30 +957,32 @@ def _roll_back_broken_update(git_cmd, pre_pull_sha, failing_path, syntax_error,
# Refusing would leave the broken tree in place: roll back unmarked, and only a tree
# verified whole at pre_pull_sha below may report success (else the manual recipe).
print(f" ⚠ Could not write the interrupted-pull marker ({exc}); rolling back without it.")
- added = _commit.files_added_by(git_cmd, root, pre_pull_sha, target_sha)
- if mode == "detach": # never move the update branch onto a parked/detached commit
- rollback_args = ["update-ref", "--no-deref", "HEAD", pre_pull_sha]
- rollback_result = _git_run(git_cmd, rollback_args)
- if mode == "branch" or rollback_result.returncode == 0:
- rollback_args = ["reset", "-q", pre_pull_sha] # HEAD (and the index) only, no file
- rollback_result = _git_run(git_cmd, rollback_args)
- if rollback_result.returncode == 0:
- rollback_args = ["reset", "--hard", pre_pull_sha]
- rollback_result = _git_run(git_cmd, rollback_args)
- if rollback_result.returncode == 0 and not _commit.drop_added_files(root, added):
+ # The paused gateways' tree gate knows the rollback's target before git writes a file.
+ with _checkout_move(_windows_gateway_resume, pre_pull_sha):
+ added = _commit.files_added_by(git_cmd, root, pre_pull_sha, target_sha)
+ if mode == "detach": # never move the update branch onto a parked/detached commit
+ rollback_args = ["update-ref", "--no-deref", "HEAD", pre_pull_sha]
+ rollback_result = _git_run(git_cmd, rollback_args)
+ if mode == "branch" or rollback_result.returncode == 0:
+ rollback_args = ["reset", "-q", pre_pull_sha] # HEAD (and the index) only, no file
+ rollback_result = _git_run(git_cmd, rollback_args)
+ if rollback_result.returncode == 0:
+ rollback_args = ["reset", "--hard", pre_pull_sha]
+ rollback_result = _git_run(git_cmd, rollback_args)
+ if rollback_result.returncode == 0 and not _commit.drop_added_files(root, added):
+ rollback_result = subprocess.CompletedProcess(
+ rollback_args, 1, "", "could not remove the broken release's added files")
+ if rollback_result.returncode == 0 and not _commit.tree_whole_at(git_cmd, root, pre_pull_sha):
+ # git said yes; the tree must agree (HEAD on pre, no tracked change) before the marker goes.
rollback_result = subprocess.CompletedProcess(
- rollback_args, 1, "", "could not remove the broken release's added files")
- if rollback_result.returncode == 0 and not _commit.tree_whole_at(git_cmd, root, pre_pull_sha):
- # git said yes; the tree must agree (HEAD on pre, no tracked change) before the marker goes.
- rollback_result = subprocess.CompletedProcess(
- rollback_args, 1, "", f"the checkout is not whole at {pre_pull_sha[:10]}")
- if rollback_result.returncode != 0 and _commit.settle_failed_tree_move(root):
- rollback_result = subprocess.CompletedProcess(rollback_args, 0, "", "") # restored in-process
- if rollback_result.returncode == 0 and parked:
- # Same commit, so only HEAD's name changes. The parked branch can be unavailable (e.g.
- # checked out in another worktree): its commit then stays checked out detached.
- if _git_run(git_cmd, ["checkout", rollback_branch]).returncode != 0:
- print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")
+ rollback_args, 1, "", f"the checkout is not whole at {pre_pull_sha[:10]}")
+ if rollback_result.returncode != 0 and _commit.settle_failed_tree_move(root):
+ rollback_result = subprocess.CompletedProcess(rollback_args, 0, "", "") # restored in-process
+ if rollback_result.returncode == 0 and parked:
+ # Same commit, so only HEAD's name changes. The parked branch can be unavailable (e.g.
+ # checked out in another worktree): its commit then stays checked out detached.
+ if _git_run(git_cmd, ["checkout", rollback_branch]).returncode != 0:
+ print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")
if rollback_result.returncode == 0:
interrupted_pull_marker(root).unlink(missing_ok=True)
_commit.disarm_commit_obligations() # back on the code this run started from
@@ -1034,6 +1039,44 @@ 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()
+
+
+def _move_checkout_to(git_cmd, branch, merge_ref, target_sha, pre_pull_sha) -> None:
+ """The principal pull's one checkout move onto *target_sha*; exits when it cannot be made."""
+ # merge --ff-only the already-fetched commit instead of `git pull`, which would do a
+ # SECOND network fetch. Every move names ``target_sha``, never the ref: a ref that moves
+ # after the arm cannot land a commit the marker and the debt do not name (review O3).
+ 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", target_sha], check=True)
+ return
+ merge_result = _git_run(git_cmd, ["merge", "--ff-only", target_sha])
+ if merge_result.returncode == 0:
+ return
+ ancestry = _git_run(git_cmd, ["merge-base", "--is-ancestor", "HEAD", target_sha])
+ if ancestry.returncode == 1:
+ _reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha, target_ref=target_sha)
+ return
+ 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,
@@ -1073,36 +1116,9 @@ def _pull_updates(
print(f"✗ {refused}.")
sys.exit(1)
try:
- # merge --ff-only the already-fetched commit instead of `git pull`, which would do a
- # SECOND network fetch. Every move names ``target_sha``, never the ref: a ref that moves
- # after the arm cannot land a commit the marker and the debt do not name (review O3).
- 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", target_sha], check=True)
- else:
- merge_result = _git_run(git_cmd, ["merge", "--ff-only", target_sha])
- if merge_result.returncode != 0:
- ancestry = _git_run(
- git_cmd, ["merge-base", "--is-ancestor", "HEAD", target_sha])
- if ancestry.returncode == 1:
- _reconcile_diverged_checkout(
- git_cmd, branch, pre_pull_sha, target_ref=target_sha)
- 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)
+ # 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, target_sha, pre_pull_sha)
_refuse_unselected_head(git_cmd, target_sha, pre_pull_sha) # before the marker goes
except KeyboardInterrupt:
raise # Ctrl-C reached git too (same process group): the tree may be torn, keep the marker
@@ -1125,19 +1141,22 @@ def _pull_updates(
_windows_gateway_resume=_windows_gateway_resume)
try:
_m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn,
+ checkout_move=_moves_for(_windows_gateway_resume))
except UpstreamTargetBroken as broken: # refused before its move: the update rolls back
_verify_head_after_pull( # never reset an unexpected branch's ref onto pre
git_cmd, branch, movement_baseline, in_place_update=in_place_update,
_windows_gateway_resume=_windows_gateway_resume)
_roll_back_broken_update(git_cmd, pre_sync_sha or pre_pull_sha, broken.path, broken.error,
- rollback_branch=rollback_branch, header=_upstream_broken_header(broken))
+ rollback_branch=rollback_branch, header=_upstream_broken_header(broken),
+ _windows_gateway_resume=_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,
_windows_gateway_resume=_windows_gateway_resume)
_rollback_if_pulled_syntax_error(
- git_cmd, pre_sync_sha or pre_pull_sha, rollback_branch=rollback_branch)
+ git_cmd, pre_sync_sha or pre_pull_sha, rollback_branch=rollback_branch,
+ _windows_gateway_resume=_windows_gateway_resume)
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)
@@ -1158,7 +1177,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
@@ -1237,7 +1256,8 @@ def _refuse_before_commit_point(git_cmd, target_ref, _windows_gateway_resume) ->
sys.exit(1)
-def _exit_after_failed_branch_switch(git_cmd, branch, track_result, auto_stash_ref, gw_input_fn) -> NoReturn:
+def _exit_after_failed_branch_switch(
+ git_cmd, branch, track_result, auto_stash_ref, gw_input_fn, _windows_gateway_resume=None) -> NoReturn:
"""CP0 did not land: say which of refused / torn / missing branch it was, then ``sys.exit(1)``.
A torn switch keeps its marker for the next launch's restore, so the autostash stays parked:
@@ -1256,7 +1276,8 @@ def _exit_after_failed_branch_switch(git_cmd, branch, track_result, auto_stash_r
# Nothing moved: 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))
if track_result.args in (_ARM_REFUSED, _REF_MOVED):
print(f"✗ {detail}.")
else:
@@ -1349,7 +1370,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:
@@ -1357,10 +1379,14 @@ 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
- track_result = _switch_branch_at_commit_point(
- git_cmd, branch, target_ref, pre=moved_from_sha, stash=auto_stash_ref)
+ # 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 = _switch_branch_at_commit_point(
+ git_cmd, branch, target_ref, pre=moved_from_sha, stash=auto_stash_ref)
if track_result.returncode != 0:
- _exit_after_failed_branch_switch(git_cmd, branch, track_result, auto_stash_ref, gw_input_fn)
+ _exit_after_failed_branch_switch(
+ git_cmd, branch, track_result, auto_stash_ref, gw_input_fn, _windows_gateway_resume)
prompt_for_restore = (
auto_stash_ref is not None
@@ -1412,14 +1438,16 @@ def _prepare_checkout_for_update(
pre_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
try:
upstream_checked = _m()._sync_with_upstream_if_needed(
- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)
+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn,
+ checkout_move=_moves_for(_windows_gateway_resume))
except UpstreamTargetBroken as broken: # nothing moved; local edits stay parked, like a rollback
if auto_stash_ref is not None:
print(f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})")
print(" Restore manually with: git stash apply")
_clear_pending_autostash()
_roll_back_broken_update(git_cmd, pre_sync_sha, broken.path, broken.error,
- header=_upstream_broken_header(broken))
+ header=_upstream_broken_header(broken),
+ _windows_gateway_resume=_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(
@@ -1524,9 +1552,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":
@@ -1551,8 +1580,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)
@@ -1656,15 +1685,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]
@@ -1673,8 +1704,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
@@ -1749,7 +1778,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,
@@ -1870,7 +1899,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_pause_gate.py b/hermes_cli/update_cmd_pause_gate.py
new file mode 100644
index 00000000000..1f19136047c
--- /dev/null
+++ b/hermes_cli/update_cmd_pause_gate.py
@@ -0,0 +1,72 @@
+"""The paused gateways' tree gate for the update's checkout-writing steps (Windows pause, #132338).
+
+``_checkout_move`` binds one git step (switch, merge, reset, upstream sync, rollback, stash, churn
+cleanup) to the pause record BEFORE git writes a file; ``update_cmd`` re-exports these names.
+"""
+
+from contextlib import contextmanager
+
+from hermes_cli import update_pause_record as _pause_record
+
+
+@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})