The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): with no published closure the launcher reads it from git's objects (D1)
Tekniumb4f65a596774
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 3587d7d196e..123d4d6bd0d 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -248,7 +248,8 @@ def interrupted_pull_marker(root: Path) -> Path:# The repair's own code is in the tree a killed move tears (``hermes_bootstrap``, this module, the# package initializer, the lock/custody modules). ``update_cmd_commit.arm_tree_move`` publishes this# closure, as committed at the marker's ``pre``, beside the marker before git writes; a minted-# launcher whose checkout import fails runs the repair from there (``_launchers._launcher_script``).+# launcher whose checkout import fails runs the repair from there, reading the same files from git's+# objects first when no updater published them (``_launchers._CLOSURE_REPAIR``).# The modules import only the stdlib and each other; the package initializer is published empty.RECOVERY_CLOSURE_DIR = "hermes-update-recovery"RECOVERY_CLOSURE = ("hermes_cli/_early_recovery.py", "hermes_cli/update_lock.py", "hermes_cli/update_custody.py")diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.pyindex 1153f881692..8418c4a4725 100644--- a/hermes_cli/_launchers.py+++ b/hermes_cli/_launchers.py@@ -305,6 +305,63 @@ def mint_launcher(return _write_atomic(out_dir / f"{name}.cmd", lambda p: p.write_text(body, encoding="utf-8"))+# A killed move can tear the repair's own code (``hermes_bootstrap``, ``hermes_cli``). With the+# marker still there, a launcher whose checkout import failed runs the copy of the repair that the+# updater published beside the marker (``update_cmd_commit.publish_recovery_closure``), or, when+# none was published (an updater predating it), the same files read from git's objects at the+# marker's ``pre``: stdlib plus that copy only, under the same claim and checkout lock (a live+# writer still refuses), then a relaunch from the restored tree.+_CLOSURE_REPAIR = """\+def _hermes_closure_repair():+ import subprocess+ from pathlib import Path+ root = Path(__ROOT__)+ git = root / '.git'+ try:+ if git.is_file():+ text = git.read_text(encoding='utf-8-sig').strip()+ git = root / text[7:].strip() if text.startswith('gitdir:') else git+ fields = dict(line.partition('=')[::2] for line in (git / __MARKER__).read_text(encoding='utf-8-sig').splitlines())+ except OSError:+ return+ pre = fields.get('pre', '').strip()+ closure = git / __CLOSURE_DIR__ / pre+ if pre and not all((closure / rel).is_file() for rel in __CLOSURE__):+ exe = fields.get('git', '').strip()+ staging = closure.with_name('.%s.%d.launch' % (pre, os.getpid()))+ try:+ for rel in (*__CLOSURE__, 'hermes_cli/__init__.py'):+ blob = b''+ if rel in __CLOSURE__:+ blob = subprocess.run([exe if exe and os.path.isfile(exe) else 'git', '-C', str(root), 'cat-file',+ 'blob', pre + ':' + rel], capture_output=True, timeout=60,+ stdin=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))+ if blob.returncode != 0:+ return+ blob = blob.stdout+ (staging / rel).parent.mkdir(parents=True, exist_ok=True)+ (staging / rel).write_bytes(blob)+ os.replace(staging, closure)+ except (OSError, subprocess.SubprocessError):+ pass+ finally:+ __import__('shutil').rmtree(staging, ignore_errors=True)+ if not pre or not all((closure / rel).is_file() for rel in __CLOSURE__):+ return+ for name in [n for n in sys.modules if n.split('.')[0] in ('hermes_cli', 'hermes_bootstrap', 'hermes_constants', 'pm')]:+ del sys.modules[name]+ tree = os.path.normcase(os.path.realpath(root))+ sys.path[:] = [str(closure)] + [p for p in sys.path if p and os.path.normcase(os.path.realpath(p)) != tree+ and not os.path.normcase(os.path.realpath(p)).startswith(tree + os.sep)]+ print('hermes: the checkout cannot start after an interrupted `hermes update`; '+ 'repairing it with the recovery code saved before the update.', file=sys.stderr)+ sys.dont_write_bytecode = True+ from hermes_cli import _early_recovery+ if _early_recovery.restore_interrupted_pull(root):+ _early_recovery.relaunch_after_restore()+"""++def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> str:module, func = ENTRY_POINTS[name]# Profile boot repairs shared launchers: their default must stay at the@@ -317,40 +374,12 @@ def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> s# ``hermes_bootstrap`` right after the repair (``_PIN_DEFAULT_HOME``), and here again for a# bootstrap that predates that hook.root = str(repo_root.resolve())- from hermes_cli._early_recovery import INTERRUPTED_PULL_MARKER, RECOVERY_CLOSURE_DIR+ from hermes_cli._early_recovery import INTERRUPTED_PULL_MARKER, RECOVERY_CLOSURE, RECOVERY_CLOSURE_DIR- # A killed move can tear the repair's own code (``hermes_bootstrap``, ``hermes_cli``): with the- # marker still there, run the copy the updater published beside it before git wrote (stdlib +- # that copy only; it still takes the checkout lock), then relaunch from the restored tree.- closure_repair = (- "def _hermes_closure_repair():\n"- " from pathlib import Path\n"- f" root = Path({root!r})\n"- " git = root / '.git'\n"- " try:\n"- " if git.is_file():\n"- " text = git.read_text(encoding='utf-8-sig').strip()\n"- " git = root / text[7:].strip() if text.startswith('gitdir:') else git\n"- f" fields = dict(line.partition('=')[::2] for line in (git / {INTERRUPTED_PULL_MARKER!r})"- ".read_text(encoding='utf-8-sig').splitlines())\n"- " except OSError:\n"- " return\n"- " pre = fields.get('pre', '').strip()\n"- f" closure = git / {RECOVERY_CLOSURE_DIR!r} / pre\n"- " if not pre or not (closure / 'hermes_cli' / '_early_recovery.py').is_file():\n"- " return\n"- " for name in [n for n in sys.modules if n.split('.')[0] in ('hermes_cli', 'hermes_bootstrap', 'hermes_constants', 'pm')]:\n"- " del sys.modules[name]\n"- " tree = os.path.normcase(os.path.realpath(root))\n"- " sys.path[:] = [str(closure)] + [p for p in sys.path if p and os.path.normcase(os.path.realpath(p)) != tree\n"- " and not os.path.normcase(os.path.realpath(p)).startswith(tree + os.sep)]\n"- " print('hermes: the checkout cannot start after an interrupted `hermes update`; '\n"- " 'repairing it with the recovery code saved before the update.', file=sys.stderr)\n"- " sys.dont_write_bytecode = True\n"- " from hermes_cli import _early_recovery\n"- " if _early_recovery.restore_interrupted_pull(root):\n"- " _early_recovery.relaunch_after_restore()\n"- )+ closure_repair = (_CLOSURE_REPAIR.replace("__MARKER__", repr(INTERRUPTED_PULL_MARKER))+ .replace("__CLOSURE_DIR__", repr(RECOVERY_CLOSURE_DIR))+ .replace("__CLOSURE__", repr(RECOVERY_CLOSURE))+ .replace("__ROOT__", repr(root))) # last: a path is never re-substitutedreturn ("import os, re, sys\n""os.environ.pop('PYTHONHOME', None)\n"diff --git a/tests/hermes_cli/test_update_recovery_closure.py b/tests/hermes_cli/test_update_recovery_closure.pyindex ca3d14005f4..a9c4c789ef3 100644--- a/tests/hermes_cli/test_update_recovery_closure.py+++ b/tests/hermes_cli/test_update_recovery_closure.py@@ -2,7 +2,7 @@The repair (``hermes_bootstrap`` -> ``_early_recovery`` under the checkout lock) lives in the tree gitrewrites. ``arm_tree_move`` publishes that closure beside the marker before git writes; the minted-launcher runs it when the checkout's copy cannot even import. Real git, really killed mid-write (a+launcher runs it (or the same files read from git's objects) when the checkout's copy cannot import. Real git, really killed mid-write (asmudge-filter barrier), the production marker writer in a child that exits, the production launcher;the application entry is an inert receipt."""@@ -102,16 +102,20 @@ def _killed_mid_write(tmp_path: Path, rel: str):@pytest.mark.platforms("posix")[email protected](("rel", "torn"), [- ("hermes_bootstrap.py", False),- ("hermes_cli/_early_recovery.py", True),- ("hermes_cli/__init__.py", True),- ("hermes_cli/update_lock.py", True),[email protected](("rel", "torn", "published"), [+ ("hermes_bootstrap.py", False, True),+ ("hermes_cli/_early_recovery.py", True, True),+ ("hermes_cli/__init__.py", True, True),+ ("hermes_cli/update_lock.py", True, True),+ # An updater that predates publication: the launcher reads the same files from git's objects.+ ("hermes_bootstrap.py", True, False),])-def test_a_launch_repairs_a_move_killed_while_writing_the_repairs_own_code(tmp_path, rel, torn):+def test_a_launch_repairs_a_move_killed_while_writing_the_repairs_own_code(tmp_path, rel, torn, published):root, env, original, launcher = _killed_mid_write(tmp_path, rel)if torn: # git's write cut short: a prefix of the new blob(root / rel).write_bytes(original[:12])+ if not published:+ shutil.rmtree(root / ".git/hermes-update-recovery")launch = subprocess.run([str(launcher)], cwd=tmp_path, env=env, capture_output=True, text=True, encoding="utf-8",errors="replace", timeout=60)assert launch.returncode == 0 and "APP_REACHED" in launch.stdout, launch.stderrdiff --git a/website/docs/developer-guide/source-update-completion.md b/website/docs/developer-guide/source-update-completion.mdindex cb7c1cafd7e..c601a4b68e9 100644--- a/website/docs/developer-guide/source-update-completion.md+++ b/website/docs/developer-guide/source-update-completion.md@@ -124,13 +124,16 @@ The repair code lives in the tree a killed move tears (`hermes_bootstrap.py`,recovery/lock/custody modules, as committed at the move's starting commit, to`<git dir>/hermes-update-recovery/<pre>/`, outside the working tree and keyedto the marker's `pre`. When the checkout's own import fails while the marker-exists, the minted launcher (`.hermes/bin/hermes`) runs that published copy:-stdlib plus the copy only, the same restore claim and checkout lock (a live-writer still gets `Not repairing the checkout now`), then relaunches from the-restored tree. Limits: other entry points (`python -m hermes_cli.main`, the-`hermes-agent` hook) have no such fallback, a launcher minted before this-fallback existed has none, and the first update performed by such an old-launcher's code publishes no closure.+exists, the minted launcher (`.hermes/bin/hermes`) runs that published copy+(when an older updater published none, it first reads the same files from+git's objects at `pre` into that directory): stdlib plus the copy only, the+same restore claim and checkout lock (a live writer still gets `Not repairing+the checkout now`), then relaunches from the restored tree. Limits: other entry+points (`python -m hermes_cli.main`, the `hermes-agent` hook) have no such+fallback; a launcher minted before this fallback existed has none, so a kill+during the first update onto this code (run under the old launcher) is not+covered; a `pre` whose tree lacks the checkout lock or custody runner is not+used.## Historical surface