The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a historical updater's hand-off no longer dies on a missing ruamel
Teknium98649fd74f3e
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 3cbecb4c9e2..07c6c1bc688 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -643,7 +643,7 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Faexecutable = _git_executable()def git(*args: str, stdin: str | None = None, text: bool = True) -> subprocess.CompletedProcess:- return subprocess.run([executable, "--literal-pathspecs", "-C", str(root), *args], input=stdin,+ return subprocess.run([executable, "--literal-pathspecs", "-C", str(root), *args], input=stdin, cwd=str(root),capture_output=True, timeout=120, stdin=None if stdin is not None else subprocess.DEVNULL,**({"text": True, "encoding": "utf-8", "errors": "replace"} if text else {}))@@ -668,7 +668,10 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Fafile=sys.stderr)return False# A killed claim holder's own git child can still be writing; scanning under it reads half a tree.- if not _release_dead_index_lock(git_dir):+ # After a git that EXITED (``after_failure``) no git of ours is left: a lock now is another git's+ # (often the very reason ours failed), never ours to drop. The scan below only reads.+ foreign_lock = after_failure and (git_dir / "index.lock").exists()+ if not foreign_lock and not _release_dead_index_lock(git_dir):print("⚠ A running git holds the index after an interrupted `hermes update`; the next launch ""finishes the restore.", file=sys.stderr)return False@@ -678,6 +681,10 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Faprint(f"⚠ Ignoring a stale interrupted-update marker: commit {target[:10]} is gone.", file=sys.stderr)return Falserestore, added, new_dirs = written+ if (restore or added) and foreign_lock:+ print("⚠ Another git holds the index, so the files the update already wrote cannot be put back "+ "now; the next launch restores them.", file=sys.stderr)+ return Falseif restore or added:print(("⚠ git stopped partway through writing the new code — " if after_failure else"⚠ A previous `hermes update` was killed while git was writing the new code — ")diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.pyindex 16db8baafec..3f7b7d2920a 100644--- a/hermes_cli/_update_takeover.py+++ b/hermes_cli/_update_takeover.py@@ -2,9 +2,11 @@from __future__ import annotationsimport json+import osfrom pathlib import Pathimport subprocessimport sys+import timedef prepare(request: dict) -> tuple[Path, dict[str, str]]:@@ -64,10 +66,20 @@ def _arm_fleet_obligation(root: Path) -> None:head = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, encoding="utf-8",stdin=subprocess.DEVNULL, timeout=60)sha = head.stdout.strip() if head.returncode == 0 else ""- if sha: # an SHA-less record names no code the fleet could be proven current on- from hermes_cli.update_cmd_fleet import _write_fleet_restart_pending_marker-- _write_fleet_restart_pending_marker(expected_sha=sha)+ if not sha: # an SHA-less record names no code the fleet could be proven current on+ return+ # This runs in the HISTORICAL interpreter, before PM syncs the new dependencies: only stdlib-only+ # modules here (``update_cmd_fleet``'s writer imports ``update_cmd`` -> config -> ruamel, which a+ # release older than ruamel does not have).+ from hermes_cli.update_host_obligation import write_host_obligation++ if not write_host_obligation(expected_sha=sha):+ # Same fallback as ``update_cmd_fleet._write_fleet_restart_pending_marker``: the per-home+ # breadcrumb every reader still honours.+ from hermes_constants import get_hermes_home++ (get_hermes_home() / "fleet_restart_pending").write_text(+ f"started={time.time()}\npid={os.getpid()}\nexpected_sha={sha}\n", encoding="utf-8")def _record_failure(request: dict, result: Path, code: int, detail: str) -> None:diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 3f538b53788..c0a2f5df58a 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -932,9 +932,11 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N# writes, so the next launch's restore lands on pre_pull_sha, never on the broken commit;# ``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=_capture_head_sha(git_cmd, root),+ _commit.arm_tree_move(git_cmd, root, pre=pre_pull_sha, target=target_sha,stash=None, rollback=mode)+ 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 commitrollback_args = ["update-ref", "--no-deref", "HEAD", pre_pull_sha]rollback_result = _git_run(git_cmd, rollback_args)@@ -944,6 +946,8 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=Nif rollback_result.returncode == 0:rollback_args = ["reset", "--hard", pre_pull_sha]rollback_result = _git_run(git_cmd, rollback_args)+ if rollback_result.returncode == 0:+ _commit.drop_added_files(root, added)if rollback_result.returncode != 0 and _commit.settle_failed_tree_move(root):rollback_result = subprocess.CompletedProcess(rollback_args, 0, "", "") # restored in-processif rollback_result.returncode == 0 and parked:diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.pyindex 2534691586f..6d70dcadd5e 100644--- a/hermes_cli/update_cmd_commit.py+++ b/hermes_cli/update_cmd_commit.py@@ -118,6 +118,30 @@ def arm_tree_move(git_cmd, root: Path, *, pre: str | None, target: str, stash: sreturn marker+def files_added_by(git_cmd, root: Path, pre: str, target: str | None) -> list[str]:+ """Paths ``target`` adds over ``pre``. A rollback's mixed reset un-tracks them and ``reset --hard``+ never touches untracked files, so ``drop_added_files`` removes them by name afterwards."""+ if not target or target == pre:+ return []+ cp = subprocess.run([*git_cmd, "diff", "--name-only", "-z", "--no-renames", "--diff-filter=A", pre, target],+ cwd=str(root), capture_output=True, text=True, encoding="utf-8", errors="replace",+ stdin=subprocess.DEVNULL, timeout=120)+ return [p for p in cp.stdout.split("\0") if p] if cp.returncode == 0 else []+++def drop_added_files(root: Path, added: list[str]) -> None:+ """Every one is the move's own file: git refuses to move a checkout over an untracked file."""+ root = Path(root)+ for rel in added:+ (root / rel).unlink(missing_ok=True)+ for parent in sorted({p for rel in added for p in Path(rel).parents if str(p) != "."},+ key=lambda p: len(p.parts), reverse=True):+ try:+ (root / parent).rmdir() # only when empty: anything else inside keeps it+ except OSError:+ pass++def settle_failed_tree_move(root: Path) -> bool:"""Git exited without finishing a tree move: put back what it wrote, keep the marker if we can't.diff --git a/tests/e2e/core/upgrade/git/test_hostile_commit.py b/tests/e2e/core/upgrade/git/test_hostile_commit.pyindex fe35846a537..430a5e3fec6 100644--- a/tests/e2e/core/upgrade/git/test_hostile_commit.py+++ b/tests/e2e/core/upgrade/git/test_hostile_commit.py@@ -234,7 +234,10 @@ def _zip_killed_at(world, kill_at: str, files: dict[str, str] | None = None):def test_kill_mid_zip_swap_is_settled_by_the_next_launch(world):sb = world["sb"]pre = _head(sb)- killed = _zip_killed_at(world, "12")+ # Killed right after a TRACKED file's new bytes landed: the swap order follows the archive's+ # directory listing, so a "kill at the N-th swap" can land on N unchanged entries only.+ agents = I.git("show", "HEAD:AGENTS.md", cwd=world["origin"]) + "\n<!-- e2e zip swap -->\n"+ killed = _zip_killed_at(world, "after:AGENTS.md", {"AGENTS.md": agents})at_kill = {"artifacts": _artifacts(sb), "dirty": _tracked_dirty(sb),"new_entry": (sb.checkout / "e2e_zip_release.py").exists()}assert at_kill["artifacts"] and at_kill["dirty"], (diff --git a/tests/fixtures/resolution_allowlist.json b/tests/fixtures/resolution_allowlist.jsonindex dfdb7c2b45b..eb19295eed1 100644--- a/tests/fixtures/resolution_allowlist.json+++ b/tests/fixtures/resolution_allowlist.json@@ -119,6 +119,12 @@"symbol": "_spawn_detached_update","kind": "bare_which"},+ {+ "path": "hermes_cli/_early_recovery.py",+ "symbol": "_git_executable",+ "kind": "bare_which",+ "reason": "stdlib-only launch-time repair (runs from hermes_bootstrap before hermes_platform or app deps import); falls back to PM's staged git"+ },{"path": "hermes_cli/_subprocess_compat.py","symbol": "resolve_node_command",diff --git a/tests/hermes_cli/test_source_release_channels.py b/tests/hermes_cli/test_source_release_channels.pyindex caa6c2342d7..e8388b7441a 100644--- a/tests/hermes_cli/test_source_release_channels.py+++ b/tests/hermes_cli/test_source_release_channels.py@@ -125,10 +125,10 @@ def test_source_check_and_apply_land_on_selected_release(releases, monkeypatch,if start != "old":git(releases.root, "checkout", "-b", "my-work", releases.commits[3])if start == "local":- (releases.root / "my-work.txt").write_text("committed local work\n")+ (releases.root / "my-work.txt").write_text("committed local work\n", encoding="utf-8")git(releases.root, "add", ".")git(releases.root, "commit", "-m", "local work")- (releases.root / "notes.txt").write_text("uncommitted notes\n")+ (releases.root / "notes.txt").write_text("uncommitted notes\n", encoding="utf-8")branch_sha = git(releases.root, "rev-parse", "HEAD")set_install_channel(channel, releases.root)before = git(releases.root, "rev-parse", "HEAD")@@ -159,7 +159,7 @@ def test_source_check_and_apply_land_on_selected_release(releases, monkeypatch,if start != "old":assert git(releases.root, "rev-parse", "my-work") == branch_shaif start == "local":- assert (releases.root / "notes.txt").read_text() == "uncommitted notes\n"+ assert (releases.root / "notes.txt").read_text(encoding="utf-8") == "uncommitted notes\n"update_cmd._cmd_update_check()assert "Up to date with" in capsys.readouterr().out@@ -194,15 +194,16 @@ def test_zip_fallback_keeps_selected_repository_and_commit(releases, monkeypatchmonkeypatch.setattr(update_cmd_zip, "_abort_zip_update_if_dirty_tree", lambda: None)class DownloadBoundary(Exception):pass- def download(branch, url):- seen.append(url)+ def download(branch, url, target_sha=None):+ seen.append((url, target_sha))raise DownloadBoundarymonkeypatch.setattr(update_cmd_zip, "_download_and_swap_zip", download)with pytest.raises(DownloadBoundary):update_cmd_zip._update_via_zip(SimpleNamespace(branch=None), target_sha=releases.commits[2],target_repository="Fixture/hermes-agent", completion_request={})- assert seen == [f"https://github.com/Fixture/hermes-agent/archive/{releases.commits[2]}.zip"]+ assert seen == [(f"https://github.com/Fixture/hermes-agent/archive/{releases.commits[2]}.zip",+ releases.commits[2])]@pytest.mark.parametrize("git_cmd", [["git"], None], ids=["git", "no-git"])diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.pyindex 0b76375390d..1bb0457f9d4 100644--- a/tests/hermes_cli/test_update_target_identity.py+++ b/tests/hermes_cli/test_update_target_identity.py@@ -132,15 +132,12 @@ def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkeydef fault(command, *args, **kwargs):assert Path(command[0]).name.lower() in {'git', 'git.exe'} or command[0] == sys.executable, commandassert Path(kwargs['cwd']).resolve() in {t.clone, t.origin}, command- if 'merge' in command and _upstream_sha() in command: # the fork sync's local fast-forward- result = run(command, *args, **kwargs)- if case.startswith('fork-late'):- if case.endswith('wrong-branch'):- run(['git', 'checkout', '-qb', 'wrong'], cwd=t.clone, check=True, capture_output=True)- if case.endswith('reverted'):- run(['git', 'reset', '--hard', t.base], cwd=t.clone, check=True, capture_output=True)- return result- if 'merge' in command and '--ff-only' in command:+ # The upstream sync's tree move (`pull upstream main` on older updaters, a local merge of+ # the commit resolved from `refs/remotes/upstream/main` now, m2) vs the origin fast-forward.+ upstream_move = ('pull' in command or 'merge' in command) and (+ any(arg == 'upstream' or arg.startswith(('upstream/', 'refs/remotes/upstream/')) for arg in command)+ or ('merge' in command and _upstream_sha() in command))+ if 'merge' in command and '--ff-only' in command and not upstream_move:if case == 'no-move':return subprocess.CompletedProcess(command, 0, stdout='', stderr='')result = run(command, *args, **kwargs)@@ -150,6 +147,11 @@ def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkeyrun(['git', 'reset', '--hard', t.base], cwd=t.clone, check=True, capture_output=True)return resultresult = run(command, *args, **kwargs)+ if upstream_move and case.startswith('fork-late'):+ if case.endswith('wrong-branch'):+ run(['git', 'checkout', '-qb', 'wrong'], cwd=t.clone, check=True, capture_output=True)+ if case.endswith('reverted'):+ run(['git', 'reset', '--hard', t.base], cwd=t.clone, check=True, capture_output=True)if 'push' in command and 'origin' in command:pushes.append(result.returncode)return result@@ -457,7 +459,10 @@ def test_update_syntax_failure_restores_pre_update_head(update_tree, monkeypatchassert "checkout is on 'unexpected'" in outputassert 'Rolling back' not in outputelse:- assert 'Pulled code has a syntax error' in output+ # Origin's own target is refused before HEAD moves (the commit point's preflight); an+ # upstream sync's target is still caught by the post-pull guard and rolled back.+ assert ('The update target has a syntax error' if sync_phase == 'origin'+ else 'Pulled code has a syntax error') in outputassert git(t.clone, 'rev-parse', 'HEAD') == t.baseassert not (t.clone / 'hermes_cli' / 'config.py').exists()assert not git(t.clone, 'status', '--porcelain')