The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): interrupted-pull restore never touches the user's own edits
teknium1f035bf872ec5
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 813e911fe83..16f0fe18411 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -211,36 +211,80 @@ def _marker_owner_is_live(marker: Path) -> bool:return False-# ``hermes update`` writes this into ``.git/`` right before git moves the checkout and removes it once-# git is done. Git rewrites the tree file by file and moves HEAD last, so an update killed in between-# leaves HEAD on the old commit with a prefix of the files already new; that mixed tree fails at import-# in every entry point, ``hermes update`` included. A marker whose owner is gone means exactly that.+# ``hermes update`` writes this into the git dir right before git moves the checkout and removes it+# once git has exited (a kill is the only exit that keeps it). Git rewrites the tree file by file and+# moves HEAD last, so an update killed in between leaves HEAD on the old commit with a prefix of the+# files already new; that mixed tree fails at import in every entry point, ``hermes update`` included.INTERRUPTED_PULL_MARKER = "hermes-update-pull"# A fast-forward takes seconds; past this a "live" owner pid is a recycled one._INTERRUPTED_PULL_MAX_AGE_SECONDS = 10 * 60+# The user (or a killed updater) is mid-operation: its own state files own the tree.+_GIT_OPERATION_IN_PROGRESS = ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply")+_REGULAR_FILE_MODES = ("100644", "100755")+++def _git_dir(root: Path) -> Path:+ """``root``'s git dir: ``.git`` itself, or where a linked worktree's ``.git`` file points."""+ dot_git = root / ".git"+ if dot_git.is_file():+ text = dot_git.read_text(encoding="utf-8").strip()+ if text.startswith("gitdir:"):+ return root / text[len("gitdir:"):].strip()+ return dot_gitdef interrupted_pull_marker(root: Path) -> Path:- return root / ".git" / INTERRUPTED_PULL_MARKER+ return _git_dir(root) / INTERRUPTED_PULL_MARKER+++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).++ 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.+ """+ diff = git("diff", "--raw", "-z", "--no-renames", "--no-abbrev", pre, target)+ if diff.returncode != 0:+ return None+ parts = diff.stdout.split("\0")+ entries = [] # (status, path, target blob)+ for meta, path in zip(parts[::2], parts[1::2]):+ 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))+ 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()]+ hashed = git("hash-object", "--stdin-paths", stdin="\n".join(present) + "\n") if present else None+ if hashed is not None and hashed.returncode != 0:+ return None+ 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+ if written:+ (added if status == "A" else restore).append(path)+ return restore, addeddef restore_interrupted_pull(project_root: Path | None = None) -> bool:- """Put back the files a killed ``hermes update`` had half-moved to the new commit. Never raises.+ """Put back the files a killed ``hermes update`` had half-moved to the new commit.Returns True when files were restored: modules this process already imported may be thehalf-written ones, so the caller must relaunch (``relaunch_after_restore``).- Fast path (no marker) is one ``stat``. Acts only when the marker's owner is gone and HEAD is still- the pre-pull commit: every path that differs between it and the pull target 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. Paths the update does not change keep any local edits; the updater's- autostash (if any) stays in ``git stash list``.+ 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``."""try:root = _project_root() if project_root is None else project_rootmarker = interrupted_pull_marker(root)if not marker.is_file() or _pytest_owns_live_checkout(root):return False+ git_dir = marker.parentfields = dict(line.partition("=")[::2] for line in marker.read_text(encoding="utf-8").splitlines())try:owner = int(fields.get("pid", ""))@@ -251,36 +295,33 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:if (owner != os.getpid() and _pid_is_running(owner)and time.time() - marker.stat().st_mtime < _INTERRUPTED_PULL_MAX_AGE_SECONDS):return False+ if any((git_dir / name).exists() for name in _GIT_OPERATION_IN_PROGRESS):+ return Falsedef git(*args: str, stdin: str | None = None) -> subprocess.CompletedProcess:return subprocess.run(["git", "--literal-pathspecs", "-C", str(root), *args], input=stdin,- capture_output=True, text=True, timeout=120,- stdin=None if stdin is not None else subprocess.DEVNULL)+ capture_output=True, text=True, encoding="utf-8", errors="replace",+ timeout=120, stdin=None if stdin is not None else subprocess.DEVNULL)pre, target = fields.get("pre", "").strip(), fields.get("target", "").strip()if not pre or not target or git("rev-parse", "HEAD").stdout.strip() != pre:marker.unlink() # git finished (HEAD moved) or the marker is unusablereturn False- diff = git("diff", "--name-status", "-z", "--no-renames", pre, target)- if diff.returncode != 0:+ written = _paths_git_wrote(git, root, pre, target)+ if written is None:return False- parts = diff.stdout.split("\0")- added = [p for s, p in zip(parts[::2], parts[1::2]) if s == "A"]- kept = [p for s, p in zip(parts[::2], parts[1::2]) if s and s != "A"]- # The dead git's index lock would refuse every command below.- (root / ".git" / "index.lock").unlink(missing_ok=True)- status = git("status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames")- dirty = {entry[3:] for entry in status.stdout.split("\0") if len(entry) > 3}- if status.returncode != 0 or dirty.isdisjoint(added + kept):- if status.returncode == 0:- marker.unlink() # the killed git never reached the tree: nothing to put back+ restore, added = written+ if not restore and not added:+ marker.unlink() # the killed git never reached the tree: nothing to put backreturn Falseprint("⚠ A previous `hermes update` was killed while git was writing the new code — "f"restoring the checkout to {pre[:10]}...", file=sys.stderr)+ # The dead git's index lock would refuse every command below.+ (git_dir / "index.lock").unlink(missing_ok=True)ok = True- if kept:+ if restore:ok = git("restore", "--source=HEAD", "--staged", "--worktree", "--pathspec-from-file=-",- "--pathspec-file-nul", stdin="\0".join(kept)).returncode == 0+ "--pathspec-file-nul", stdin="\0".join(restore)).returncode == 0if added and ok:ok = git("rm", "-q", "--cached", "--ignore-unmatch", "--pathspec-from-file=-","--pathspec-file-nul", stdin="\0".join(added)).returncode == 0@@ -298,8 +339,9 @@ def restore_interrupted_pull(project_root: Path | None = None) -> bool:return Trueprint(f" ✗ Could not restore it automatically. Recover with: git -C {root} reset --hard {pre}",file=sys.stderr)- except Exception:- pass # Never block launch — the import that follows surfaces the real error.+ except (OSError, subprocess.SubprocessError, ValueError) as exc:+ # Never block launch: the import that follows surfaces any real breakage.+ print(f"⚠ Could not check for an interrupted `hermes update`: {exc}", file=sys.stderr)return Falsediff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 01c4f0a2734..702742bd18c 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -868,17 +868,25 @@ def _pull_updates(# every user who ran ``hermes update`` for the 7 minutes between the bad commit and the fix landing).pre_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)# Git moves the tree file by file and HEAD last: if this process dies in between, the next launch- # of any entry point finds this marker and puts the old tree back (_early_recovery).+ # of any entry point finds this marker and puts the old tree back (_early_recovery). The target is+ # the resolved commit, so a later `git fetch` cannot widen what that restore considers.pull_marker = interrupted_pull_marker(_m().PROJECT_ROOT)+ target_sha = (_git_run(git_cmd, ["rev-parse", f"origin/{branch}^{{commit}}"]).stdout or "").strip()with _best_effort('Could not write the interrupted-pull marker: %s'):pull_marker.write_text(- f"pid={os.getpid()}\npre={pre_pull_sha}\ntarget=origin/{branch}\nstash={auto_stash_ref or ''}\n",+ f"pid={os.getpid()}\npre={pre_pull_sha}\ntarget={target_sha}\nstash={auto_stash_ref or ''}\n",encoding="utf-8")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.- if _git_run(git_cmd, ["merge", "--ff-only", f"origin/{branch}"]).returncode != 0:- _reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha)+ 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.+ if _git_run(git_cmd, ["merge", "--ff-only", f"origin/{branch}"]).returncode != 0:+ _reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha)+ except KeyboardInterrupt:+ raise # Ctrl-C reached git too (same process group): the tree may be torn, keep the marker+ except BaseException:+ pull_marker.unlink(missing_ok=True) # git exited on its own (sys.exit on conflict/reset failure)+ raisepull_marker.unlink(missing_ok=True) # git is done: the tree is whole again_rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha)update_succeeded = Truediff --git a/tests/hermes_cli/test_update_interrupted_pull.py b/tests/hermes_cli/test_update_interrupted_pull.pyindex 50b4485650a..da898223265 100644--- a/tests/hermes_cli/test_update_interrupted_pull.py+++ b/tests/hermes_cli/test_update_interrupted_pull.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport osimport subprocess+import sysfrom pathlib import Pathimport pytest@@ -20,7 +21,7 @@ from hermes_cli import update_cmddef _git(root: Path, *args: str) -> str:return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True,- text=True).stdout.strip()+ text=True, encoding="utf-8").stdout.strip()@pytest.fixture@@ -31,14 +32,15 @@ def checkout(tmp_path, monkeypatch):_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", "gone.py": "x = 1\n", "notes.md": "user file\n"}.items():- (origin / name).write_text(body)+ for name, body in {"utils.py": "OLD = 1\n", "other.py": "a = 1\n", "gone.py": "x = 1\n"}.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")+ (origin / "utils.py").write_text("NEW = 1\n", encoding="utf-8", newline="")+ (origin / "other.py").write_text("a = 2\n", encoding="utf-8", newline="")(origin / "gone.py").unlink()(origin / "newpkg").mkdir()- (origin / "newpkg" / "__init__.py").write_text("from utils import NEW\n")+ (origin / "newpkg" / "__init__.py").write_text("from utils import NEW\n", encoding="utf-8", newline="")_git(origin, "add", "-A")_git(origin, "commit", "-qm", "B")root = tmp_path / "install"@@ -59,8 +61,9 @@ def _kill_mid_pull(root: Path, monkeypatch) -> None:def dying_git_run(git_cmd, args, *a, **kw):if args[:1] == ["merge"]:+ (root / "utils.py").write_text("NEW = 1\n", encoding="utf-8", newline="")(root / "newpkg").mkdir()- (root / "newpkg" / "__init__.py").write_text("from utils import NEW\n")+ (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 runsreturn real(git_cmd, args, *a, **kw)@@ -73,32 +76,90 @@ def _kill_mid_pull(root: Path, monkeypatch) -> None:def test_killed_pull_is_restored_on_next_launch_and_update_reruns(checkout, monkeypatch):root, a, b = checkout- (root / "notes.md").write_text("edited while bricked\n") # a path the update never touches_kill_mid_pull(root, monkeypatch)- assert _git(root, "rev-parse", "HEAD") == a # the torn state: HEAD old, newpkg already new+ assert _git(root, "rev-parse", "HEAD") == a # the torn state: HEAD old, utils + newpkg 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.- assert f"pid={os.getpid()}" in marker.read_text()+ 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="")assert er.restore_interrupted_pull(root) is True, "restored files mean the caller must relaunch"assert _git(root, "rev-parse", "HEAD") == a- assert _git(root, "status", "--porcelain", "--untracked-files=all") == "M notes.md"+ assert _git(root, "status", "--porcelain", "--untracked-files=all") == "M other.py"+ assert (root / "other.py").read_text(encoding="utf-8") == "a = 1 # my edit\n", "the user's edit survives"assert not (root / "newpkg").exists() and not (root / ".git" / "index.lock").exists()assert not marker.exists()- (root / "notes.md").write_text("user file\n")+ (root / "other.py").write_text("a = 1\n", encoding="utf-8", newline="")_pull(root) # `hermes update` again: a normal fast-forwardassert _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."""+ root, a, b = checkout+ _git(root, "config", "user.email", "[email protected]")+ _git(root, "config", "user.name", "t")+ _git(root, "checkout", "-q", "-b", "mywork")+ (root / "other.py").write_text("a = 'mine'\n", encoding="utf-8", newline="")+ _git(root, "commit", "-qam", "local work that conflicts upstream")+ with pytest.raises(SystemExit):+ _pull(root)+ marker = er.interrupted_pull_marker(root)+ assert not marker.exists()++ # Even a leftover marker (an older updater, or a kill mid-reconcile) stays out of the user's way:+ # following the printed advice leaves a merge in progress, and edits git never wrote are theirs.+ stale = f"pid=0\npre={_git(root, 'rev-parse', 'HEAD')}\ntarget={b}\nstash=\n"+ marker.write_text(stale, encoding="utf-8", newline="")+ merge = subprocess.run(["git", "-C", str(root), "merge", "origin/main"],+ capture_output=True, text=True, encoding="utf-8")+ assert (root / ".git" / "MERGE_HEAD").exists(), merge.stdout + merge.stderr+ (root / "utils.py").write_text("OLD = 1 # resolved by hand\n", encoding="utf-8", newline="")+ before = _git(root, "status", "--porcelain", "--untracked-files=all")+ assert er.restore_interrupted_pull(root) is False+ assert _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="")+ assert er.restore_interrupted_pull(root) is False+ assert (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.- marker.write_text(marker.read_text().replace(f"pid={os.getpid()}", f"pid={os.getppid()}"))-- assert er.restore_interrupted_pull(root) is False+ 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"