The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): one install's failed run hands back only its own stake in the host restart record
Teknium9909a180256e
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.pyindex de12137c0ee..ae6a2acf879 100644--- a/hermes_cli/update_cmd_commit.py+++ b/hermes_cli/update_cmd_commit.py@@ -44,6 +44,8 @@ _armed_bytes: dict[Path, Optional[bytes]] = {}# (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] = None+# This run's stake in the shared host record (``owners``): disarm removes only this one.+_owner: str = ""def _owns_live_checkout(root: Path) -> bool:@@ -76,7 +78,9 @@ def arm_commit_obligations(root: Path, expected_sha: str) -> None:raises: nothing has moved yet, and moving without the obligation is exactly thetail-never-runs state this exists to prevent."""- global _armed_snapshot+ global _armed_snapshot, _owner+ import uuid+from hermes_cli.update_cmd_fleet import _write_fleet_restart_pending_markerfrom hermes_cli.venv_sync import arm_completion@@ -85,9 +89,10 @@ def arm_commit_obligations(root: Path, expected_sha: str) -> None:returnif _armed_snapshot is None:_armed_snapshot = {path: _read_or_none(path) for path in _obligation_paths(root)}+ _owner = f"{root}|{os.getpid()}|{uuid.uuid4().hex}"try:arm_completion(root)- owed = _write_fleet_restart_pending_marker(expected_sha=expected_sha or "")+ owed = _write_fleet_restart_pending_marker(expected_sha=expected_sha or "", owner=_owner)finally: # even a half-done arm: disarm must still recognise what this run wrote_armed_bytes.update({path: _read_or_none(path) for path in _armed_snapshot})if not owed:@@ -111,11 +116,19 @@ def disarm_commit_obligations() -> None:if root is not None:_owe_for(root, head)return+ from hermes_cli.update_host_obligation import host_obligation_path, release_host_obligation+snapshot, _armed_snapshot = _armed_snapshot, Nonearmed = dict(_armed_bytes)_armed_bytes.clear()+ host = host_obligation_path()for path, data in (snapshot or {}).items():try:+ if path == host:+ # Shared by every install of the OS user: same-SHA arms join one record, so bytes+ # cannot tell whose it is; the ``owners`` stake can (review C2).+ release_host_obligation(_owner)+ continueif path not in armed or _read_or_none(path) != armed[path]:continue # rewritten since this run armed it (another install's update): theirs nowif data is None:@@ -127,6 +140,8 @@ def disarm_commit_obligations() -> None:fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)with os.fdopen(fd, "wb") as handle:handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())os.replace(tmp, path)except OSError:pass # an owed tail/restart left armed is a retry, never a lost obligation@@ -456,7 +471,8 @@ def preflight_refusal(git_cmd, root: Path, target_ref: str, critical_files) -> sdef reset_for_tests() -> None:- global _armed_snapshot, _run_start, _obligation_root+ global _armed_snapshot, _run_start, _obligation_root, _owner+ _owner = ""_armed_snapshot = None_armed_bytes.clear()_run_start = Nonediff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex c2e0be51785..fecaee647e7 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -82,7 +82,7 @@ def _write_legacy_fleet_restart_pending_marker(return False-def _write_fleet_restart_pending_marker(*, expected_sha: str = "", runtimes: list[dict] | None = None) -> bool:+def _write_fleet_restart_pending_marker(*, expected_sha: str = "", runtimes: list[dict] | None = None, owner: str = "") -> bool:"""Arm the HOST pull→restart obligation. Never raises; False when neither store took it.An unwritable host state dir (``HERMES_GATEWAY_LOCK_DIR`` on a read-only mount, a container@@ -102,7 +102,7 @@ def _write_fleet_restart_pending_marker(*, expected_sha: str = "", runtimes: lislogger.debug("Skipping fleet-restart-pending obligation under pytest (live checkout)")return Trueif write_host_obligation(- expected_sha=expected_sha, runtimes=runtimes, profile=_current_profile_name()):+ expected_sha=expected_sha, runtimes=runtimes, profile=_current_profile_name(), owner=owner):return Trueif _write_legacy_fleet_restart_pending_marker(expected_sha=expected_sha, runtimes=runtimes):logger.warning(diff --git a/hermes_cli/update_host_obligation.py b/hermes_cli/update_host_obligation.pyindex 426737e1cff..33320a23ea6 100644--- a/hermes_cli/update_host_obligation.py+++ b/hermes_cli/update_host_obligation.py@@ -20,6 +20,7 @@ live ``MainPID``, so restarting each one restarts the host process N times.from __future__ import annotations+import base64import contextlibimport jsonimport logging@@ -100,24 +101,44 @@ def amend_host_obligation(**fields: Any) -> None:def write_host_obligation(- *, expected_sha: str = "", runtimes: Optional[list] = None, profile: str = ""+ *, expected_sha: str = "", runtimes: Optional[list] = None, profile: str = "", owner: str = "") -> bool:"""Arm the host obligation. True when it was written. Never raises.Re-arming from a second profile for the SAME pulled SHA keeps the existing record (and its``restarted`` proof) instead of resetting it: the host owes one restart, not one per profile.+ ``owner`` (an update run's commit-point token) joins the record's ``owners``: a run that+ fails before its move hands back only its own stake (``release_host_obligation``), never+ another install's debt for the same SHA. The first owner also stores what it found there+ (``found``), which the last owner to leave puts back."""path = host_obligation_path()existing = read_host_obligation()+ try:+ found = _found_field(path) if owner and not _owners(existing or {}) else None+ except OSError as exc: # unreadable is not absent: a guessed ``found`` would delete it later+ logger.debug("Could not read the host update-restart obligation: %s", exc)+ return Falseif existing is not None and expected_sha and existing.get("expected_sha") == expected_sha:# Same pull, second profile: the host owes ONE restart, so keep the standing record (and# any proof that the restart already happened) rather than resetting it. A later arm that# carries the owed inventory still upgrades it — an inventory-less record owes no set.- if runtimes is None:- return True+ fields: dict[str, Any] = {}+ owners = _owners(existing)+ if owner and owner not in owners:+ fields["owners"] = [*owners, owner]+ if not owners:+ fields["found"] = foundinventory = {"version": 1, "runtimes": runtimes}- if existing.get("inventory") != inventory:- amend_host_obligation(inventory=inventory)+ if runtimes is not None and existing.get("inventory") != inventory:+ fields["inventory"] = inventory+ if not fields:+ return True+ try:+ _write_record(path, {**existing, **fields})+ except Exception as exc: # health: allow BLE001 -- never raises: the caller falls back to the per-home marker+ logger.debug("Could not amend host update-restart obligation: %s", exc)+ return Falsereturn Truepayload: dict[str, Any] = {"version": _RECORD_VERSION,@@ -126,6 +147,9 @@ def write_host_obligation("armed_by_profile": profile or "","expected_sha": expected_sha or "",}+ if owner:+ payload["owners"] = [owner]+ payload["found"] = foundif runtimes is not None:payload["inventory"] = {"version": 1, "runtimes": runtimes}try:@@ -137,6 +161,62 @@ def write_host_obligation(return True+def _owners(record: dict) -> list[str]:+ owners = record.get("owners")+ return [str(o) for o in owners] if isinstance(owners, list) else []+++def _found_field(path: Path) -> Optional[str]:+ """The record's current bytes (base64), ``None`` when absent: what a first owner puts back.+ Any other read error raises: custody is never guessed."""+ try:+ return base64.b64encode(path.read_bytes()).decode("ascii")+ except FileNotFoundError:+ return None+++def release_host_obligation(owner: str) -> None:+ """Hand back ``owner``'s stake in the record. When no other run still owes through it, the+ record goes back to what its first owner found (``found``; absent = unlinked).++ A record without ``owner`` was rewritten since (another install's newer pull): it is theirs and+ stays. Raises OSError when the record cannot be rewritten (the caller keeps the debt armed).+ """+ record = read_host_obligation()+ owners = _owners(record) if record is not None else []+ if not owner or owner not in owners:+ return+ path = host_obligation_path()+ remaining = [o for o in owners if o != owner]+ if remaining:+ _write_record(path, {**record, "owners": remaining})+ return+ try:+ found = base64.b64decode(record["found"], validate=True) if record.get("found") is not None else None+ except (TypeError, ValueError):+ return # a damaged ``found`` cannot be put back: the debt stays armed, never guessed away+ if found is None:+ path.unlink(missing_ok=True)+ else:+ _replace_bytes(path, found)+++def _replace_bytes(path: Path, data: bytes) -> None:+ """Put ``data`` back at ``path``: a fresh ``mkstemp`` file (never through a planted alias),+ fsynced, then renamed over the record."""+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.stem}_", suffix=".restore")+ try:+ with os.fdopen(fd, "wb") as handle:+ handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(tmp, path)+ except BaseException:+ with contextlib.suppress(OSError):+ os.unlink(tmp)+ raise++def clear_host_obligation() -> None:"""Discharge the obligation for the whole host. Never raises."""try:diff --git a/tests/hermes_cli/test_update_commit_obligations.py b/tests/hermes_cli/test_update_commit_obligations.pyindex 9fea63068e2..39cba70ffc3 100644--- a/tests/hermes_cli/test_update_commit_obligations.py+++ b/tests/hermes_cli/test_update_commit_obligations.py@@ -157,3 +157,40 @@ def test_a_refused_pull_after_the_branch_switch_owes_the_head_the_switch_landed_assert reason and "the checkout was not changed" not in reason and a[:10] in reasonassert (read_host_obligation() or {}).get("expected_sha") == a+++def _run_state() -> dict:+ return {name: getattr(commit, name, None) for name in ("_armed_snapshot", "_owner")} | {+ "_armed_bytes": dict(commit._armed_bytes)}+++def _enter_run(state: dict) -> None:+ for name, value in state.items():+ if name == "_armed_bytes":+ commit._armed_bytes.clear()+ commit._armed_bytes.update(value)+ else:+ setattr(commit, name, value)+++def test_one_installs_disarm_never_deletes_another_installs_debt_for_the_same_sha(root, tmp_path):+ """Install A and install B both arm SHA X. Same-SHA arms share one host record, so a byte+ compare cannot tell them apart: A's failed run used to delete the record B still owes through+ (review C2). A's disarm hands back only A's stake; the last owner to leave puts back what the first found."""+ from hermes_cli.update_host_obligation import read_host_obligation++ other = tmp_path / "other-install"+ other.mkdir()+ commit.arm_commit_obligations(root, "a" * 40) # install A+ run_a = _run_state()+ commit.reset_for_tests()+ commit.arm_commit_obligations(other, "a" * 40) # install B, same pulled SHA+ run_b = _run_state()++ _enter_run(run_a)+ commit.disarm_commit_obligations()+ assert (read_host_obligation() or {}).get("expected_sha") == "a" * 40 # B still owes it++ _enter_run(run_b)+ commit.disarm_commit_obligations()+ assert not host_obligation_path().exists() # the last owner puts back what the FIRST one found