The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: the paused gateways' tree gate judges a moved HEAD against the commit it reached
Tekniumb3835f965655
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 2b04dfec4b6..81e559b796a 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -967,54 +967,59 @@ def _resolved_commit(git_cmd, ref: str) -> str:@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.+def _checkout_move(token, *targets, paths=()):+ """Run one checkout-writing git step (switch, merge, reset, upstream sync, rollback, stash) with+ the paused gateways' tree gate bound to it BEFORE git writes a file: the commit(s) it can move+ to and the tracked *paths* it rewrites in place (stash push/apply, ``reset --hard``,+ ``checkout -- <paths>``), 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."""+ were already there). A later step gets a baseline of its own, retired once git returns with the+ tree whole: HEAD moved and every file the move wrote holds the new commit, the tree exactly as+ the step found it, or the step reported ``whole`` on the dict this yields (a stash restore that+ applied cleanly changes the tree by design). A move is judged the moment git returns (see+ ``_settle_checkout_move``)."""+ step: dict = {}targets = sorted({t for t in targets if t})pause_id = (token or {}).get("pause_id")- if not pause_id or not targets:- yield+ root = _pause_record.install_root() if pause_id and (targets or paths) else None+ found = _pause_record.tree_state(root) if root else None+ if found is None: # nothing paused, nothing bound, or not a git checkout: no tree gate to bind+ yield stepreturn- 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")}+ move_id = f"{pause_id}@{found['pre_sha']}"+ baseline = next((b for b in baselines if b.get("pre_sha") == found["pre_sha"]+ and b.get("pause_id") in (pause_id, move_id)), None)+ if baseline is None:+ baseline = {"pause_id": move_id, **found}+ baselines.append(baseline)+ for key, bound in (("move_targets", targets), ("move_paths", paths)):+ if bound:+ baseline[key] = sorted({*baseline.get(key, []), *bound})_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})+ yield step+ finally:+ _settle_checkout_move(token, baseline, found, root, step)+++def _settle_checkout_move(token: dict, baseline: dict, found: dict, root, step: dict) -> None:+ """Record what the returned step left. A moved HEAD gets its verdict now: git can move HEAD+ past a file it failed to write, and only now are the move's paths untouched by later steps+ (dependency syncs, stash restores). A step's own baseline is retired when the tree is whole."""+ now = _pause_record.tree_state(root)+ moved = now["pre_sha"] != found["pre_sha"]+ torn = _pause_record.torn_by_move(root, found, now["dirty_at_pause"]) if moved else None+ if moved and torn is not None: # unknown stays unjudged: the gate judges it at resume time+ baseline.setdefault("landed", {})[now["pre_sha"]] = torn+ whole = torn == [] if moved else step.get("whole") or all(now[key] == found[key] for key in found)+ if baseline["pause_id"] != token["pause_id"] and whole:+ token["baselines"] = [b for b in token["baselines"] if b is not baseline]+ _pause_record.write({**token, "resume_needed": True})def _move_checkout_to(git_cmd, branch, merge_ref, pre_pull_sha) -> None:diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex 57690ed1974..3fb2c4d43d4 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -209,14 +209,21 @@ def stamp_tree(token: dict, root: Path | None = None) -> dict:root = root or install_root()pause_id = token.setdefault("pause_id", uuid.uuid4().hex)baselines = token.setdefault("baselines", [])- if (root / ".git").exists() and not any(b.get("pause_id") == pause_id for b in baselines):- dirty = tracked_changes(root)- # The bytes, not just the names: an autostashed edit and git's half-written bytes share a path.- baselines.append({"pause_id": pause_id, "pre_sha": head_sha(root), "dirty_at_pause": dirty,- "dirty_digests": {path: _digest(root / path) for path in dirty or []}})+ if not any(b.get("pause_id") == pause_id for b in baselines) and (state := tree_state(root)):+ baselines.append({"pause_id": pause_id, **state})return token+def tree_state(root: Path) -> dict | None:+ """HEAD, the tracked changes and their bytes now; ``None`` when *root* is not a git checkout."""+ if not (root / ".git").exists():+ return None+ dirty = tracked_changes(root)+ # The bytes, not just the names: an autostashed edit and git's half-written bytes share a path.+ return {"pre_sha": head_sha(root), "dirty_at_pause": dirty,+ "dirty_digests": {path: _digest(root / path) for path in dirty or []}}++def _digest(path: Path) -> str | None:try:return hashlib.sha256(path.read_bytes()).hexdigest()@@ -291,9 +298,36 @@ def _half_written(root: Path, changes: list[str], at_head: list[dict]) -> list[sunexpected = sorted(path for path in changes if not _seen_at_pause(root, baseline, path))if not unexpected:continue- targets = baseline.get("move_targets")- writable = _paths_between(root, targets) if targets else _paths_a_move_could_write(root)- torn = unexpected if writable is None else [path for path in unexpected if path in writable]+ # move_paths: files a step rewrote toward this HEAD (stash push/apply, reset, checkout --).+ targets, paths = baseline.get("move_targets"), baseline.get("move_paths")+ writable = _paths_between(root, targets) if targets else set() if paths else _paths_a_move_could_write(root)+ torn = unexpected if writable is None else [path for path in unexpected if path in {*writable, *(paths or ())}]+ if torn:+ return torn+ return []+++def torn_by_move(root: Path, found: dict, changes: list[str] | None) -> list[str] | None:+ """Paths a move from *found*'s HEAD to the current one wrote that do not hold the current+ commit's bytes: tracked changes on them that were not already there, byte for byte, when the+ move started. ``None`` when git cannot say."""+ writable = _paths_between(root, [found["pre_sha"]]) if found.get("pre_sha") else None+ if writable is None or changes is None:+ return None+ return sorted(path for path in changes if path in writable and not _seen_at_pause(root, found, path))+++def _landed_torn(root: Path, head: str, changes: list[str], landed: list[dict]) -> list[str]:+ """Tracked changes at a HEAD a recorded move reached that are not that commit's bytes. git can+ move HEAD past a file it failed to write (``checkout`` exits 0 after "unable to unlink old"),+ so a moved HEAD vouches for nothing by itself. The verdict the updater took the moment git+ returned stands while those paths stay changed: a later dependency sync or stash restore+ rewriting a file is not the move's doing. A move the updater died before judging is judged now."""+ for baseline in landed:+ verdict = (baseline.get("landed") or {}).get(head)+ if verdict is None:+ verdict = torn_by_move(root, baseline, changes)+ torn = list(changes) if verdict is None else [path for path in verdict if path in changes]if torn:return tornreturn []@@ -332,18 +366,23 @@ def tree_is_whole(token: dict, root: Path | None = None) -> tuple[bool, str]:head = head_sha(root)if head is None:return False, "the checkout HEAD is unreadable"- at_head = [b for b in token.get("baselines") or [] if b.get("pre_sha") == head]- if at_head:- # HEAD never moved for these pauses: a tracked change one of them did not see is git's- # half-written checkout. Each is judged on its own set — a killed run that moved HEAD- # elsewhere vouches for nothing here, and this run's set never certifies an older one's.+ baselines = token.get("baselines") or []+ at_head = [b for b in baselines if b.get("pre_sha") == head]+ # HEAD reached by a move these pauses recorded: judged against that commit's tree.+ landed = [b for b in baselines if b.get("pre_sha") != head+ and (head in (b.get("landed") or {}) or head in (b.get("move_targets") or []))]+ if at_head or landed:+ # HEAD never moved for the at_head pauses: a tracked change one of them did not see is+ # git's half-written checkout. Each is judged on its own set — a killed run that moved+ # HEAD elsewhere vouches for nothing here, and this run's set never certifies an older one's.changes = tracked_changes(root)if changes is None:return False, "git cannot read the checkout state"- torn = _half_written(root, changes, at_head)+ torn = _half_written(root, changes, at_head) or _landed_torn(root, head, changes, landed)if torn:return False, f"the checkout has {len(torn)} file(s) git left half-written (e.g. {torn[0]})"- return True, ""+ if at_head:+ return True, ""if _deps_hold_resume(root):return False, "dependencies are not current for the updated code yet"return True, ""diff --git a/tests/hermes_cli/test_update_pause_moved_head_gate.py b/tests/hermes_cli/test_update_pause_moved_head_gate.pynew file mode 100644index 00000000000..f7660beec20--- /dev/null+++ b/tests/hermes_cli/test_update_pause_moved_head_gate.py@@ -0,0 +1,100 @@+"""The paused gateways' tree gate judges a MOVED HEAD too (#132338 R3 follow-up).++``git checkout <existing branch>`` can exit 0 and move HEAD while leaving a file unwritten+("error: unable to unlink old ..."): the index and HEAD name the new commit, the file keeps the old+bytes. The gate used to judge only an unmoved HEAD, so that torn tree was admitted. Now the commit a+recorded move reached names the expected tree: its paths are judged the moment git returns (before+a dependency sync or stash restore rewrites one), or at resume time when the updater died first.++Real git, real update step, real durable record and gate; git's failure is a read-only directory.+"""++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 parked(tmp_path, monkeypatch):+ """Parked on a merged ``feature`` at A; local and origin ``main`` at B, which rewrites locked/z.py."""+ 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)+ a = commit(root, "A", **{"a.py": "A=1\n", "locked__z.py": "Z=1\n", "package-lock.json": "{}\n"})+ git(root, "branch", "-q", "feature")+ b = commit(root, "B", **{"a.py": "A=2\n", "locked__z.py": "Z=2\n", "package-lock.json": "{\"v\": 2}\n"})+ git(root, "update-ref", "refs/remotes/origin/main", b)+ git(root, "checkout", "-q", "feature")+ yield root, a, b+ (root / "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]++[email protected]("unlink_fails", [True, False])+def test_a_switch_that_moved_head_past_an_unwritten_file_stays_held(parked, unlink_fails):+ root, _a, b = parked+ token = pause(root)+ if unlink_fails:+ (root / "locked").chmod(0o555)+ 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)+ assert git(root, "rev-parse", "HEAD") == b, "fixture: the switch did not move HEAD"+ assert (root / "a.py").read_text() == "A=2\n"+ # Later, npm rewrites a lockfile the move also changed: not the move's doing.+ (root / "package-lock.json").write_text("{\"v\": 2, \"churn\": 1}\n", encoding="utf-8")+ if unlink_fails:+ assert (root / "locked" / "z.py").read_text() == "Z=1\n", "fixture: git wrote the file"+ assert gate(root) is False, "a moved HEAD whose tree is not its commit's was admitted"+ (root / "locked").chmod(0o755)+ git(root, "checkout", "--", "locked/z.py") # the user repairs it: the set may start+ assert gate(root) is True, "a switch that left the tree whole held the paused set"+++def test_a_move_the_updater_died_before_judging_is_judged_at_resume(parked):+ root, _a, b = parked+ token = pause(root)+ pause_record.mark_move(token, b) # recorded before git ran; the updater dies after git returns+ (root / "locked").chmod(0o555)+ git(root, "checkout", "-q", "main") # exits 0 with "unable to unlink old 'locked/z.py'"+ assert git(root, "rev-parse", "HEAD") == b and (root / "locked" / "z.py").read_text() == "Z=1\n"+ assert gate(root) is False, "an unjudged move to a recorded target was admitted torn"