The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a file torn by the killed git is restored, not kept as a user edit
teknium19f835060d525
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 16f0fe18411..32d522868a6 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -238,30 +238,44 @@ def interrupted_pull_marker(root: Path) -> Path:def _paths_git_wrote(git, root: Path, pre: str, target: str) -> tuple[list[str], list[str]] | None:- """Paths the killed git already moved to ``target``: (restore from HEAD, delete as added).+ """Paths the killed git already touched on the way to ``target``: (restore from HEAD, delete as added).- Only a path whose content is exactly ``target``'s blob (or, for a deletion, that is gone) counts;- anything else is the user's own edit — e.g. a re-applied stash — and is left alone.+ Git rewrites a file as unlink, create, write, so a kill leaves it missing, empty or cut short:+ all of those count as git's, like the full ``target`` blob. Content that matches neither side and+ is not the start of the target is the user's own edit (e.g. a re-applied stash) and is left+ alone. ``None``: git no longer knows ``target``."""diff = git("diff", "--raw", "-z", "--no-renames", "--no-abbrev", pre, target)if diff.returncode != 0:return Noneparts = diff.stdout.split("\0")- entries = [] # (status, path, target blob)+ entries = [] # (status, path, pre mode, pre blob, target blob)for meta, path in zip(parts[::2], parts[1::2]):- old_mode, new_mode, _old_blob, new_blob, status = meta.lstrip(":").split()+ old_mode, new_mode, old_blob, new_blob, status = meta.lstrip(":").split()if status == "D" and old_mode in _REGULAR_FILE_MODES:- entries.append((status, path, None))+ entries.append((status, path, old_mode, old_blob, None))elif status != "D" and new_mode in _REGULAR_FILE_MODES:- entries.append((status, path, new_blob))- present = [path for _s, path, blob in entries if blob and (root / path).is_file()]+ entries.append((status, path, old_mode, old_blob, new_blob))+ present = [path for _s, path, _m, _o, blob in entries if blob and (root / path).is_file()]hashed = git("hash-object", "--stdin-paths", stdin="\n".join(present) + "\n") if present else Noneif hashed is not None and hashed.returncode != 0:- return None+ raise subprocess.SubprocessError(hashed.stderr.strip())worktree_blob = dict(zip(present, hashed.stdout.split() if hashed else ()))restore, added = [], []- for status, path, blob in entries:- written = (not (root / path).exists()) if blob is None else worktree_blob.get(path) == blob+ for status, path, old_mode, old_blob, blob in entries:+ file = root / path+ if blob is None:+ written = not file.exists()+ elif path not in worktree_blob:+ written = status != "A" # unlinked, not yet recreated+ elif worktree_blob[path] not in (old_blob, blob): # git's own file, cut short, starts the target+ smudged = subprocess.run(["git", "-C", str(root), "cat-file", "--filters", f"--path={path}", blob],+ capture_output=True, check=True, timeout=120, stdin=subprocess.DEVNULL)+ written = smudged.stdout.startswith(file.read_bytes())+ elif old_blob == blob: # mode-only: only the exec bit tells whether git got here+ written = sys.platform != "win32" and bool(file.stat().st_mode & 0o100) != (old_mode == "100755")+ else:+ written = worktree_blob[path] == blobif written:(added if status == "A" else restore).append(path)return restore, added@@ -274,10 +288,10 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:half-written ones, so the caller must relaunch (``relaunch_after_restore``).Fast path (no marker) is one or two ``stat`` calls. Acts only when the marker's owner is gone,- HEAD is still the pre-pull commit and no merge/rebase is in progress; then every path whose- content is the pull target's returns to HEAD (the commit the venv was built for), so the install is- whole again and ``hermes update`` redoes the update from the start. Local edits are never touched;- the updater's autostash (if any) stays in ``git stash list``.+ HEAD is still the pre-pull commit and no merge/rebase is in progress; then every path git wrote+ (the target's content, or torn on the way there) returns to HEAD (the commit the venv was built+ for), so the install is whole again and ``hermes update`` redoes the update from the start. Local+ edits are never touched; the updater's autostash (if any) stays in ``git stash list``."""try:root = _project_root() if project_root is None else project_root@@ -308,7 +322,9 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:marker.unlink() # git finished (HEAD moved) or the marker is unusablereturn Falsewritten = _paths_git_wrote(git, root, pre, target)- if written is None:+ if written is None: # after a gc or re-clone: nothing left to compare against+ marker.unlink()+ print(f"⚠ Ignoring a stale interrupted-update marker: commit {target[:10]} is gone.", file=sys.stderr)return Falserestore, added = writtenif not restore and not added:diff --git a/tests/hermes_cli/test_update_interrupted_pull.py b/tests/hermes_cli/test_update_interrupted_pull.pyindex da898223265..394d8362635 100644--- a/tests/hermes_cli/test_update_interrupted_pull.py+++ b/tests/hermes_cli/test_update_interrupted_pull.py@@ -26,22 +26,26 @@ def _git(root: Path, *args: str) -> str:@pytest.fixturedef checkout(tmp_path, monkeypatch):- """An install at commit A whose fetched ``origin/main`` is B (modifies, deletes, adds a package)."""+ """An install at commit A whose fetched ``origin/main`` is B (modifies, deletes, adds, flips a mode)."""origin = tmp_path / "origin"origin.mkdir()_git(origin, "init", "-q", "-b", "main")_git(origin, "config", "user.email", "[email protected]")_git(origin, "config", "user.name", "t")- for name, body in {"utils.py": "OLD = 1\n", "other.py": "a = 1\n", "gone.py": "x = 1\n"}.items():+ files = {"utils.py": "OLD = 1\n", "other.py": "a = 1\n", "gone.py": "x = 1\n", "cut.py": "c = 1\n",+ "blank.py": "b = 1\n", "half.py": "h = 1\n", "tool.sh": "echo\n"}+ for name, body in files.items():(origin / name).write_text(body, encoding="utf-8", newline="")_git(origin, "add", "-A")_git(origin, "commit", "-qm", "A")- (origin / "utils.py").write_text("NEW = 1\n", encoding="utf-8", newline="")- (origin / "other.py").write_text("a = 2\n", encoding="utf-8", newline="")+ for name, body in {"utils.py": "NEW = 1\n", "other.py": "a = 2\n", "cut.py": "c = 2\n",+ "blank.py": "b = 2\n", "half.py": "h = 2 # long enough to span pages\n"}.items():+ (origin / name).write_text(body, encoding="utf-8", newline="")(origin / "gone.py").unlink()(origin / "newpkg").mkdir()(origin / "newpkg" / "__init__.py").write_text("from utils import NEW\n", encoding="utf-8", newline="")_git(origin, "add", "-A")+ _git(origin, "update-index", "--chmod=+x", "tool.sh")_git(origin, "commit", "-qm", "B")root = tmp_path / "install"_git(tmp_path, "clone", "-q", str(origin), str(root))@@ -55,36 +59,47 @@ def _pull(root: Path) -> None:discard_local_changes=False, keep_stash=False)-def _kill_mid_pull(root: Path, monkeypatch) -> None:- """The fast-forward writes one new file, holds index.lock, and the process dies."""+def test_killed_pull_is_restored_on_next_launch_and_update_reruns(checkout, monkeypatch):+ root, a, b = checkoutreal = update_cmd._git_run- def dying_git_run(git_cmd, args, *a, **kw):+ def dying_git_run(git_cmd, args, *rest, **kw):if args[:1] == ["merge"]:+ # Git rewrites a file as unlink, create, write: the kill lands inside one of those.(root / "utils.py").write_text("NEW = 1\n", encoding="utf-8", newline="")+ (root / "cut.py").unlink()+ (root / "blank.py").write_bytes(b"")+ (root / "half.py").write_bytes(b"h = 2 # long") # a multi-page write cut short(root / "newpkg").mkdir()(root / "newpkg" / "__init__.py").write_text("from utils import NEW\n", encoding="utf-8", newline="")(root / ".git" / "index.lock").touch()raise KeyboardInterrupt # SIGKILL: nothing after this line of the updater runs- return real(git_cmd, args, *a, **kw)+ return real(git_cmd, args, *rest, **kw)monkeypatch.setattr(update_cmd, "_git_run", dying_git_run)with pytest.raises(KeyboardInterrupt):_pull(root)monkeypatch.setattr(update_cmd, "_git_run", real)---def test_killed_pull_is_restored_on_next_launch_and_update_reruns(checkout, monkeypatch):- root, a, b = checkout- _kill_mid_pull(root, monkeypatch)- assert _git(root, "rev-parse", "HEAD") == a # the torn state: HEAD old, utils + newpkg already new+ assert _git(root, "rev-parse", "HEAD") == a # the torn state: HEAD old, some files already newmarker = er.interrupted_pull_marker(root)- # A retry in a container gets the killed updater's pid: our own pid is never a live owner.recorded = marker.read_text(encoding="utf-8")assert f"pid={os.getpid()}" in recorded and f"target={b}" in recorded # the commit, not the ref name# The user re-applies their stash to a file the update also changes (git had not written it yet).(root / "other.py").write_text("a = 1 # my edit\n", encoding="utf-8", newline="")+ # Another `hermes` launched while an update is mid-pull must not race its git.+ updater = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ marker.write_text(recorded.replace(f"pid={os.getpid()}", f"pid={updater.pid}"), encoding="utf-8",+ newline="")+ assert er.restore_interrupted_pull(root) is False+ assert marker.exists() and (root / ".git" / "index.lock").exists()+ finally:+ updater.kill()+ updater.wait()++ # A retry in a container gets the killed updater's pid: our own pid is never a live owner.+ marker.write_text(recorded, encoding="utf-8", newline="")assert er.restore_interrupted_pull(root) is True, "restored files mean the caller must relaunch"assert _git(root, "rev-parse", "HEAD") == a@@ -97,8 +112,8 @@ def test_killed_pull_is_restored_on_next_launch_and_update_reruns(checkout, monkassert _git(root, "rev-parse", "HEAD") == b and not marker.exists()-def test_failed_update_leaves_no_marker_and_restore_never_touches_user_work(checkout):- """sys.exit on a merge conflict is not a kill: nothing may be restored behind the user's back."""+def test_restore_never_touches_user_work_when_git_wrote_nothing(checkout):+ """sys.exit on a merge conflict is not a kill, and a marker git never acted on restores nothing."""root, a, b = checkout_git(root, "config", "user.email", "[email protected]")_git(root, "config", "user.name", "t")@@ -123,43 +138,10 @@ def test_failed_update_leaves_no_marker_and_restore_never_touches_user_work(checassert _git(root, "status", "--porcelain", "--untracked-files=all") == before_git(root, "reset", "-q", "--hard") # the user gives up on the merge(root / "utils.py").write_text("OLD = 1 # my stash, re-applied\n", encoding="utf-8", newline="")+ # tool.sh only changes mode upstream and git never reached it: nothing to restore, no relaunch.assert er.restore_interrupted_pull(root) is Falseassert (root / "utils.py").read_text(encoding="utf-8") == "OLD = 1 # my stash, re-applied\n"assert not marker.exists(), "git wrote nothing: the marker is spent"---def test_pull_marker_of_a_live_updater_is_left_alone(checkout, monkeypatch):- root, a, _b = checkout- _kill_mid_pull(root, monkeypatch)- marker = er.interrupted_pull_marker(root)- # Another `hermes` launched while an update is mid-pull must not race its git.- updater = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])- try:- live = marker.read_text(encoding="utf-8").replace(f"pid={os.getpid()}", f"pid={updater.pid}")- marker.write_text(live, encoding="utf-8", newline="")- assert er.restore_interrupted_pull(root) is False- finally:- updater.kill()- updater.wait()-- assert marker.exists() and (root / "newpkg" / "__init__.py").exists()- assert (root / ".git" / "index.lock").exists()---def test_main_restores_before_importing_anything_else_from_the_checkout():- """``hermes_cli.main`` itself may be one of the half-written files: the restore and relaunch run- before any other checkout module is imported."""- probe = (- "import sys\n"- "from hermes_cli import _early_recovery as er\n"- "er.restore_interrupted_pull = lambda: True\n"- "def relaunch():\n"- " print(','.join(sorted(m for m in sys.modules if m.split('.')[0] == 'hermes_cli'))); sys.exit(42)\n"- "er.relaunch_after_restore = relaunch\n"- "import hermes_cli.main\n"- )- root = Path(er.__file__).resolve().parent.parent- result = subprocess.run([sys.executable, "-c", probe], cwd=root, env={**os.environ, "PYTHONPATH": str(root)},- capture_output=True, text=True, encoding="utf-8", timeout=60)- assert result.returncode == 42, result.stderr- assert result.stdout.strip() == "hermes_cli,hermes_cli._early_recovery,hermes_cli.main"+ # A target git no longer knows (gc, re-clone) can never be compared against: drop the marker.+ marker.write_text(stale.replace(b, "0" * 40), encoding="utf-8", newline="")+ assert er.restore_interrupted_pull(root) is False and not marker.exists()