The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: every checkout-writing update step binds the paused gateways' tree gate first
Teknium9f2e21115695
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 8c8c68ebe06..2b04dfec4b6 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -6,7 +6,7 @@ main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at cal"""import logging-from contextlib import suppress+from contextlib import contextmanager, nullcontext, suppressimport osimport shleximport shutil # noqa: F401 (tests patch update_cmd.shutil.*; split modules resolve it here)@@ -902,7 +902,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_rsys.exit(1)-def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=None) -> None:+def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=None, _windows_gateway_resume=None) -> None:"""Post-pull syntax guard: roll back to *pre_pull_sha* and ``sys.exit(1)`` when a criticalfile no longer compiles (a bad admin-merge past CI must not brick the CLI)."""syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)@@ -926,13 +926,14 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=Nelse:rollback_args = ["reset", "--hard", pre_pull_sha]print(f"→ Rolling back to {rollback_branch if parked else pre_pull_sha[:10]}...")- rollback_result = _git_run(git_cmd, rollback_args)- if rollback_result.returncode != 0 and parked:- # The parked branch can be unavailable (e.g. checked out in another worktree): restore- # its commit detached so the install still boots the code it ran before.- print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")- rollback_args = ["checkout", "--detach", pre_pull_sha]+ with _checkout_move(_windows_gateway_resume, pre_pull_sha):rollback_result = _git_run(git_cmd, rollback_args)+ if rollback_result.returncode != 0 and parked:+ # The parked branch can be unavailable (e.g. checked out in another worktree): restore+ # its commit detached so the install still boots the code it ran before.+ print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")+ rollback_args = ["checkout", "--detach", pre_pull_sha]+ rollback_result = _git_run(git_cmd, rollback_args)if rollback_result.returncode == 0:print(" ✓ Rollback complete — your install is unchanged.")print(" Try ``hermes update`` again later once a fix lands.")@@ -960,6 +961,95 @@ def _update_movement_baseline(git_cmd, pre_pull_sha, pre_sync_sha, rollback_branreturn pre_sync_sha or pre_pull_sha+def _resolved_commit(git_cmd, ref: str) -> str:+ """The commit *ref* names now, or ``""`` when it names none."""+ return (_git_run(git_cmd, ["rev-parse", "-q", "--verify", f"{ref}^{{commit}}"]).stdout or "").strip()+++@contextmanager+def _checkout_move(token, *targets):+ """Run one checkout-writing git step (switch, merge, reset, upstream sync, rollback) with the+ paused gateways' tree gate bound to it BEFORE git writes a file: the commit(s) it can move to,+ on a baseline taken at the HEAD it starts from. Without that, a step git leaves half-written at+ an unmoved HEAD is judged against whatever refs a later fetch left, or against no baseline at+ all once an earlier step moved HEAD. A failed record write raises: the step must not run.++ The first step from the pause's own HEAD extends the pause's baseline (it knows the edits that+ were already there). A later step gets a baseline of its own, retired once git returns with+ HEAD moved or the tree exactly as the step found it, so a clean refusal never holds the set."""+ targets = sorted({t for t in targets if t})+ pause_id = (token or {}).get("pause_id")+ if not pause_id or not targets:+ yield+ return+ root = _pause_record.install_root()+ baselines = token.setdefault("baselines", [])+ head = _pause_record.head_sha(root)+ if any(b.get("pause_id") == pause_id and b.get("pre_sha") == head for b in baselines):+ for target in targets:+ _pause_record.mark_move(token, target)+ yield+ return+ # stamp_tree on a view sharing *token*'s list: the same HEAD + dirty-digest baseline, keyed per move.+ move_id = f"{pause_id}@{head}"+ _pause_record.stamp_tree({"pause_id": move_id, "baselines": baselines}, root)+ baseline = next((b for b in baselines if b.get("pause_id") == move_id), None)+ if baseline is None: # not a git checkout: no tree gate to bind+ yield+ return+ baseline["move_targets"] = sorted({*baseline.get("move_targets", []), *targets})+ found = {key: baseline.get(key) for key in ("pre_sha", "dirty_at_pause", "dirty_digests")}+ _pause_record.write({**token, "resume_needed": True})+ try:+ yield+ except Exception:+ _settle_checkout_move(token, move_id, found, root)+ raise+ _settle_checkout_move(token, move_id, found, root)+++def _settle_checkout_move(token: dict, move_id: str, found: dict, root) -> None:+ """Retire a returned step's baseline when git left nothing it could have torn: HEAD moved on,+ or HEAD, dirty paths and their bytes are exactly as the step found them."""+ now = _pause_record.stamp_tree({"pause_id": move_id, "baselines": []}, root)["baselines"][0]+ if now["pre_sha"] != found["pre_sha"] or all(now.get(key) == found[key] for key in found):+ token["baselines"] = [b for b in token["baselines"] if b.get("pause_id") != move_id]+ _pause_record.write({**token, "resume_needed": True})+++def _move_checkout_to(git_cmd, branch, merge_ref, pre_pull_sha) -> None:+ """The principal pull's one checkout move onto *merge_ref*; exits when it cannot be made."""+ # 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 merge_ref != f"origin/{branch}":+ # Keep detached local commits reachable, too. Named branches are+ # untouched by checkout --detach; an autostash protects dirty files.+ _park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)+ _git_run(git_cmd, ["checkout", "--detach", merge_ref], check=True)+ else:+ merge_result = _git_run(git_cmd, ["merge", "--ff-only", merge_ref])+ if merge_result.returncode != 0:+ ancestry = _git_run(+ git_cmd, ["merge-base", "--is-ancestor", "HEAD", merge_ref])+ if ancestry.returncode == 1:+ _reconcile_diverged_checkout(+ git_cmd, branch, pre_pull_sha, target_ref=merge_ref)+ else:+ print("✗ Fast-forward failed; refusing to reset because history divergence was not proven.")+ detail = (merge_result.stderr or merge_result.stdout or "").strip()+ if detail:+ print(f" {detail}")+ if ancestry.returncode == 0:+ print(f" HEAD is still an ancestor of {merge_ref}.")+ else:+ print(f" Could not verify whether HEAD is an ancestor of {merge_ref}.")+ ancestry_detail = (ancestry.stderr or ancestry.stdout or "").strip()+ if ancestry_detail:+ print(f" {ancestry_detail}")+ print(" Resolve the Git error and re-run `hermes update`; no reset was attempted.")+ sys.exit(1)++def _pull_updates(git_cmd, branch, auto_stash_ref, *, prompt_for_restore, gw_input_fn, discard_local_changes,keep_stash, target_ref=None, pre_sync_sha=None, rollback_branch=None, sync_upstream=False, assume_yes=False,@@ -987,36 +1077,8 @@ def _pull_updates(try:try:# The paused gateways' tree gate must know this move's target before git writes a file.- _pause_record.mark_move(_windows_gateway_resume, target_sha)- # 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 merge_ref != f"origin/{branch}":- # Keep detached local commits reachable, too. Named branches are- # untouched by checkout --detach; an autostash protects dirty files.- _park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)- _git_run(git_cmd, ["checkout", "--detach", merge_ref], check=True)- else:- merge_result = _git_run(git_cmd, ["merge", "--ff-only", merge_ref])- if merge_result.returncode != 0:- ancestry = _git_run(- git_cmd, ["merge-base", "--is-ancestor", "HEAD", merge_ref])- if ancestry.returncode == 1:- _reconcile_diverged_checkout(- git_cmd, branch, pre_pull_sha, target_ref=merge_ref)- else:- print("✗ Fast-forward failed; refusing to reset because history divergence was not proven.")- detail = (merge_result.stderr or merge_result.stdout or "").strip()- if detail:- print(f" {detail}")- if ancestry.returncode == 0:- print(f" HEAD is still an ancestor of {merge_ref}.")- else:- print(f" Could not verify whether HEAD is an ancestor of {merge_ref}.")- ancestry_detail = (ancestry.stderr or ancestry.stdout or "").strip()- if ancestry_detail:- print(f" {ancestry_detail}")- print(" Resolve the Git error and re-run `hermes update`; no reset was attempted.")- sys.exit(1)+ with _checkout_move(_windows_gateway_resume, target_sha):+ _move_checkout_to(git_cmd, branch, merge_ref, pre_pull_sha)except KeyboardInterrupt:raise # Ctrl-C reached git too (same process group): the tree may be torn, keep the markerexcept BaseException:@@ -1030,13 +1092,15 @@ def _pull_updates(git_cmd, branch, movement_baseline, in_place_update=in_place_update,_windows_gateway_resume=_windows_gateway_resume)_m()._sync_with_upstream_if_needed(- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn,+ checkout_move=lambda target: _checkout_move(_windows_gateway_resume, target))# Refuse an unexpected branch before syntax rollback can reset its ref._verify_head_after_pull(git_cmd, branch, movement_baseline, in_place_update=in_place_update,_windows_gateway_resume=_windows_gateway_resume)_rollback_if_pulled_syntax_error(- git_cmd, pre_sync_sha or pre_pull_sha, rollback_branch=rollback_branch)+ git_cmd, pre_sync_sha or pre_pull_sha, rollback_branch=rollback_branch,+ _windows_gateway_resume=_windows_gateway_resume)update_succeeded = Truefinally:if auto_stash_ref is not None:@@ -1149,9 +1213,12 @@ def _prepare_checkout_for_update(# Keep the running code AND its branch identity for syntax rollback.moved_from_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)rollback_branch = current_branch- track_result = _git_run(git_cmd, ["checkout", branch])- if track_result.returncode != 0:- track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])+ # The switch (or its -B fallback) is this update's first tree write: bind both commits first.+ with _checkout_move(_windows_gateway_resume, *(_resolved_commit(git_cmd, ref) for ref in (+ f"refs/heads/{branch}", f"origin/{branch}"))):+ track_result = _git_run(git_cmd, ["checkout", branch])+ if track_result.returncode != 0:+ track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])if track_result.returncode != 0:# Restore the stash before bailing so the user isn't stranded.if auto_stash_ref is not None:@@ -1211,7 +1278,8 @@ def _prepare_checkout_for_update(if commit_count == 0 and is_fork and branch == "main" and not release_tag:pre_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)upstream_checked = _m()._sync_with_upstream_if_needed(- git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn,+ checkout_move=lambda target: _checkout_move(_windows_gateway_resume, target))post_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)if pre_sync_sha and post_sync_sha and pre_sync_sha != post_sync_sha:synced_count = _count_commits_between(diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex dddc07304c6..8b5994a77cb 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -6,7 +6,7 @@ test patches on ``update_cmd`` stay effective)."""import logging-from contextlib import suppress+from contextlib import nullcontext, suppressimport subprocessimport sysfrom datetime import datetime, timedelta, timezone@@ -363,13 +363,17 @@ def _offer_upstream_remote(git_cmd: list[str], cwd: Path, *, assume_yes: bool, ireturn True-def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes: bool = False, input_fn=None) -> bool:+def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes: bool = False, input_fn=None,+ checkout_move=None) -> bool:"""Offer to add ``upstream``, compare origin/main vs upstream/main, ff-pull when strictly behind, then push origin.Returns True only when origin/main was actually verified against upstream/main; False when the check neverhappened, so the caller never reports "up to date" on an origin-only compare. Fetches only upstream/main:a bare fetch drags in thousands of auto-generated branches.+ ``checkout_move(target)`` is the caller's context for the one tree write (the merge): the+ paused gateways' tree gate is bound to *target* before git writes a file.+See #97052."""from hermes_cli.update_cmd import _count_commits_between, _has_upstream_remote, _no_prompt_git_kwargs, _should_skip_upstream_prompt@@ -408,7 +412,8 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:# 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.- run_git(git_cmd, ["merge", "--ff-only", upstream], cwd=cwd, check=True, **_no_prompt_git_kwargs())+ with (checkout_move or (lambda _target: nullcontext()))(upstream):+ run_git(git_cmd, ["merge", "--ff-only", upstream], cwd=cwd, check=True, **_no_prompt_git_kwargs())except subprocess.CalledProcessError:print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")return Falsediff --git a/tests/hermes_cli/test_update_pause_checkout_moves.py b/tests/hermes_cli/test_update_pause_checkout_moves.pynew file mode 100644index 00000000000..f172eb2d78f--- /dev/null+++ b/tests/hermes_cli/test_update_pause_checkout_moves.py@@ -0,0 +1,145 @@+"""Every checkout-writing step binds the paused gateways' tree gate first (#132338 R3, thread 5).++The Windows pause records what "the tree before this update" was, and the gate that lets paused+gateways start holds them while git may have left a half-written tree at an unmoved HEAD. Only the+principal pull recorded its target, so a failure in an EARLIER step (the switch onto an existing+local target branch, a fork's early upstream sync) was judged against whatever refs a later fetch+left, and a failure in a LATER step (the upstream sync after a successful pull) had no baseline at+its starting HEAD at all: both torn trees were admitted.++Real git (local repositories and a bare "upstream"), real update steps, real durable pause record+and gate. git's mid-move failure is real too: a read-only directory, as an unprivileged user.+"""++from __future__ import annotations++import os+import subprocess++import pytest++from hermes_cli import update_cmd+from hermes_cli import update_pause_record as pause_record++pytestmark = [+ pytest.mark.platforms("posix"),+ pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores read-only dirs"),+]+++def git(root, *args) -> str:+ return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, text=True).stdout.strip()+++def commit(root, message, **files) -> str:+ for name, text in files.items():+ path = root / name.replace("__", "/")+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ git(root, "add", ".")+ git(root, "commit", "-qm", message)+ return git(root, "rev-parse", "HEAD")+++def repo(tmp_path, monkeypatch):+ root = tmp_path / "checkout"+ root.mkdir()+ git(root, "init", "-q", "-b", "main")+ git(root, "config", "user.name", "Fixture")+ git(root, "config", "user.email", "[email protected]")+ monkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)+ monkeypatch.setattr(pause_record, "install_root", lambda: root)+ locked = root / "locked"+ yield root+ if locked.exists():+ locked.chmod(0o755)+++def pause(root) -> dict:+ token = pause_record.stamp_tree({"resume_needed": True, "profiles": {"default": 999999}}, root)+ pause_record.write(token)+ return token+++def gate(root) -> bool:+ """The verdict recovery reaches: the durable record, as the next launch reads it."""+ return pause_record.tree_is_whole(pause_record.read(pause_record.record_path())["token"], root)[0]+++def bare_upstream(root, tmp_path, tip) -> None:+ remote = tmp_path / "upstream.git"+ subprocess.run(["git", "clone", "-q", "--bare", str(root), str(remote)], check=True)+ git(remote, "update-ref", "refs/heads/main", tip)+ git(root, "remote", "add", "upstream", str(remote))+++def test_a_torn_first_branch_switch_stays_held_after_a_ref_only_fetch(repo):+ a = commit(repo, "A", **{"a.py": "A=1\n"})+ git(repo, "checkout", "-q", "-b", "feature") # parked on a merged branch: the update switches to main+ git(repo, "checkout", "-q", "main")+ b = commit(repo, "B", **{"a.py": "A=2\n"})+ git(repo, "update-ref", "refs/remotes/origin/main", b)+ git(repo, "checkout", "-q", "feature")+ git(repo, "branch", "-q", "-D", "main") # no local main: the switch falls back to `checkout -B`+ token = pause(repo)+ # `checkout -B` writes the tree, then creates the branch ref: an unwritable ref directory stops+ # it between the two, as a kill would (HEAD unmoved, the target's bytes already in the tree).+ (repo / ".git" / "refs" / "heads").chmod(0o555)+ try:+ with pytest.raises(SystemExit):+ update_cmd._prepare_checkout_for_update(+ ["git"], "main", "feature", is_fork=False, assume_yes=True, gateway_mode=False,+ gw_input_fn=None, switch_branch=False, _windows_gateway_resume=token)+ finally:+ (repo / ".git" / "refs" / "heads").chmod(0o755)+ assert git(repo, "rev-parse", "HEAD") == a and (repo / "a.py").read_text() == "A=2\n", "fixture: not torn"+ c = git(repo, "commit-tree", "-p", a, "-m", "C", git(repo, "rev-parse", f"{a}^{{tree}}"))+ git(repo, "update-ref", "refs/remotes/origin/main", c) # a later fetch: refs no longer reach a.py+ assert gate(repo) is False, "a torn switch was admitted once a fetch moved the refs"+++def test_a_torn_early_upstream_sync_stays_held_after_a_ref_only_fetch(repo, tmp_path):+ a = commit(repo, "A", **{"a.py": "A=1\n", "locked__z.py": "Z=1\n"})+ b = commit(repo, "B", **{"a.py": "A=2\n", "locked__z.py": "Z=2\n"})+ bare_upstream(repo, tmp_path, b)+ git(repo, "reset", "-q", "--hard", a)+ git(repo, "update-ref", "refs/remotes/origin/main", a) # the fork matches origin, trails upstream+ token = pause(repo)+ (repo / "locked").chmod(0o555)+ update_cmd._prepare_checkout_for_update(+ ["git"], "main", "main", is_fork=True, assume_yes=True, gateway_mode=False,+ gw_input_fn=None, switch_branch=False, _windows_gateway_resume=token)+ assert git(repo, "rev-parse", "HEAD") == a and (repo / "a.py").read_text() == "A=2\n", "fixture: not torn"+ git(tmp_path / "upstream.git", "update-ref", "refs/heads/main", a) # upstream moves on (here: back)+ git(repo, "fetch", "-q", "upstream", "+refs/heads/main:refs/remotes/upstream/main") # a later real fetch+ assert gate(repo) is False, "a torn upstream sync was admitted once a fetch moved the refs"++[email protected]("second_move", ["torn", "refused", "complete"])+def test_a_second_move_is_gated_from_the_head_the_first_one_reached(repo, tmp_path, second_move):+ commit(repo, "A", **{"a.py": "A=1\n", "locked__z.py": "Z=1\n", "notes.txt": "mine\n"})+ o = commit(repo, "O", **{"origin.py": "O=1\n"})+ # Refused: upstream also touches the user's file, which the user edits again after the update.+ edits = {"notes.txt": "upstream\n"} if second_move == "refused" else {}+ u = commit(repo, "U", **{"a.py": "A=2\n", "locked__z.py": "Z=2\n", "new.py": "N=1\n", **edits})+ bare_upstream(repo, tmp_path, u)+ git(repo, "reset", "-q", "--hard", "HEAD~2")+ git(repo, "update-ref", "refs/remotes/origin/main", o)+ (repo / "notes.txt").write_text("my edit\n", encoding="utf-8") # dirty before the update: unchanged bytes pass+ token = pause(repo)+ if second_move == "torn":+ (repo / "locked").chmod(0o555)+ elif second_move == "refused":+ (repo / "new.py").write_text("in the way\n", encoding="utf-8") # git refuses before writing a file+ update_cmd._pull_updates(+ ["git"], "main", None, prompt_for_restore=False, gw_input_fn=None, discard_local_changes=False,+ keep_stash=False, sync_upstream=True, assume_yes=True, _windows_gateway_resume=token)+ head = git(repo, "rev-parse", "HEAD")+ if second_move == "torn":+ assert head == o and (repo / "a.py").read_text() == "A=2\n", "fixture: not torn"+ assert gate(repo) is False, "the failed second move's torn tree was admitted at the first move's HEAD"+ else:+ assert head == (o if second_move == "refused" else u)+ (repo / "notes.txt").write_text("my later edit\n", encoding="utf-8") # life goes on after the update+ assert gate(repo) is True, "a move that left the tree whole held the paused set"