The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): refuse recovery when checkout custody code is torn
Tekniumd565161188d8
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 7c5e1f64885..6a2c317e530 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -795,15 +795,18 @@ def _checkout_custody(root: Path):or join this process's kill-on-close job (Windows) through ``update_custody.run_git``, so alaunch killed mid-restore keeps the checkout locked until its git is gone.- A tree too torn to import the lock module still gets its repair (this is the code that untears- it); no updater can be running from such a tree.+ A torn lock module cannot prove custody: an already-running updater retains its imported+ copy and may still be writing this checkout. Refuse launch rather than race that writer."""try:from hermes_cli import update_lock- except Exception as exc: # noqa: BLE001 - torn tree: repair without the lock rather than never- print(f"⚠ Repairing without the checkout lock ({type(exc).__name__}: {exc}).", file=sys.stderr)- yield ""- return+ except Exception as exc: # noqa: BLE001 - syntax/import damage must never authorize a write+ raise RuntimeError(+ "Cannot safely repair the interrupted update: checkout custody is unavailable "+ f"({type(exc).__name__}: {exc}). The recovery marker was kept. "+ "Wait for any running update to finish; if this persists, repair the checkout "+ "before launching Hermes again."+ ) from excholder = 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@@ -842,17 +845,19 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Faexecutable = _git_executable(fields.get("git", "").strip())try:from hermes_cli.update_custody import run_git- except Exception: # noqa: BLE001 - torn tree: plain spawns (see _checkout_custody)- run_git = None+ except Exception as exc: # noqa: BLE001 - never start an uncontained repair writer+ raise RuntimeError(+ "Cannot safely repair the interrupted update: child custody is unavailable "+ f"({type(exc).__name__}: {exc}). The recovery marker was kept. "+ "Repair the checkout before launching Hermes again."+ ) from excdef git(*args: str, stdin: str | None = None, text: bool = True) -> subprocess.CompletedProcess:base = [executable, "--literal-pathspecs", "-C", str(root)]kwargs = dict(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 {}))- if run_git is not None:- return run_git(base, list(args), **kwargs)- return subprocess.run([*base, *args], **kwargs)+ return run_git(base, list(args), **kwargs)# A killed git's index.lock goes first, before any git runs (an unresolvable or failing git# would otherwise strand it, and it refuses every later git command). Proven-dead only; after adiff --git a/tests/hermes_cli/test_update_recovery_custody.py b/tests/hermes_cli/test_update_recovery_custody.pynew file mode 100644index 00000000000..f9b056a3817--- /dev/null+++ b/tests/hermes_cli/test_update_recovery_custody.py@@ -0,0 +1,74 @@+"""Broken custody imports never authorize repair of a possibly live checkout."""+from pathlib import Path+import os+import shutil+import subprocess+import sys++import pytest++[email protected]("posix")[email protected]("live_owner", [True, False])+def test_torn_custody_modules_cannot_authorize_uncontained_repair(tmp_path, live_owner):+ source = Path(__file__).resolve().parents[2]+ root = tmp_path / "checkout"+ package = root / "hermes_cli"+ package.mkdir(parents=True)+ for name in ("__init__.py", "_early_recovery.py", "update_lock.py", "update_custody.py"):+ shutil.copy2(source / "hermes_cli" / name, package / name)+ env = {**os.environ, "HOME": str(tmp_path / "home"), "HERMES_HOME": str(tmp_path / "state"),+ "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull,+ "PYTHONDONTWRITEBYTECODE": "1"}+ # The child owns a newly created Git repo, not the checkout running pytest.+ env.pop("PYTEST_CURRENT_TEST", None)++ def git(*args):+ return subprocess.check_output(["git", "-C", str(root), *args], env=env, text=True).strip()++ git("init", "-q", "-b", "main")+ git("config", "user.name", "review")+ git("config", "user.email", "[email protected]")+ payload = root / "payload"+ payload.write_bytes(b"before\n")+ git("add", "-A")+ git("commit", "-qm", "before")+ before = git("rev-parse", "HEAD")+ payload.write_bytes(b"after\n")+ git("commit", "-qam", "after")+ after = git("rev-parse", "HEAD")+ git("reset", "-q", "--hard", before)+ payload.write_bytes(b"after\n")+ marker = root / ".git/hermes-update-pull"+ marker.write_text(f"pid=0\npre={before}\ntarget={after}\ngit={shutil.which('git')}\n", encoding="utf-8")+ holder_script = tmp_path / "holder.py"+ holder_script.write_text(+ "import sys,time\nfrom pathlib import Path\nsys.path.insert(0,sys.argv[1])\n"+ "from hermes_cli.update_lock import UpdateLock\n"+ "lock=UpdateLock(path=Path(sys.argv[2])/'owner',install_root=Path(sys.argv[2]))\n"+ "assert lock.acquire()\nprint('HELD',flush=True)\ntime.sleep(60)\n", encoding="utf-8")+ recovery_script = tmp_path / "recover.py"+ recovery_script.write_text(+ "import sys\nfrom pathlib import Path\nsys.path.insert(0,sys.argv[1])\n"+ "from hermes_cli._early_recovery import restore_interrupted_pull\n"+ "restore_interrupted_pull(Path(sys.argv[1]))\n", encoding="utf-8")+ owner = subprocess.Popen([sys.executable, "-I", str(holder_script), str(source), str(root)],+ env=env, stdout=subprocess.PIPE, text=True, encoding="utf-8")+ try:+ assert owner.stdout.readline().strip() == "HELD"+ damaged = ("update_lock.py", "update_custody.py") if live_owner else ("update_custody.py",)+ if not live_owner:+ owner.kill()+ owner.wait()+ for name in damaged:+ (package / name).write_bytes(b'"""torn')+ result = subprocess.run([sys.executable, "-I", str(recovery_script), str(root)],+ cwd=tmp_path, env=env, capture_output=True, text=True,+ encoding="utf-8", timeout=30)+ assert (owner.poll() is None) == live_owner+ assert payload.read_bytes() == b"after\n", "repair wrote without verifiable child custody"+ assert marker.exists(), "unverified custody must retain the interrupted-update record"+ assert result.returncode != 0 and "Cannot safely repair" in result.stderr+ finally:+ owner.kill()+ owner.wait()diff --git a/website/docs/developer-guide/source-update-completion.md b/website/docs/developer-guide/source-update-completion.mdindex fd0a75b22ce..3bc61dab36f 100644--- a/website/docs/developer-guide/source-update-completion.md+++ b/website/docs/developer-guide/source-update-completion.md@@ -109,6 +109,18 @@ lifecycle obligation when the child cannot execute or is killed. A failed childnever clears the pending fleet obligation. No automatic code rollback aftermaintenance has begun (SQLite snapshots remain file-loss recovery, not rollback).+### Damaged recovery code++Launch-time checkout repair requires both the checkout lock and the child-custody+runner to be importable. If either module is torn, launch stops with+`Cannot safely repair` and retains the interrupted-update marker instead of+writing without exclusion. An updater that already imported healthy code can+still hold and write the checkout even when its on-disk modules are damaged.+Wait for any running update to finish; persistent damage requires checkout repair+before launching again. This safety refusal is not automatic recovery of the+recovery modules themselves: the launcher still depends on checkout bootstrap+code, which a killed tree move can also leave unavailable.+## Historical surfaceAll names frozen from the complete reachable shipped updater history stay