The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the launch repair verifies the recorded git and retries a lock freed mid-refusal (m5, m10)
Tekniumceac89b92f38
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex eecb6671500..7c5e1f64885 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport contextlibimport errnoimport os+import reimport subprocessimport sysimport time@@ -256,7 +257,7 @@ def _git_executable(recorded_by_updater: str = "") -> str:"""import shutil- if recorded_by_updater and os.path.isfile(recorded_by_updater):+ if recorded_by_updater and os.path.isfile(recorded_by_updater) and _is_git(recorded_by_updater):return recorded_by_updaterfound = shutil.which("git")if found:@@ -277,6 +278,23 @@ def _git_executable(recorded_by_updater: str = "") -> str:return "git"+def _is_git(path: str) -> bool:+ """``path`` still runs as git: ``--version`` exits 0 and says ``git version`` (m5). A recorded+ git that decayed into anything else (gone executable, a stub that exits 0 silently) must not+ answer the repair's questions: its empty ``rev-parse`` would read as "HEAD moved"."""+ try:+ probe = subprocess.run([path, "--version"], capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=30, stdin=subprocess.DEVNULL,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ except (OSError, ValueError, subprocess.SubprocessError):+ return False+ return probe.returncode == 0 and probe.stdout.startswith("git version")+++# A full object name (SHA-1 or SHA-256): what `git rev-parse --verify HEAD` must print (m5).+_OID = re.compile(r"[0-9a-f]{40}(?:[0-9a-f]{24})?")++def _trees_git_could_write(git, pre: str, target: str) -> tuple[list[str], set[str]]:"""The trees the killed git was moving the checkout to, and the paths whose new content is unknowable.@@ -787,6 +805,10 @@ def _checkout_custody(root: Path):yield ""returnholder = update_lock._acquire_checkout(Path(root))+ if holder is not None and not update_lock.checkout_lock_held(Path(root)):+ # Refused, then free by the probe: its holder just exited. Take it now rather than run the+ # repair unguarded in that window (m10).+ holder = update_lock._acquire_checkout(Path(root))if holder is not None:if not update_lock.checkout_lock_held(Path(root)):# Not a holder but no lock at all (a git dir without working locks, e.g. NFS without@@ -840,12 +862,21 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Farollback = fields.get("rollback", "").strip()rollback = rollback if rollback in ("branch", "detach") else ""- head = git("rev-parse", "HEAD")- if head.returncode != 0:- print(f"⚠ Could not read HEAD to repair an interrupted `hermes update` ({head.stderr.strip()}); "+ def read_head() -> str | None:+ # Only a full object name is an answer: an empty or garbled one keeps the marker (m5).+ head = git("rev-parse", "HEAD")+ oid = head.stdout.strip() if head.returncode == 0 else ""+ if _OID.fullmatch(oid):+ return oid+ detail = head.stderr.strip() or f"git printed {oid!r}, exit {head.returncode}"+ print(f"⚠ Could not read HEAD to repair an interrupted `hermes update` ({detail}); ""the next launch retries.", file=sys.stderr)+ return None++ head = read_head()+ if head is None:return False- if rollback and pre and target and head.stdout.strip() == target:+ if rollback and pre and target and head == target:# A syntax rollback killed before it moved HEAD back: redo that step (HEAD and index, no file),# so the restore below lands on ``pre`` (the code the update started from), not the broken tree.# Every step is checked, and the killed step's ``index.lock`` goes first, only once its git is@@ -855,8 +886,10 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Faprint(f"⚠ An interrupted `hermes update` rollback to {pre[:10]} cannot resume yet ({reason}); ""the next launch retries.", file=sys.stderr)return False- head = git("rev-parse", "HEAD")- if not pre or not target or head.stdout.strip() != pre:+ head = read_head()+ if head is None:+ return False+ if not pre or not target or head != pre:marker.unlink() # git finished (HEAD moved) or the marker is unusablereturn Falseif any((git_dir / name).exists() for name in _GIT_OPERATION_IN_PROGRESS):diff --git a/tests/hermes_cli/test_update_interrupted_pull.py b/tests/hermes_cli/test_update_interrupted_pull.pyindex ce9474dc261..a7c2fbe3ce1 100644--- a/tests/hermes_cli/test_update_interrupted_pull.py+++ b/tests/hermes_cli/test_update_interrupted_pull.py@@ -490,3 +490,68 @@ def test_a_reader_git_in_the_tree_is_not_an_index_lock_holder_and_a_holder_is_nafinally:holder.kill()holder.wait()++[email protected](sys.platform == "win32", reason="POSIX shell stubs stand in for a decayed git")[email protected]("stub", ["#!/bin/sh\nexit 0\n", "not a program\n"], ids=["silent-exit-0", "not-executable"])+def test_a_recorded_git_that_is_no_longer_git_falls_back_and_still_repairs(tmp_path, stub):+ """m5: the marker's recorded ``git=`` was trusted on ``os.path.isfile`` alone. A stub that exits 0+ silently made ``rev-parse HEAD`` print nothing, which read as "HEAD moved": the marker was+ deleted over the torn tree. A non-executable file bricked every launch. The recorded git must+ answer ``--version`` as git, else the resolver's git repairs."""+ root, pre, target = _broken_release(tmp_path, 5)+ stub_path = tmp_path / "decayed-git"+ stub_path.write_text(stub, encoding="utf-8", newline="")+ if stub.startswith("#!"):+ stub_path.chmod(0o755)+ marker = er.interrupted_pull_marker(root)+ marker.write_text(f"pid=0\npre={pre}\ntarget={target}\nstash=\nrollback=branch\ngit={stub_path}\n",+ encoding="utf-8", newline="")+ assert er.restore_interrupted_pull(root) is True+ assert _git(root, "rev-parse", "HEAD") == pre and not marker.exists()+ assert er._git_executable(str(stub_path)) != str(stub_path)+++def test_an_empty_head_answer_keeps_the_marker(tmp_path, monkeypatch, capsys):+ """m5: whatever git answers, only a full object name counts as HEAD; an empty one keeps the+ marker for the next launch instead of reading as "the update finished"."""+ root, pre, target = _broken_release(tmp_path, 5)+ marker = _rollback_marker(root, pre, target)+ stub = tmp_path / "silent-git"+ stub.write_text("", encoding="utf-8")+ monkeypatch.setattr(er, "_git_executable", lambda recorded="": str(stub))+ real_run = subprocess.run++ def silent(argv, *args, **kwargs): # every git call "succeeds" with no output+ if argv and argv[0] == str(stub):+ return subprocess.CompletedProcess(argv, 0, "", "")+ return real_run(argv, *args, **kwargs)++ monkeypatch.setattr(subprocess, "run", silent)+ assert er.restore_interrupted_pull(root) is False+ assert marker.exists(), "an empty `rev-parse HEAD` deleted the marker over a torn tree"+ assert "Could not read HEAD" in capsys.readouterr().err+++def test_a_refusal_whose_holder_exits_before_the_probe_retries_the_lock(tmp_path, monkeypatch):+ """m10: the acquire was refused, then the follow-up probe found the lock free (its holder had+ just exited) and the repair ran unguarded. It takes the lock in that case."""+ from hermes_cli import update_lock++ root, _pre, _target = _broken_release(tmp_path, 1)+ real = update_lock._acquire_checkout+ calls = []++ def refused_once(install_root):+ calls.append(install_root)+ if len(calls) == 1: # the refusal; by the probe its holder is gone+ return update_lock.UpdateHolder(pid=2 ** 22 + 7, age_seconds=0.0)+ return real(install_root)++ monkeypatch.setattr(update_lock, "_acquire_checkout", refused_once)+ with er._checkout_custody(root) as busy:+ assert busy == ""+ held = update_lock._HELD+ assert held is not None and held["path"] == str(update_lock.checkout_lock_path(root)), \+ "the repair ran without the checkout lock"+ assert update_lock._HELD is None and len(calls) == 2diff --git a/tests/hermes_cli/test_update_post_pull_syntax_guard.py b/tests/hermes_cli/test_update_post_pull_syntax_guard.pyindex 9b5dd1ffeb9..c72c5ca66a9 100644--- a/tests/hermes_cli/test_update_post_pull_syntax_guard.py+++ b/tests/hermes_cli/test_update_post_pull_syntax_guard.py@@ -138,7 +138,9 @@ def test_the_tree_move_marker_records_the_absolute_git_the_repair_reruns(tmp_pattarget="b" * 40, stash=None)fields = dict(line.partition("=")[::2] for line in marker.read_text(encoding="utf-8").splitlines())assert fields["git"] == str(fake)- # ...and the repair prefers it to PATH (empty here) and to the pm lookup.+ # ...and the repair prefers it to PATH (empty here) and to the pm lookup, once it answers as a+ # git (m5: this fake is an empty file; the version probe is what decides).monkeypatch.setattr("shutil.which", lambda name: None)+ monkeypatch.setattr(_early_recovery, "_is_git", lambda path: path == str(fake))assert _early_recovery._git_executable(fields["git"]) == str(fake)assert _early_recovery._git_executable(str(tmp_path / "gone")) != str(tmp_path / "gone")