Skip to content

The agent that grows with you

fix(update): a failed later tree move owes the restart for the HEAD it settled on

Teknium56fa24ab6f03
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 2348c122c45..92498d69da0 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -980,6 +980,7 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
if rollback_result.stderr.strip():
print(f" ({rollback_result.stderr.strip().splitlines()[0]})")
if interrupted_pull_marker(root).is_file():
+ _commit.owe_restore_of(root, pre_pull_sha)
print(f" The next `hermes` launch also finishes the rollback to {pre_pull_sha[:10]} on its own.")
else:
print(" Could not capture pre-pull SHA — recover manually with:")
@@ -1072,10 +1073,13 @@ def _pull_updates(
raise # Ctrl-C reached git too (same process group): the tree may be torn, keep the marker
except BaseException:
# 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)):
+ # put back what it wrote; the marker stays until the tree is verified whole. Settled:
+ # handed back at the run's start, else owed for the HEAD it settled on; torn: owed for
+ # the commit the next launch's restore lands on.
+ if _commit.settle_failed_tree_move(_m().PROJECT_ROOT):
_commit.disarm_commit_obligations()
+ else:
+ _commit.owe_restore_of(_m().PROJECT_ROOT, pre_pull_sha)
raise
pull_marker.unlink(missing_ok=True) # git exited 0: the tree is whole at the target
if sync_upstream:
@@ -1133,6 +1137,7 @@ def _switch_branch_at_commit_point(git_cmd, branch, target_ref, *, pre, stash):
if not target:
if args is attempts[0][0]:
continue # no local branch: only the -B form can land on it
+ _commit.disarm_commit_obligations() # an earlier attempt's arm, its move settled
return _git_run(git_cmd, args) # unresolvable: git fails before touching the tree
# Owe what this attempt lands on: a stop before CP1 must be dischargeable at *target*
# (CP1 retargets the obligation before its own move).
@@ -1144,15 +1149,19 @@ def _switch_branch_at_commit_point(git_cmd, branch, target_ref, *, pre, stash):
except KeyboardInterrupt:
raise
except BaseException:
- _commit.settle_failed_tree_move(root)
+ if _commit.settle_failed_tree_move(root):
+ _commit.disarm_commit_obligations()
+ else:
+ _commit.owe_restore_of(root, pre)
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):
+ _commit.owe_restore_of(root, pre) # owed for what the next launch's restore lands on
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()
+ # Back at *pre*: handed back at the run's start commit, else re-owed for the HEAD it is on.
+ _commit.disarm_commit_obligations()
return result
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
index e8e9d015733..de12137c0ee 100644
--- a/hermes_cli/update_cmd_commit.py
+++ b/hermes_cli/update_cmd_commit.py
@@ -15,6 +15,7 @@ this run found them once the tree is verified at its pre-update commit again.
from __future__ import annotations
+import logging
import os
import subprocess
import sys
@@ -35,6 +36,7 @@ from hermes_cli._early_recovery import (
)
from hermes_cli.update_custody import run_git
+logger = logging.getLogger("hermes_cli.update_cmd")
# What this run found before it armed anything: {path: bytes or None}. None = nothing armed yet.
_armed_snapshot: Optional[dict[Path, Optional[bytes]]] = None
# What this run's latest arm left at each path: disarm hands back only records still exactly these.
@@ -95,15 +97,19 @@ def arm_commit_obligations(root: Path, expected_sha: str) -> None:
def disarm_commit_obligations() -> None:
"""Restore both obligations to what this run found: the tree never left its pre-update commit.
- Refused (obligations stay armed) unless HEAD is the commit this run STARTED from: a failed later
- move (the upstream fork ff after a committed origin pull) is put back to a commit that is
- already new code, and that tree still owes its tail.
+ Off the commit this run STARTED from nothing is handed back: a failed later move (CP1 refused
+ or failed after the CP0 branch switch, the upstream fork ff after the origin pull) settles on a
+ commit that is already new code, so the obligations are owed for THAT head instead of the
+ failed move's target, which the checkout does not contain and no restart could discharge.
"""
global _armed_snapshot
if _run_start is not None:
git_cmd, (start_head, _branch) = _run_start
root = Path(_obligation_root) if _obligation_root is not None else None
- if root is None or not start_head or head_and_branch(git_cmd, root)[0] != start_head:
+ head = head_and_branch(git_cmd, root)[0] if root is not None else ""
+ if root is None or not start_head or head != start_head:
+ if root is not None:
+ _owe_for(root, head)
return
snapshot, _armed_snapshot = _armed_snapshot, None
armed = dict(_armed_bytes)
@@ -126,6 +132,24 @@ def disarm_commit_obligations() -> None:
pass # an owed tail/restart left armed is a retry, never a lost obligation
+def owe_restore_of(root: Path, pre: str | None) -> None:
+ """A failed move left a torn tree under its marker: the next launch's restore puts ``pre`` back,
+ so the obligations name ``pre``, never the target the checkout will not hold."""
+ _owe_for(Path(root), pre or "")
+
+
+def _owe_for(root: Path, sha: str) -> None:
+ """Re-arm what this run armed for ``sha``, the commit the checkout is (or is restored) on."""
+ if _armed_snapshot is None or not is_object_id(sha):
+ return # nothing armed by this run, or nothing names the code: keep what stands
+ try:
+ arm_commit_obligations(root, sha)
+ except OSError as exc:
+ logger.warning("Could not re-arm the update obligations for %s: %s", sha[:10], exc)
+ print(f" ⚠ Could not record the restart this update still owes for {sha[:10]} ({exc}); "
+ "run `hermes gateway restart` once the update is done.", file=sys.stderr)
+
+
def commit_obligations_armed() -> bool:
return _armed_snapshot is not None
@@ -141,6 +165,11 @@ def arm_commit_point(git_cmd, root: Path, expected_sha: str, **move) -> str | No
arm_tree_move(git_cmd, root, **move)
except OSError as exc:
disarm_commit_obligations()
+ head = head_and_branch(git_cmd, root)[0] if _run_start is not None else ""
+ if head and head != _run_start[1][0]:
+ # A later move (CP1 after the CP0 switch): THIS step moved nothing, an earlier one did.
+ return (f"could not arm the update ({exc}); this step changed nothing, but an earlier step "
+ f"of this update already moved the checkout to {head[:10]}")
return f"could not arm the update ({exc}); the checkout was not changed"
return None
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index 16550fcc037..6c9bfce5b8c 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -411,8 +411,12 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
# 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
+ from hermes_cli._early_recovery import interrupted_pull_marker, is_object_id
pre = _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd)
+ if not is_object_id(pre):
+ # The marker's ``pre`` is what a killed move is restored to: never arm ``pre=``.
+ print(" ✗ Could not resolve HEAD. Skipping upstream sync.")
+ return False
target = upstream # the counted commit is the marker's target and the merge's (m2)
refused = _commit.arm_commit_point(git_cmd, cwd, target, pre=pre, target=target, stash=None)
try:
@@ -423,18 +427,17 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:
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 as exc:
+ except (OSError, subprocess.SubprocessError) as exc: # CustodyRefused is an OSError; a timeout too
if refused or _commit.settle_failed_tree_move(cwd):
- # Back at ``pre``; that is still new code when the origin pull moved first: owe the
- # restart for it again, not for ``target`` (disarm refuses then: it only hands
- # obligations back at the run's start commit).
- if pre and _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd) == pre:
- with suppress(OSError):
- _commit.arm_commit_obligations(cwd, pre)
+ # Back at ``pre``; that is still new code when the origin pull moved first, and disarm
+ # then owes the restart for it instead of ``target`` (it hands obligations back only at
+ # the run's start commit).
_commit.disarm_commit_obligations()
+ else:
+ _commit.owe_restore_of(cwd, pre) # torn under its marker: the restore lands on ``pre``
print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")
- if exc.stderr:
- print(f" ({exc.stderr})")
+ if detail := (getattr(exc, "stderr", None) or ("" if isinstance(exc, subprocess.CalledProcessError) else str(exc))):
+ print(f" ({detail})")
return False
interrupted_pull_marker(cwd).unlink(missing_ok=True)
print(" ✓ Updated from upstream")
diff --git a/tests/hermes_cli/test_update_commit_obligations.py b/tests/hermes_cli/test_update_commit_obligations.py
index da58423623f..9fea63068e2 100644
--- a/tests/hermes_cli/test_update_commit_obligations.py
+++ b/tests/hermes_cli/test_update_commit_obligations.py
@@ -8,6 +8,8 @@ tree at its start commit. The host record is shared by every install of the OS u
from __future__ import annotations
import os
+import shutil
+import subprocess
from pathlib import Path
import pytest
@@ -105,3 +107,53 @@ def test_disarm_never_writes_through_a_planted_restore_alias(root, tmp_path):
assert sentinel.read_text(encoding="utf-8-sig") == "PRECIOUS"
assert not host.is_symlink() and host.read_text(encoding="utf-8-sig") == "ORIGINAL"
+
+
+def _git(cwd: Path, *args: str) -> str:
+ env = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1",
+ "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "[email protected]"}
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True,
+ encoding="utf-8", env=env).stdout.strip()
+
+
[email protected](shutil.which("git") is None, reason="needs git")
+def test_a_refused_pull_after_the_branch_switch_owes_the_head_the_switch_landed_on(tmp_path, monkeypatch):
+ """CP0 switched a parked feature branch (X) to main (A); CP1's arm for B then failed. The
+ obligation used to stay on B, which the checkout at A never contains, while disarm refused
+ (HEAD != X): an undischargeable debt (review C1). It must name A, and the refusal must not
+ claim the checkout was untouched."""
+ import hermes_cli.main as hermes_main
+ from hermes_cli import update_cmd
+ from hermes_cli._early_recovery import interrupted_pull_marker
+ from hermes_cli.update_host_obligation import read_host_obligation
+
+ up, clone = tmp_path / "up", tmp_path / "clone"
+ up.mkdir()
+ _git(up, "init", "-q", "-b", "main")
+ (up / "f").write_text("A", encoding="utf-8")
+ _git(up, "add", "-A")
+ _git(up, "commit", "-qm", "A")
+ a = _git(up, "rev-parse", "HEAD")
+ _git(tmp_path, "clone", "-q", str(up), str(clone))
+ _git(clone, "checkout", "-q", "-b", "feat")
+ (clone / "g").write_text("X", encoding="utf-8")
+ _git(clone, "add", "-A")
+ _git(clone, "commit", "-qm", "X")
+ x = _git(clone, "rev-parse", "HEAD")
+ (up / "f").write_text("B", encoding="utf-8")
+ _git(up, "commit", "-qam", "B")
+ b = _git(up, "rev-parse", "HEAD")
+ _git(clone, "fetch", "-q", "origin")
+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", clone)
+ monkeypatch.setattr(commit, "_owns_live_checkout", lambda _root: False)
+ monkeypatch.chdir(clone)
+
+ commit.record_run_start(["git"], clone)
+ switched = update_cmd._switch_branch_at_commit_point(["git"], "main", "origin/main", pre=x, stash=None)
+ assert switched.returncode == 0 and _git(clone, "rev-parse", "HEAD") == a
+ interrupted_pull_marker(clone).mkdir() # CP1's marker cannot be written
+ reason = commit.arm_commit_point(["git"], clone, b, pre=a, target=b, stash=None)
+
+ assert reason and "the checkout was not changed" not in reason and a[:10] in reason
+ assert (read_host_obligation() or {}).get("expected_sha") == a
diff --git a/tests/hermes_cli/test_update_fork_sync_identity.py b/tests/hermes_cli/test_update_fork_sync_identity.py
index 180cb00a2ef..6dccb8d8105 100644
--- a/tests/hermes_cli/test_update_fork_sync_identity.py
+++ b/tests/hermes_cli/test_update_fork_sync_identity.py
@@ -138,3 +138,33 @@ def test_a_failed_upstream_sync_after_the_pull_owes_the_restart_for_the_pulled_c
update_cmd_commit.reset_for_tests()
assert _git(clone, "rev-parse", "HEAD") == commits[1]
assert (read_host_obligation() or {}).get("expected_sha") == commits[1]
+
+
+def test_a_custody_refused_upstream_merge_after_the_pull_still_owes_the_pulled_commit(tmp_path, monkeypatch, capsys):
+ """A merge refused by custody (CustodyRefused, an OSError) used to escape ``except
+ CalledProcessError`` with the obligation naming c2, which the checkout at c1 never holds
+ (review C1): it must settle like any failed merge and owe the restart for c1."""
+ from hermes_cli import update_cmd_commit, update_custody
+ from hermes_cli.update_host_obligation import read_host_obligation
+
+ clone, commits = _fork_behind_upstream(tmp_path, monkeypatch)
+ update_cmd_commit.reset_for_tests()
+ _git(clone, "reset", "-q", "--hard", commits[0])
+ update_cmd_commit.record_run_start(["git"], clone)
+ update_cmd_commit.arm_commit_obligations(clone, commits[1])
+ _git(clone, "reset", "-q", "--hard", commits[1]) # the committed origin pull
+ real = update_custody.run_git
+
+ def merge_refused(git_cmd, args, *rest, **kw):
+ if args[:1] == ["merge"]:
+ raise update_custody.CustodyRefused(["git"], "access denied")
+ return real(git_cmd, args, *rest, **kw)
+
+ monkeypatch.setattr(update_custody, "run_git", merge_refused)
+ try:
+ assert _sync_with_upstream_if_needed(["git"], clone, assume_yes=True) is False
+ finally:
+ update_cmd_commit.reset_for_tests()
+ assert "process job (access denied)" in capsys.readouterr().out
+ assert _git(clone, "rev-parse", "HEAD") == commits[1]
+ assert (read_host_obligation() or {}).get("expected_sha") == commits[1]