Skip to content

The agent that grows with you

fix(update): the historical takeover always owes the fleet restart and never fails a committed update (review F20, F21, F25)

Teknium1dc5b42ae26b
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.py
index 3f7b7d2920a..3430bca0add 100644
--- a/hermes_cli/_update_takeover.py
+++ b/hermes_cli/_update_takeover.py
@@ -4,10 +4,13 @@ from __future__ import annotations
import json
import os
from pathlib import Path
+import re
import subprocess
import sys
import time
+_SHA = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
+
def prepare(request: dict) -> tuple[Path, dict[str, str]]:
"""Provision the new graph before entering its application interpreter."""
@@ -63,23 +66,61 @@ def prepare(request: dict) -> tuple[Path, dict[str, str]]:
def _arm_fleet_obligation(root: Path) -> None:
- head = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, encoding="utf-8",
- stdin=subprocess.DEVNULL, timeout=60)
- sha = head.stdout.strip() if head.returncode == 0 else ""
- if not sha: # an SHA-less record names no code the fleet could be proven current on
- return
+ """Owe the fleet restart for the moved tree. Never raises: the update is already committed, and
+ ``main`` would report any exception here as a failed update."""
# This runs in the HISTORICAL interpreter, before PM syncs the new dependencies: only stdlib-only
# modules here (``update_cmd_fleet``'s writer imports ``update_cmd`` -> config -> ruamel, which a
# release older than ruamel does not have).
from hermes_cli.update_host_obligation import write_host_obligation
- if not write_host_obligation(expected_sha=sha):
- # Same fallback as ``update_cmd_fleet._write_fleet_restart_pending_marker``: the per-home
- # breadcrumb every reader still honours.
- from hermes_constants import get_hermes_home
+ # A git-less archive root has no SHA: an SHA-less record still owes the restart; its readers hold
+ # the fleet to the checkout instead of a named pull.
+ sha = _head_sha(root)
+ if write_host_obligation(expected_sha=sha):
+ return
+ # Same fallback as ``update_cmd_fleet._write_fleet_restart_pending_marker``: the per-home
+ # breadcrumb every reader still honours.
+ from hermes_constants import get_hermes_home
+
+ lines = [f"started={time.time()}", f"pid={os.getpid()}"] + ([f"expected_sha={sha}"] if sha else [])
+ try:
+ (get_hermes_home() / "fleet_restart_pending").write_text("\n".join(lines) + "\n", encoding="utf-8")
+ except OSError as exc:
+ print(f"Warning: could not record the owed gateway restart ({exc}); run `hermes update` again "
+ "to restart the gateway onto the new code.", file=sys.stderr)
+
+
+def _head_sha(root: Path) -> str:
+ """HEAD of ``root``, or ``''``. Git may be off PATH (only PM's store copy) or broken here, so a
+ failed ``rev-parse`` falls back to reading the ref files git itself would read."""
+ from hermes_cli._early_recovery import _git_executable
- (get_hermes_home() / "fleet_restart_pending").write_text(
- f"started={time.time()}\npid={os.getpid()}\nexpected_sha={sha}\n", encoding="utf-8")
+ try:
+ head = subprocess.run([_git_executable(), "-C", str(root), "rev-parse", "HEAD"], capture_output=True,
+ text=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=60)
+ if head.returncode == 0 and _SHA.fullmatch(head.stdout.strip()):
+ return head.stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ pass # no runnable git: the ref files below are the whole of the evidence
+ try:
+ git_dir = root / ".git"
+ if git_dir.is_file(): # a linked worktree / submodule: ``gitdir: <path>``
+ git_dir = root / git_dir.read_text(encoding="utf-8-sig").strip().removeprefix("gitdir:").strip()
+ # Branch refs live in the common dir a linked worktree's ``commondir`` names.
+ common = git_dir / (git_dir / "commondir").read_text(encoding="utf-8-sig").strip() \
+ if (git_dir / "commondir").is_file() else git_dir
+ head = (git_dir / "HEAD").read_text(encoding="utf-8-sig").strip()
+ if head.startswith("ref:"):
+ ref = head.removeprefix("ref:").strip()
+ loose = common / ref
+ if loose.is_file():
+ head = loose.read_text(encoding="utf-8-sig").strip()
+ else:
+ packed = (common / "packed-refs").read_text(encoding="utf-8-sig").splitlines()
+ head = next((line.split(" ", 1)[0] for line in packed if line.endswith(f" {ref}")), "")
+ except (OSError, UnicodeDecodeError):
+ return ""
+ return head if _SHA.fullmatch(head) else ""
def _record_failure(request: dict, result: Path, code: int, detail: str) -> None:
diff --git a/tests/hermes_cli/test_old_updater_takeover.py b/tests/hermes_cli/test_old_updater_takeover.py
index 2ecc8de3d9e..7dea229e2b5 100644
--- a/tests/hermes_cli/test_old_updater_takeover.py
+++ b/tests/hermes_cli/test_old_updater_takeover.py
@@ -445,3 +445,67 @@ def test_bootstrap_lock_remains_live_without_application_dependencies(tmp_path):
assert result.returncode == 0, result.stdout + result.stderr
assert holder.returncode == 0
assert not lock.exists()
+
+
+SHA = "c" * 40
+
+
+ "missing",
+ pytest.param("failing", marks=pytest.mark.platforms("posix")), # POSIX shell stub
+])
+def test_takeover_arms_the_checkout_head_when_git_cannot_answer(tmp_path, monkeypatch, git):
+ """The historical takeover arms the fleet restart AFTER the tree moved. A host whose git is off
+ PATH (only PM's store copy) used to raise FileNotFoundError there, reporting a committed update
+ as failed (F20); a git that runs but fails silently armed nothing (F25). Either way the record
+ must still name the HEAD the checkout's own ref files hold."""
+ from hermes_cli import _early_recovery, _update_takeover
+ from hermes_cli.update_host_obligation import read_host_obligation
+
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ monkeypatch.setenv("PATH", str(bin_dir))
+ root = tmp_path / "checkout"
+ if git == "missing":
+ # The git PATH and PM's store cannot find; the checkout is a linked worktree whose branch
+ # is only in the common dir's packed-refs.
+ monkeypatch.setattr(_early_recovery, "_git_executable", lambda *args, **kwargs: "git")
+ worktree = tmp_path / "repo.git" / "worktrees" / "checkout"
+ worktree.mkdir(parents=True)
+ (worktree / "commondir").write_text("../..\n", encoding="utf-8")
+ (worktree / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ (tmp_path / "repo.git" / "packed-refs").write_text(
+ f"# pack-refs with: peeled fully-peeled sorted\n{'d' * 40} refs/heads/other\n{SHA} refs/heads/main\n",
+ encoding="utf-8")
+ root.mkdir()
+ (root / ".git").write_text(f"gitdir: {worktree}\n", encoding="utf-8")
+ else:
+ stub = bin_dir / "git"
+ stub.write_text("#!/bin/sh\nexit 128\n", encoding="utf-8")
+ stub.chmod(0o755)
+ monkeypatch.setattr(_early_recovery, "_git_executable", lambda *args, **kwargs: str(stub))
+ (root / ".git" / "refs" / "heads").mkdir(parents=True)
+ (root / ".git" / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ (root / ".git" / "refs" / "heads" / "main").write_text(f"{SHA}\n", encoding="utf-8")
+
+ _update_takeover._arm_fleet_obligation(root)
+
+ assert (read_host_obligation() or {}).get("expected_sha") == SHA
+
+
[email protected](shutil.which("git") is None, reason="needs git")
+def test_takeover_arms_an_sha_less_obligation_for_a_git_less_root(tmp_path, monkeypatch):
+ """An archive install has no HEAD to name, yet its update still owes the fleet a restart (F21):
+ an SHA-less record (readers hold the fleet to the checkout) instead of no record at all."""
+ from hermes_cli import _update_takeover
+ from hermes_cli.update_host_obligation import read_host_obligation
+
+ monkeypatch.setenv("GIT_CEILING_DIRECTORIES", str(tmp_path)) # no enclosing repo answers for it
+ root = tmp_path / "archive"
+ root.mkdir()
+
+ _update_takeover._arm_fleet_obligation(root)
+
+ record = read_host_obligation()
+ assert record is not None and record["expected_sha"] == ""
+