The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): keep the commit point's obligations and copies through failed later moves
Teknium26e3e2d55d52
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 65be3bd93af..eabe1da9dc2 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -552,6 +552,9 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:staging, old = Path(f"{dst}{_ZIP_STAGING_SUFFIX}"), Path(f"{dst}{_ZIP_OLD_SUFFIX}")try:if phase == "swapping":+ # Staging finished before this phase, so a backup now is the one the swap made+ # from the old entry: it existed, whatever an older journal recorded.+ existed = existed or old.exists()if existed and old.exists():if old.is_file() and not old.is_symlink() and not dst.is_dir():os.replace(old, dst) # a file entry never goes missing, not even here@@ -644,6 +647,11 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Facapture_output=True, timeout=120, stdin=None if stdin is not None else subprocess.DEVNULL,**({"text": True, "encoding": "utf-8", "errors": "replace"} if text else {}))+ rollback = fields.get("rollback", "").strip()+ if rollback in ("soft", "detach") and pre and target and git("rev-parse", "HEAD").stdout.strip() == target:+ # A syntax rollback killed before it moved HEAD back: redo that step (it writes no file), so+ # the restore below lands on ``pre`` (the code the update started from), not the broken tree.+ git(*(["reset", "--soft", pre] if rollback == "soft" else ["update-ref", "--no-deref", "HEAD", pre]))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 Falsediff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex caf752d0854..cba3a7f4dab 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -908,6 +908,9 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_rdef _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=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)."""+ pyproject = Path(_m().PROJECT_ROOT) / "pyproject.toml"+ if pyproject.is_file() and _commit.requires_other_python(pyproject.read_bytes()):+ return # a newer Python's syntax: this interpreter's compile() cannot judge itsyntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)if syntax_ok:return@@ -921,33 +924,41 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=Nif pre_pull_sha:# Restore the checkout the update left, never reset the update branch onto commits from# a parked feature branch or a detached checkout.+ root = _m().PROJECT_ROOTparked = rollback_branch not in (None, "HEAD")- if rollback_branch == "HEAD":- rollback_args = ["checkout", "--detach", pre_pull_sha]- elif rollback_branch:- rollback_args = ["checkout", rollback_branch]- else:- rollback_args = ["reset", "--hard", pre_pull_sha]print(f"→ Rolling back to {rollback_branch if parked else pre_pull_sha[:10]}...")+ # HEAD goes back FIRST, without writing a file, then the files follow. A kill anywhere in+ # between leaves HEAD on pre_pull_sha with the broken files reading as the move's own+ # 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 = "soft" if rollback_branch is None else "detach"+ head_step = (["reset", "--soft", pre_pull_sha] if mode == "soft"+ else ["update-ref", "--no-deref", "HEAD", pre_pull_sha])with _best_effort('Could not write the interrupted-pull marker: %s'):- _commit.arm_tree_move(git_cmd, _m().PROJECT_ROOT, pre=_capture_head_sha(git_cmd, _m().PROJECT_ROOT),- target=pre_pull_sha, stash=None)- 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]+ _commit.arm_tree_move(git_cmd, root, pre=pre_pull_sha, target=_capture_head_sha(git_cmd, root),+ stash=None, rollback=mode)+ rollback_args = head_step+ rollback_result = _git_run(git_cmd, head_step)+ if rollback_result.returncode == 0:+ rollback_args = ["reset", "--hard", pre_pull_sha]rollback_result = _git_run(git_cmd, rollback_args)+ if rollback_result.returncode != 0 and _commit.settle_failed_tree_move(root):+ rollback_result = subprocess.CompletedProcess(rollback_args, 0, "", "")+ else:+ interrupted_pull_marker(root).unlink(missing_ok=True) # nothing moved: still the pulled tree+ if rollback_result.returncode == 0 and parked:+ # Same commit, so only HEAD's name changes. The parked branch can be unavailable (e.g.+ # checked out in another worktree): its commit then stays checked out detached.+ if _git_run(git_cmd, ["checkout", rollback_branch]).returncode != 0:+ print(f" ✗ Could not check out {rollback_branch}; restoring its commit detached.")if rollback_result.returncode == 0:- interrupted_pull_marker(_m().PROJECT_ROOT).unlink(missing_ok=True)+ interrupted_pull_marker(root).unlink(missing_ok=True)_commit.disarm_commit_obligations() # back on the code this run started fromprint(" ✓ Rollback complete — your install is unchanged.")print(" Try ``hermes update`` again later once a fix lands.")else:- _commit.settle_failed_tree_move(_m().PROJECT_ROOT)print(" ✗ Rollback failed. Recover manually with:")- print(f" cd {_m().PROJECT_ROOT} && git {shlex.join(rollback_args)}")+ print(f" cd {root} && git {shlex.join(rollback_args)}")if rollback_result.stderr.strip():print(f" ({rollback_result.stderr.strip().splitlines()[0]})")else:@@ -1086,16 +1097,16 @@ def _switch_branch_at_commit_point(git_cmd, branch, target_ref, *, pre, stash):def resolve(ref):return (_git_run(git_cmd, ["rev-parse", "-q", "--verify", f"{ref}^{{commit}}"]).stdout or "").strip()- attempts = [(["checkout", branch], resolve(branch)),+ # --no-guess: with no local *branch* git would otherwise create it from origin/<branch> and+ # rewrite the tree while this loop believed the checkout could not move.+ attempts = [(["checkout", "--no-guess", branch], resolve(f"refs/heads/{branch}")),(["checkout", "-B", branch, f"origin/{branch}"], resolve(f"origin/{branch}"))]result = Nonefor args, target in attempts:if not target:- result = _git_run(git_cmd, args) # unresolvable: git fails before touching the tree- if result.returncode == 0:- interrupted_pull_marker(root).unlink(missing_ok=True)- return result- continue+ if args is attempts[0][0]:+ continue # no local branch: only the -B form can land on it+ return _git_run(git_cmd, args) # unresolvable: git fails before touching the tree_commit.arm_commit_obligations(root, resolve(target_ref) or target)with _best_effort('Could not write the interrupted-pull marker: %s'):_commit.arm_tree_move(git_cmd, root, pre=pre, target=target, stash=stash)@@ -1447,6 +1458,7 @@ def _verify_head_after_pull(print(" Reattach to the branch and retry: "f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update")+ _commit.disarm_commit_obligations() # nothing moved: no tail is owed (refused if HEAD did)_m()._resume_windows_gateways_after_update(_windows_gateway_resume)sys.exit(1)diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.pyindex 33d14cfe9c2..af63ad846b4 100644--- a/hermes_cli/update_cmd_commit.py+++ b/hermes_cli/update_cmd_commit.py@@ -25,8 +25,9 @@ from hermes_cli._early_recovery import interrupted_pull_marker, restore_interrup# What this run found before it armed anything: {path: bytes or None}. None = nothing armed yet._armed_snapshot: Optional[dict[Path, Optional[bytes]]] = None-# (git_cmd, (HEAD, branch)) when this run reached its checkout phase.+# (git_cmd, (HEAD, branch)) when this run reached its checkout phase, and the checkout it names._run_start: Optional[tuple[list, tuple[str, str]]] = None+_obligation_root: Optional[Path] = Nonedef _owns_live_checkout(root: Path) -> bool:@@ -74,15 +75,27 @@ def arm_commit_obligations(root: Path, expected_sha: str) -> None:def disarm_commit_obligations() -> None:- """Restore both obligations to what this run found: the tree never left its pre-update commit."""+ """Restore both obligations to what this run found: the tree never left its pre-update commit.++ Refused (obligations stay armed) unless HEAD is the commit this run STARTED from: a failed later+ move (the upstream fork ff after a committed origin pull) is put back to a commit that is+ already new code, and that tree still owes its tail.+ """global _armed_snapshot+ if _run_start is not None:+ git_cmd, (start_head, _branch) = _run_start+ root = Path(_obligation_root) if _obligation_root is not None else None+ if root is None or not start_head or head_and_branch(git_cmd, root)[0] != start_head:+ returnsnapshot, _armed_snapshot = _armed_snapshot, Nonefor path, data in (snapshot or {}).items():try:if data is None:path.unlink(missing_ok=True)else:- path.write_bytes(data)+ tmp = path.with_name(path.name + ".restore")+ tmp.write_bytes(data)+ os.replace(tmp, path)except OSError:pass # an owed tail/restart left armed is a retry, never a lost obligation@@ -91,11 +104,16 @@ def commit_obligations_armed() -> bool:return _armed_snapshot is not None-def arm_tree_move(git_cmd, root: Path, *, pre: str | None, target: str, stash: str | None) -> Path:- """Write the interrupted-pull marker for one git tree move (pre -> target)."""+def arm_tree_move(git_cmd, root: Path, *, pre: str | None, target: str, stash: str | None,+ rollback: str | None = None) -> Path:+ """Write the interrupted-pull marker for one git tree move (pre -> target).++ ``rollback`` (``soft``/``detach``): a syntax rollback that moves HEAD back to ``pre`` before any+ file; a kill before that step finds HEAD still on ``target`` and the restore redoes it first.+ """marker = interrupted_pull_marker(root)- marker.write_text(f"pid={os.getpid()}\npre={pre or ''}\ntarget={target}\nstash={stash or ''}\n",- encoding="utf-8")+ marker.write_text(f"pid={os.getpid()}\npre={pre or ''}\ntarget={target}\nstash={stash or ''}\n"+ + (f"rollback={rollback}\n" if rollback else ""), encoding="utf-8")return marker@@ -109,12 +127,43 @@ def settle_failed_tree_move(root: Path) -> bool:return not interrupted_pull_marker(Path(root)).is_file()+def requires_other_python(pyproject: bytes | str | None) -> bool:+ """True when a target's ``requires-python`` excludes the running interpreter.++ Its startup modules may then use a newer Python's syntax that this interpreter's ``compile()``+ cannot judge (PM provisions the required Python with the new code). Unknown -> False: keep+ checking, so a real syntax error is never waved through on a guess.+ """+ if not pyproject:+ return False+ import platform+ import re+ import tomllib++ try:+ text = pyproject.decode("utf-8") if isinstance(pyproject, bytes) else pyproject+ spec = tomllib.loads(text)["project"]["requires-python"]+ try:+ from packaging.specifiers import SpecifierSet+ except ImportError: # the lower bound is the part a Python bump moves+ floor = re.search(r">=\s*(\d+)\.(\d+)", spec)+ return bool(floor) and sys.version_info[:2] < (int(floor[1]), int(floor[2]))+ return not SpecifierSet(spec).contains(platform.python_version(), prereleases=True)+ except (KeyError, TypeError, ValueError): # TOMLDecodeError / InvalidSpecifier are ValueErrors+ return False++def target_syntax_error(git_cmd, root: Path, target_ref: str, relpaths) -> tuple[str, str] | None:"""``(path, error)`` for the first startup-critical file that does not compile at ``target_ref``.Read from the object store, never written to the tree: this runs BEFORE HEAD moves, so a brokenrelease is refused with the install untouched (the post-pull rollback stays as the backstop).+ Skipped for a target that requires a Python this interpreter is not (``requires_other_python``)."""+ pyproject = subprocess.run([*git_cmd, "show", f"{target_ref}:pyproject.toml"], cwd=str(root),+ capture_output=True, stdin=subprocess.DEVNULL, timeout=120)+ if pyproject.returncode == 0 and requires_other_python(pyproject.stdout):+ return Nonefor rel in relpaths:shown = subprocess.run([*git_cmd, "show", f"{target_ref}:{rel}"], cwd=str(root), capture_output=True,stdin=subprocess.DEVNULL, timeout=120)@@ -149,8 +198,9 @@ def checkout_untouched(git_cmd, root: Path, start: tuple[str, str] | None) -> bodef record_run_start(git_cmd, root: Path) -> None:- global _run_start+ global _run_start, _obligation_root_run_start = (list(git_cmd), head_and_branch(git_cmd, root))+ _obligation_root = Path(root)def run_checkout_untouched(root: Path) -> bool:@@ -185,6 +235,7 @@ def preflight_refusal(git_cmd, root: Path, target_ref: str, critical_files) -> sdef reset_for_tests() -> None:- global _armed_snapshot, _run_start+ global _armed_snapshot, _run_start, _obligation_root_armed_snapshot = None_run_start = None+ _obligation_root = Nonediff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex c8b75427eb0..961e6e9cd39 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -424,7 +424,9 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path, *, assume_yes:with (checkout_move or _no_move)(upstream):run_git(git_cmd, ["merge", "--ff-only", upstream], cwd=cwd, check=True, **_no_prompt_git_kwargs())except subprocess.CalledProcessError:- if _commit.settle_failed_tree_move(cwd) and _git_stdout(git_cmd, ["rev-parse", "HEAD"], cwd) == pre:+ if _commit.settle_failed_tree_move(cwd):+ # Back at ``pre``; that is still new code when the origin pull moved first, and+ # disarm refuses then (it only hands obligations back at the run's start commit)._commit.disarm_commit_obligations()print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.")return Falsediff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 5386839ddb9..16b0148e986 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -365,12 +365,17 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, tafrom hermes_cli import update_cmd_commit as _commitfrom hermes_cli.update_cmd import _UPDATE_CRITICAL_FILES, _m- # A previous run killed mid-swap: settle it before staging over its leftovers.+ # A previous run killed mid-swap: settle it before staging over its leftovers. A journal it could+ # not settle is that swap's only record: never overwrite it with this run's.restore_interrupted_zip_swap(root)+ if (root / ZIP_SWAP_JOURNAL).exists():+ raise RuntimeError("an interrupted ZIP update could not be settled; see the warning above")with zip_swap_owner_lock(root, wait=10.0) as owned:if not owned:raise RuntimeError("another `hermes update` is swapping this install right now")- journal_entries = [[item, os.path.lexists(os.path.join(root, item))] for item in entries]+ # A leftover backup counts: _stage_replacement puts it back as the entry before the swap.+ journal_entries = [[item, any(os.path.lexists(os.path.join(root, item + suffix))+ for suffix in ("", ".hermes-update-old"))] for item in entries]write_zip_swap_journal(root, "staging", journal_entries)try:staged = _stage_entries(extracted, entries, str(root))@@ -388,8 +393,11 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, taprint(" Files appeared in the checkout while the update was downloading; committing the swap would delete them.")print(_STASH_HINT)_m().sys.exit(1)- # Pre-commit gate: a target whose startup modules do not compile is refused untouched.- for rel in _UPDATE_CRITICAL_FILES:+ # Pre-commit gate: a target whose startup modules do not compile is refused untouched+ # (unless it requires a Python this interpreter is not: its syntax is not ours to judge).+ pyproject = Path(extracted, "pyproject.toml")+ newer_python = pyproject.is_file() and _commit.requires_other_python(pyproject.read_bytes())+ for rel in () if newer_python else _UPDATE_CRITICAL_FILES:path = os.path.join(extracted, *rel.split("/"))if os.path.isfile(path):with open(path, "rb") as handle:diff --git a/tests/e2e/core/upgrade/git/test_hostile_commit.py b/tests/e2e/core/upgrade/git/test_hostile_commit.pyindex dfc93cf58e2..9a91b72a9e5 100644--- a/tests/e2e/core/upgrade/git/test_hostile_commit.py+++ b/tests/e2e/core/upgrade/git/test_hostile_commit.py@@ -20,6 +20,15 @@ real git failure, and then judges the next real launch from the files the updatecode itself) aside and died before its replacement landed. The next launch must still restore.* ``syntax_error_target``: a release whose startup module does not compile is refused BEFOREHEAD moves (no fast-forward in the reflog), not merely rolled back afterwards.+* ``failed_upstream_sync_after_origin_pull``: a fork checkout whose origin pull already moved the+ tree, then the upstream fast-forward fails (read-only directory) and the updater is killed. The+ tail owed for the moved tree must survive the failed second move.+* ``kill_mid_zip_swap_over_leftover_backup``: the only copy of an entry is a leftover+ ``*.hermes-update-old`` the swap heals before swapping; a kill mid-swap must never delete both.+* ``kill_during_branch_switch_without_local_branch``: the parked checkout has no local ``main``+ (only ``origin/main``); git's checkout guess would create it and rewrite the tree unmarked.+* ``kill_during_syntax_rollback``: a broken release past the preflight is rolled back and the+ updater dies mid-rollback; the next launch must land on the pre-update commit, not the broken one."""from __future__ import annotations@@ -61,9 +70,9 @@ def world(tmp_path_factory, provider):sb, origin = P.install_head(root)P.configure(sb, provider.base_url)shim = sb.root / "wrap" / "git"- world = {"sb": sb, "origin": origin, "root": root, "shim": shim, "shim_text": shim.read_text(), "n": 0}+ world = {"sb": sb, "origin": origin, "root": root, "shim": shim, "shim_text": shim.read_text(encoding="utf-8-sig"), "n": 0}yield world- shim.write_text(world["shim_text"])+ shim.write_text(world["shim_text"], encoding="utf-8")def _hostile_git(world, body: str) -> None:@@ -71,7 +80,7 @@ def _hostile_git(world, body: str) -> None:updater process that spawned git)."""text = world["shim_text"]head, _, rest = text.partition("\n")- world["shim"].write_text(f'{head}\nREAL="{REAL_GIT}"\n{body}\n{rest}')+ world["shim"].write_text(f'{head}\nREAL="{REAL_GIT}"\n{body}\n{rest}', encoding="utf-8")def _release(world, files: dict[str, str]) -> str:@@ -89,7 +98,7 @@ def _tracked_dirty(sb) -> str:def _stamp_commit(sb) -> str:try:- return json.loads((sb.checkout / "install-stamp.json").read_text(encoding="utf-8")).get("commit") or ""+ return json.loads((sb.checkout / "install-stamp.json").read_text(encoding="utf-8-sig")).get("commit") or ""except (OSError, ValueError):return ""@@ -193,7 +202,10 @@ swaps, kill_at = [0], sys.argv[2]def killing(real):def move(src, dst):real(src, dst)- if kill_at == "hermes_cli-moved-aside": # the live package renamed away, its replacement not yet in+ if kill_at.startswith("after:"): # right after the named entry's replacement landed+ if os.path.basename(str(src)) == kill_at[6:] + ".hermes-update-staging":+ os.kill(os.getpid(), signal.SIGKILL)+ elif kill_at == "hermes_cli-moved-aside": # the live package renamed away, its replacement not yet inif os.path.basename(str(src)) == "hermes_cli" and str(dst).endswith(".hermes-update-old"):os.kill(os.getpid(), signal.SIGKILL)elif str(src).endswith(".hermes-update-staging"): # one entry swapped in@@ -206,10 +218,11 @@ z._download_and_swap_zip("main", sys.argv[1])"""-def _zip_killed_at(world, kill_at: str):+def _zip_killed_at(world, kill_at: str, files: dict[str, str] | None = None):"""A ZIP update of a fresh release, SIGKILLed at ``kill_at`` (N-th entry swapped in, or a named point)."""sb = world["sb"]- target = _release(world, {"e2e_zip_release.py": f"Z = {world['n']}\n", "hermes_cli/e2e_zip_marker.py": "M = 1\n"})+ target = _release(world, {"e2e_zip_release.py": f"Z = {world['n']}\n", "hermes_cli/e2e_zip_marker.py": "M = 1\n",+ **(files or {})})archive = world["root"] / f"release-{world['n']}.zip"I.git("archive", "--format=zip", "--prefix=hermes-agent-main/", "-o", str(archive), target, cwd=world["origin"])driver = world["root"] / "zip_driver.py"@@ -250,3 +263,110 @@ def test_kill_mid_zip_swap_with_hermes_cli_moved_aside_reaches_recovery(world):assert not _artifacts(sb) and _head(sb) == pre and not _tracked_dirty(sb), (f"left {_artifacts(sb)[:5]} / tracked changes {_tracked_dirty(sb)!r}\n" + I.describe(launch))P.ok(_update(sb), "the update after the restored swap failed")+++def test_failed_upstream_sync_after_origin_pull_keeps_the_tail_owed(world):+ """Fork checkout: the origin pull moves the tree (committed), then the upstream fast-forward fails+ on a read-only directory and is put back to the post-origin commit. That failure must not hand+ back the obligations the origin pull armed: a kill right after it still owes the tail."""+ sb, root = world["sb"], world["root"]+ first = _release(world, {"zzz_e2e_fork/mod.py": "V = 1\n"})+ P.ok(_update(sb), "harness: plain update to the first release failed")+ assert _head(sb) == first and _stamp_commit(sb) == first+ moved = _release(world, {"e2e_fork_origin.py": "B = 1\n"})+ upstream = root / "upstream.git"+ I.git("clone", "-q", "--bare", "--shared", str(world["origin"]), str(upstream), cwd=root)+ I.publish_commit(upstream, root, "upstream: touches the locked dir", {"zzz_e2e_fork/mod.py": "V = 2\n"})+ I.git("remote", "add", "upstream", str(upstream), cwd=sb.checkout)+ flag = sb.checkout / ".git" / "e2e-upstream-ff-failed"+ # Kill the updater at its next branch check once the upstream merge has failed (and been settled).+ _hostile_git(world, f'case " $* " in *" merge --ff-only upstream/main "*) "$REAL" "$@"; rc=$?; '+ f'[ $rc != 0 ] && touch "{flag}"; exit $rc;; esac\n'+ f'if [ -e "{flag}" ]; then case " $* " in *" rev-parse --abbrev-ref HEAD "*) '+ 'kill -KILL $PPID; exit 137;; esac; fi')+ locked = sb.checkout / "zzz_e2e_fork"+ locked.chmod(0o555)+ try:+ killed = _update(sb)+ finally:+ locked.chmod(0o755)+ _hostile_git(world, "")+ assert flag.exists() and killed.returncode != 0 and _head(sb) == moved and not _tracked_dirty(sb), (+ "harness: the upstream ff did not fail after the origin pull moved the tree\n" + I.describe(killed))+ owed = P.pending_marker(sb).exists()+ launch = _launch(sb, "first launch after a failed upstream sync")+ assert owed, ("the origin pull moved the tree but the failed upstream ff disarmed its owed tail\n"+ + P.diagnostics(sb, killed, launch))+ assert _stamp_commit(sb) == moved and not P.pending_marker(sb).exists(), (+ "the next launch did not finish the tail for the moved tree\n" + P.diagnostics(sb, killed, launch))+++def test_kill_mid_zip_swap_over_leftover_backup_keeps_the_entry(world):+ """A pre-journal crash left ``e2e_zip_lost.hermes-update-old`` as the ONLY copy of a tracked dir.+ The next swap heals it, swaps it, and is killed right after its replacement landed: recovery+ must put the old dir back, never drop both copies."""+ sb = world["sb"]+ pre = _release(world, {"e2e_zip_lost/m.py": "OLD = 1\n"})+ P.ok(_update(sb), "harness: plain update failed")+ lost = sb.checkout / "e2e_zip_lost"+ lost.rename(sb.checkout / "e2e_zip_lost.hermes-update-old")+ killed = _zip_killed_at(world, "after:e2e_zip_lost", {"e2e_zip_lost/m.py": "NEW = 1\n"})+ assert (lost / "m.py").read_text(encoding="utf-8-sig") == "NEW = 1\n" and (sb.checkout / "e2e_zip_lost.hermes-update-old").is_dir(), (+ "harness: the swap was not killed right after e2e_zip_lost landed\n" + I.describe(killed))+ launch = _launch(sb, "first launch after a kill over a leftover backup")+ assert (lost / "m.py").is_file() and (lost / "m.py").read_text(encoding="utf-8-sig") == "OLD = 1\n", (+ "recovery deleted both copies of an entry whose backup was healed before the swap: "+ f"{sorted(p.name for p in sb.checkout.iterdir() if p.name.startswith('e2e_zip'))}\n" + I.describe(launch))+ assert not _artifacts(sb) and _head(sb) == pre and not _tracked_dirty(sb), (+ f"left {_artifacts(sb)[:5]} / tracked changes {_tracked_dirty(sb)!r}\n" + I.describe(launch))+++def test_kill_during_branch_switch_without_local_branch_is_restored(world):+ """The parked checkout has no local ``main``: only ``origin/main``. Whichever checkout actually+ moves the tree to main must run under the marker."""+ sb = world["sb"]+ base = _head(sb)+ _release(world, {"e2e_dwim_a.py": "A = 1\n"})+ P.ok(_update(sb), "harness: plain update failed")+ I.git("checkout", "-q", "-b", "e2e-parked", base, cwd=sb.checkout)+ I.git("branch", "-q", "-D", "main", cwd=sb.checkout)+ parked = _head(sb)+ _release(world, {"e2e_dwim_c.py": "C = 1\n"})+ # Die after writing one of main's files, in the checkout that moves the tree: a local main+ # exists, `-B` was given, or git may guess (no --no-guess) and create main from origin/main.+ _hostile_git(world, 'case " $* " in *" checkout "*) case "${@: -1}" in main|origin/main) moves=0; '+ '"$REAL" rev-parse -q --verify refs/heads/main >/dev/null && moves=1; '+ 'case " $* " in *" -B "*) moves=1;; *" --no-guess "*) ;; *) moves=1;; esac; '+ 'if [ $moves = 1 ]; then "$REAL" show origin/main:e2e_dwim_a.py > e2e_dwim_a.py; '+ 'kill -KILL $PPID; exit 137; fi;; esac;; esac')+ killed = _update(sb)+ _hostile_git(world, "")+ assert (sb.checkout / "e2e_dwim_a.py").is_file() and _head(sb) == parked, (+ "harness: the kill did not land mid-switch\n" + I.describe(killed))+ launch = _launch(sb, "first launch after a kill during a guessed branch switch")+ assert _head(sb) == parked and not (sb.checkout / "e2e_dwim_a.py").exists(), (+ "a kill while git created main from origin/main left main's files in the parked checkout "+ "(no interrupted-pull marker)\n" + P.diagnostics(sb, killed, launch))+++def test_kill_during_syntax_rollback_lands_on_the_pre_update_commit(world):+ """A broken release the preflight cannot see (its ``git show`` is answered with the old file)+ is rolled back by the post-pull guard; the updater dies while ``reset --hard`` is writing the old+ files back. The next launch must finish on the pre-update commit, not restore the broken one."""+ sb = world["sb"]+ pre = _head(sb)+ constants = I.git("show", "main:hermes_constants.py", cwd=world["origin"])+ broken = _release(world, {"hermes_constants.py": constants + "\ndef broken(:\n",+ "e2e_rollback_extra.py": "X = 1\n"})+ _hostile_git(world, 'case " $* " in *" show "*":hermes_constants.py "*) "$REAL" show HEAD:hermes_constants.py; '+ 'exit $?;; *" reset --hard "*) "$REAL" show "${@: -1}:hermes_constants.py" > hermes_constants.py; '+ 'kill -KILL $PPID; exit 137;; esac')+ killed = _update(sb)+ _hostile_git(world, "")+ assert "syntax error" in (killed.stdout or "") + (killed.stderr or ""), (+ "harness: the post-pull guard did not fire\n" + I.describe(killed))+ assert (sb.checkout / "e2e_rollback_extra.py").exists(), "harness: the kill did not land mid-rollback\n" + I.describe(killed)+ launch = _launch(sb, "first launch after a kill during the syntax rollback")+ assert _head(sb) == pre and not _tracked_dirty(sb) and not (sb.checkout / "e2e_rollback_extra.py").exists(), (+ f"the launch after a kill mid-rollback did not land on {pre[:10]} (HEAD {_head(sb)[:10]}, broken "+ f"{broken[:10]}; tracked changes {_tracked_dirty(sb)!r})\n" + P.diagnostics(sb, killed, launch))diff --git a/tests/hermes_cli/test_update_post_pull_syntax_guard.py b/tests/hermes_cli/test_update_post_pull_syntax_guard.pyindex 76eba53d397..8324bf435b1 100644--- a/tests/hermes_cli/test_update_post_pull_syntax_guard.py+++ b/tests/hermes_cli/test_update_post_pull_syntax_guard.py@@ -34,7 +34,7 @@ def test_validate_critical_files_syntax_tolerates_missing_files(tmp_path):continuepath = tmp_path / relpathpath.parent.mkdir(parents=True, exist_ok=True)- path.write_text("# stub\n")+ path.write_text("# stub\n", encoding="utf-8")ok, failing_path, error = update_cmd._validate_critical_files_syntax(tmp_path)@@ -45,7 +45,7 @@ def test_validate_critical_files_syntax_tolerates_missing_files(tmp_path):def test_pull_rolls_back_broken_critical_file_and_accepts_corrected_retry(tmp_path, monkeypatch, capsys):def git(*args):- return subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True, text=True).stdout.strip()+ return subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True, text=True, encoding="utf-8").stdout.strip()git("init", "-b", "main")git("config", "user.email", "[email protected]")@@ -76,7 +76,7 @@ def test_pull_rolls_back_broken_critical_file_and_accepts_corrected_retry(tmp_paassert failure.value.code == 1assert "syntax error" in capsys.readouterr().outassert git("rev-parse", "HEAD") == previous- assert subprocess.run([sys.executable, str(source)], capture_output=True, text=True, check=True).stdout == "runnable\n"+ assert subprocess.run([sys.executable, str(source)], capture_output=True, text=True, encoding="utf-8", check=True).stdout == "runnable\n"git("reset", "--hard", "origin/main")source.write_text("print('corrected')\n", encoding="utf-8")@@ -86,4 +86,38 @@ def test_pull_rolls_back_broken_critical_file_and_accepts_corrected_retry(tmp_pagit("reset", "--hard", previous)assert pull() == previousassert git("rev-parse", "HEAD") == corrected- assert subprocess.run([sys.executable, str(source)], capture_output=True, text=True, check=True).stdout == "corrected\n"+ assert subprocess.run([sys.executable, str(source)], capture_output=True, text=True, encoding="utf-8", check=True).stdout == "corrected\n"+++def test_syntax_guards_skip_a_target_that_requires_a_newer_python(tmp_path, monkeypatch):+ """A release that bumps ``requires-python`` past this interpreter may use syntax only the new+ Python parses; compiling it here would refuse that release forever. A target this interpreter+ satisfies is still refused for the same file (real git object store, real worktree)."""+ from hermes_cli import update_cmd_commit as commit++ def git(*args):+ return subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True, text=True, encoding="utf-8").stdout.strip()++ git("init", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "Test")+ (tmp_path / "hermes_constants.py").write_text("def newer_syntax(:\n", encoding="utf-8")+ pyproject = tmp_path / "pyproject.toml"+ pyproject.write_text('[project]\nname = "x"\nrequires-python = ">=3.99"\n', encoding="utf-8")+ git("add", ".")+ git("commit", "-m", "requires a future python")+ newer = git("rev-parse", "HEAD")+ pyproject.write_text('[project]\nname = "x"\nrequires-python = ">=3.8"\n', encoding="utf-8")+ git("commit", "-am", "same file, this python")+ same = git("rev-parse", "HEAD")++ critical = ["hermes_constants.py"]+ assert commit.target_syntax_error(["git"], tmp_path, newer, critical) is None+ refused = commit.target_syntax_error(["git"], tmp_path, same, critical)+ assert refused is not None and refused[0] == "hermes_constants.py"++ # The post-pull backstop judges the worktree the same way (no rollback, no exit).+ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)+ git("checkout", "-q", newer)+ update_cmd._rollback_if_pulled_syntax_error(["git"], same)+ assert git("rev-parse", "HEAD") == newer