Skip to content

The agent that grows with you

fix(update): no tree move starts without its recovery marker and a resolved target (review F17, F22, F23, F24, F25, F29)

Tekniumf3dd812df661
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 5aaa46ce48f..c989d0bef26 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -28,7 +28,7 @@ from hermes_cli.update_channel import adopt_retired_channel
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._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 import update_cmd_check as _check
@@ -933,9 +933,12 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
# ``rollback=`` lets it redo the HEAD step when the kill came before it.
mode = "branch" if rollback_branch is None else "detach"
target_sha = _capture_head_sha(git_cmd, root)
- with _best_effort('Could not write the interrupted-pull marker: %s'):
- _commit.arm_tree_move(git_cmd, root, pre=pre_pull_sha, target=target_sha,
- stash=None, rollback=mode)
+ try:
+ _commit.arm_tree_move(git_cmd, root, pre=pre_pull_sha, target=target_sha, stash=None, rollback=mode)
+ except OSError as exc:
+ # 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]
@@ -1008,20 +1011,27 @@ def _pull_updates(
pull_marker = interrupted_pull_marker(_m().PROJECT_ROOT)
# A release update moves the tree to its tag, not the branch tip: the marker names what git writes.
merge_ref = target_ref if target_ref is not None else f"origin/{branch}"
- 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'):
- _commit.arm_tree_move(git_cmd, _m().PROJECT_ROOT, pre=pre_pull_sha, target=target_sha,
- stash=auto_stash_ref)
+ # Every refusal below runs inside the try: its finally names the autostash this run took.
try:
+ target_sha = (_git_run(git_cmd, ["rev-parse", "-q", "--verify", f"{merge_ref}^{{commit}}"]).stdout
+ or "").strip()
+ if not is_object_id(target_sha):
+ # The marker must name the commit git moves to, or a killed move is unrecoverable.
+ print(f"✗ Could not resolve {merge_ref} to a commit. No update was applied.")
+ sys.exit(1)
+ movement_baseline = _update_movement_baseline(
+ git_cmd, pre_pull_sha, pre_sync_sha, rollback_branch, target_sha)
+ if expected_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, the fleet restart and the marker are durable BEFORE git writes.
+ refused = _commit.arm_commit_point(git_cmd, _m().PROJECT_ROOT, target_sha, pre=pre_pull_sha,
+ target=target_sha, stash=auto_stash_ref)
+ if refused:
+ print(f"✗ {refused}.")
+ sys.exit(1)
try:
# merge --ff-only the already-fetched ref instead of `git pull`, which would do a
# SECOND network fetch; identical in effect given the fresh tracking ref.
@@ -1118,9 +1128,10 @@ def _switch_branch_at_commit_point(git_cmd, branch, target_ref, *, pre, stash):
if args is attempts[0][0]:
continue # no local branch: only the -B form can land on it
return _git_run(git_cmd, args) # unresolvable: git fails before touching the tree
- _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)
+ refused = _commit.arm_commit_point(git_cmd, root, resolve(target_ref) or target, pre=pre, target=target,
+ stash=stash)
+ if refused: # nothing moved: the caller restores the autostash and exits
+ return subprocess.CompletedProcess(args, 1, "", refused)
try:
result = _git_run(git_cmd, args)
except KeyboardInterrupt:
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
index 579c39e5743..fccb0b7541b 100644
--- a/hermes_cli/update_cmd_commit.py
+++ b/hermes_cli/update_cmd_commit.py
@@ -129,6 +129,21 @@ def commit_obligations_armed() -> bool:
return _armed_snapshot is not None
+def arm_commit_point(git_cmd, root: Path, expected_sha: str, **move) -> str | None:
+ """Arm the obligations, then the tree-move marker (``arm_tree_move(**move)``): no marker, no move.
+
+ ``None`` when both are durable; otherwise why not, with the obligations handed back
+ (``disarm_commit_obligations``), and the caller must stop before git writes a file.
+ """
+ try:
+ arm_commit_obligations(root, expected_sha)
+ arm_tree_move(git_cmd, root, **move)
+ except OSError as exc:
+ disarm_commit_obligations()
+ return f"could not arm the update ({exc}); the checkout was not changed"
+ return None
+
+
def arm_tree_move(git_cmd, root: Path, *, pre: str | None, target: str, stash: str | None,
rollback: str | None = None) -> Path:
"""Write the interrupted-pull marker for one git tree move (pre -> target).
@@ -277,8 +292,11 @@ def settle_failed_tree_move(root: Path) -> bool:
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``.
"""
+ marker = interrupted_pull_marker(Path(root))
+ if not marker.is_file():
+ return False # no marker names the move: its absence proves nothing about the tree
restore_interrupted_pull(Path(root), after_failure=True)
- return not interrupted_pull_marker(Path(root)).is_file()
+ return not marker.is_file()
def requires_other_python(pyproject: bytes | str | None) -> bool:
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index a15eb82e41b..3a6ffa24766 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -414,21 +414,23 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
from hermes_cli._early_recovery import interrupted_pull_marker
pre = _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd)
target = upstream # the counted commit is the marker's target and the merge's (m2)
- _commit.arm_commit_obligations(cwd, target)
- with suppress(OSError):
- _commit.arm_tree_move(git_cmd, cwd, pre=pre, target=target, stash=None)
+ refused = _commit.arm_commit_point(git_cmd, cwd, target, 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
# very commit counted above.
+ if refused:
+ raise subprocess.CalledProcessError(1, "merge", stderr=refused) # no marker, no move
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):
+ except subprocess.CalledProcessError as exc:
+ if refused or _commit.settle_failed_tree_move(cwd):
# Back at ``pre``; that is still new code when the origin pull moved first, and
# disarm refuses then (it only hands obligations back at the run's start commit).
_commit.disarm_commit_obligations()
print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")
+ if exc.stderr:
+ print(f" ({exc.stderr})")
return False
interrupted_pull_marker(cwd).unlink(missing_ok=True)
print(" ✓ Updated from upstream")
diff --git a/tests/hermes_cli/test_update_fork_sync_identity.py b/tests/hermes_cli/test_update_fork_sync_identity.py
index f090d05a110..68f57f363ae 100644
--- a/tests/hermes_cli/test_update_fork_sync_identity.py
+++ b/tests/hermes_cli/test_update_fork_sync_identity.py
@@ -70,3 +70,42 @@ def test_a_local_branch_named_upstream_main_never_changes_what_the_sync_counts_o
# The deferred fork push checks HEAD against the same remote-tracking commit, not the shadow.
_push_synced_fork(["git"], clone)
assert _git(origin, "rev-parse", "refs/heads/main") == commits[2]
+
+
+def _fork_behind_upstream(tmp_path, monkeypatch):
+ """A fork clone at c1 (origin/main) whose fetched upstream/main is c2; returns (clone, commits)."""
+ for name, value in _env(tmp_path).items():
+ if name.startswith("GIT_") or name == "HOME":
+ monkeypatch.setenv(name, value)
+ upstream = tmp_path / "upstream"
+ upstream.mkdir()
+ _git(upstream, "init", "-q", "-b", "main")
+ commits = []
+ for i in range(3):
+ (upstream / "f.txt").write_text(f"{i}\n", encoding="utf-8")
+ _git(upstream, "add", "f.txt")
+ _git(upstream, "commit", "-qm", f"c{i}")
+ commits.append(_git(upstream, "rev-parse", "HEAD"))
+ origin = tmp_path / "origin.git"
+ _git(tmp_path, "clone", "-q", "--bare", str(upstream), str(origin))
+ _git(origin, "update-ref", "refs/heads/main", commits[1])
+ clone = tmp_path / "clone"
+ _git(tmp_path, "clone", "-q", str(origin), str(clone))
+ _git(clone, "remote", "add", "upstream", str(upstream))
+ return clone, commits
+
+
+def test_an_upstream_sync_whose_marker_cannot_be_written_never_moves_the_tree(tmp_path, monkeypatch):
+ """The fork fast-forward is a tree move like the pull: no marker, no merge (F24)."""
+ from hermes_cli import update_cmd_commit
+ from hermes_cli._early_recovery import interrupted_pull_marker
+
+ clone, commits = _fork_behind_upstream(tmp_path, monkeypatch)
+ update_cmd_commit.reset_for_tests()
+ interrupted_pull_marker(clone).mkdir()
+ try:
+ assert _sync_with_upstream_if_needed(["git"], clone, assume_yes=True) is False
+ finally:
+ update_cmd_commit.reset_for_tests()
+ assert _git(clone, "rev-parse", "HEAD") == commits[1]
+ assert _git(clone, "status", "--porcelain", "--untracked-files=no") == ""
diff --git a/tests/hermes_cli/test_update_interrupted_pull.py b/tests/hermes_cli/test_update_interrupted_pull.py
index bb6716bc7ce..aa75ec49327 100644
--- a/tests/hermes_cli/test_update_interrupted_pull.py
+++ b/tests/hermes_cli/test_update_interrupted_pull.py
@@ -610,3 +610,97 @@ def test_a_refusal_whose_holder_exits_before_the_probe_retries_the_lock(tmp_path
assert held is not None and held["path"] == str(update_lock.checkout_lock_path(root)), \
"the repair ran without the checkout lock"
assert update_lock._HELD is None and len(calls) == 2
+
+
+def commit_point():
+ from hermes_cli import update_cmd_commit as commit
+
+ commit.reset_for_tests()
+ yield commit
+ commit.reset_for_tests()
+
+
+def _unmovable(root: Path, a: str) -> None:
+ assert _git(root, "rev-parse", "HEAD") == a
+ assert _git(root, "status", "--porcelain", "--untracked-files=no") == ""
+
+
+def test_a_pull_whose_marker_cannot_be_written_never_moves_the_tree(checkout, commit_point):
+ """No recovery marker, no move: a kill inside an unmarked merge leaves a torn tree no launch
+ can identify (F23, F17)."""
+ root, a, _b = checkout
+ er.interrupted_pull_marker(root).mkdir() # EISDIR stands in for ENOSPC/EROFS/a sharing violation
+
+ with pytest.raises(SystemExit):
+ _pull(root)
+
+ _unmovable(root, a)
+ assert not commit_point.commit_obligations_armed()
+
+
+def test_a_pull_whose_target_does_not_resolve_never_moves_the_tree(checkout, commit_point, monkeypatch):
+ """The marker must name the commit git moves to; an unresolved target is refused (F17)."""
+ root, a, _b = checkout
+ real = update_cmd._git_run
+
+ def no_rev_parse(git_cmd, args, *rest, **kw):
+ if args[:1] == ["rev-parse"] and any("origin/main" in arg for arg in args):
+ return subprocess.CompletedProcess(args, 128, "", "fatal: ambiguous argument")
+ return real(git_cmd, args, *rest, **kw)
+
+ monkeypatch.setattr(update_cmd, "_git_run", no_rev_parse)
+ with pytest.raises(SystemExit):
+ _pull(root)
+
+ _unmovable(root, a)
+
+
+def test_an_arm_failure_after_the_autostash_still_names_the_stash(checkout, commit_point, monkeypatch, capsys):
+ """An unwritable install state refuses the pull; the user is still told where their work is (F29)."""
+ root, _a, _b = checkout
+
+ def unwritable(*_args, **_kwargs):
+ raise OSError(28, "No space left on device")
+
+ monkeypatch.setattr(commit_point, "arm_commit_obligations", unwritable)
+ with pytest.raises((SystemExit, OSError)):
+ update_cmd._pull_updates(["git"], "main", "stash@{0}", prompt_for_restore=False, gw_input_fn=None,
+ discard_local_changes=False, keep_stash=False)
+
+ assert "stash@{0}" in capsys.readouterr().out
+
+
+def test_a_branch_switch_whose_marker_cannot_be_written_never_starts(checkout, commit_point):
+ """CP0 is a tree move like the pull: no marker, no checkout (F22)."""
+ root, a, _b = checkout
+ _git(root, "checkout", "-q", "-b", "feat")
+ er.interrupted_pull_marker(root).mkdir()
+
+ result = update_cmd._switch_branch_at_commit_point(["git"], "main", "origin/main", pre=a, stash=None)
+
+ assert result.returncode != 0
+ _unmovable(root, a)
+ assert _git(root, "rev-parse", "--abbrev-ref", "HEAD") == "feat"
+
+
+def test_an_unmarked_rollback_that_fails_never_reports_the_install_unchanged(checkout, commit_point, monkeypatch, capsys):
+ """The syntax rollback cannot refuse (the tree is already broken), but without a marker only a
+ tree verified whole at pre may be reported restored (F25)."""
+ root, a, b = checkout
+ _git(root, "reset", "-q", "--hard", b)
+ er.interrupted_pull_marker(root).mkdir()
+ monkeypatch.setattr(update_cmd, "_validate_critical_files_syntax", lambda _root: (False, "utils.py", "SyntaxError"))
+ real = update_cmd._git_run
+
+ def hard_reset_fails(git_cmd, args, *rest, **kw):
+ if args[:2] == ["reset", "--hard"]:
+ return subprocess.CompletedProcess(args, 1, "", "error: unable to unlink utils.py")
+ return real(git_cmd, args, *rest, **kw)
+
+ monkeypatch.setattr(update_cmd, "_git_run", hard_reset_fails)
+ with pytest.raises(SystemExit):
+ update_cmd._rollback_if_pulled_syntax_error(["git"], a)
+
+ out = capsys.readouterr().out
+ assert "Rollback complete" not in out and "Recover manually" in out