The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): conserve Windows restart debt across pause custody transfers (R7, R13)
Teknium08aebc083bf7
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 7e8a9fdc126..e2c3fc1ab58 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -946,6 +946,9 @@ def _pause_windows_gateways_for_update() -> dict | None:service_profiles={str(s.name): str(s.profile) for s in service_gateways})with _abort_on_error("Could not record the gateways this update pauses"):pause_record.record_pause(intended, adopted, claims)+ # A second write, right before the first request: a crash before it leaves every live entry+ # "never asked" (still serving, dropped); after it, a live one is draining and stays owed.+ pause_record.mark_stop_requested(intended, running_pids)profiles = _stop_windows_gateways(running_pids, profile_processes, service_gateway_pids, unmapped_pids, unmapped)token = {"resume_needed": True, "profiles": profiles, "unmapped_pids": unmapped_pids, "unmapped": unmapped}# Every profile with ANY live gateway at discovery counts as running: service-supervised ones skip the@@ -1226,49 +1229,30 @@ def _resume_windows_services(token: dict) -> None:print("\n ✓ Restarted Windows gateway service(s): " + ", ".join(restarted_services))-def _relaunch_paused_gateways(token: dict, profiles: dict, unmapped: list) -> tuple[list[str], int]:- """Relaunch profile gateways and replay unmapped argv; ``(relaunched_profiles, unmapped_count)``.-- Failed relaunches stay on the token (and off ``relaunched_profiles``) so plan-vs-execution- reconciliation still surfaces them — Windows has no watcher to recover them."""+def _relaunch_paused_gateways(profiles: dict, unmapped: list) -> tuple[dict, list]:+ """Spawn the restart watcher for each paused profile gateway and unmapped argv; ``(launched+ profiles, launched unmapped entries)``. Nothing leaves the token here: a watcher only proves a+ relaunch was scheduled, so every entry stays owed until ITS gateway is verified ready."""with _abort_on_error("Could not load Windows gateway restart helper"):from hermes_cli.gateway import launch_detached_gateway_restart_by_cmdline, launch_detached_profile_gateway_restart# An exception from a launch (incl. bad pid/argv coercion) logs at debug and reads as a failed relaunch.- relaunched = []- failed_profiles = {}+ launched = {}for profile, old_pid in sorted(profiles.items()):if _try_call(lambda p=profile, o=old_pid: launch_detached_profile_gateway_restart(str(p), int(o)),"Could not restart Windows gateway profile %s after update: %s", profile):- relaunched.append(str(profile))- else:- failed_profiles[str(profile)] = int(old_pid)- # Surface the outcome on the token (#91277 Phase 2 plan-vs-execution reconciliation): the git-based- # update path's fleet reconciliation cross-checks every planned runtime against restarted_services /- # relaunched_profiles / externally_supervised_profiles / killed_pids — bookkeeping this Windows-specific- # pause/resume never fed, so a correctly-paused-and-relaunched Windows gateway was reported- # "unaccounted" (loud warning + exit 1) even though the restart succeeded. The caller merges this into- # the shared relaunched_profiles list before reconciliation runs. A profile whose relaunch genuinely- # failed is deliberately left off this list — it must still surface as unaccounted so the user is told- # to restart it manually (Windows has no watcher to recover a failed relaunch).- token["relaunched_profiles"] = relaunched- unmapped_relaunched = 0- failed_unmapped = []+ launched[str(profile)] = int(old_pid)+ launched_unmapped = []for entry in unmapped:argv, old_pid = entry.get("argv"), entry.get("pid")if argv and old_pid and _try_call(lambda o=old_pid, a=argv: launch_detached_gateway_restart_by_cmdline(int(o), list(a)),"Could not restart unmapped Windows gateway (pid %s) after update: %s", old_pid):- unmapped_relaunched += 1- else:- failed_unmapped.append(entry)- token["profiles"] = failed_profiles- token["unmapped"] = failed_unmapped- if failed_profiles or failed_unmapped:- raise RuntimeError("Could not restart every paused Windows gateway")- return relaunched, unmapped_relaunched+ launched_unmapped.append(entry)+ return launched, launched_unmapped_RELAUNCH_VERIFY_TIMEOUT_S = 30.0+_PER_TARGET_FLOOR_S = 6.0def _pending_relaunch_pids(profiles: dict, unmapped: list, pid_exists) -> list[int]:@@ -1297,30 +1281,75 @@ def _relaunch_verify_timeout_s(profiles: dict, unmapped: list, pid_exists) -> flreturn float(GATEWAY_RESTART_WATCHER_TIMEOUT_S) + _RELAUNCH_VERIFY_TIMEOUT_S+def _unmapped_ready_filter(entry: dict, taken: set):+ """``pid_filter`` matching the gateway an unmapped entry's argv replay started: same arguments+ after the (normalized) interpreter, not the old pid, not one another entry already vouched for."""+ import psutil+ tail, old = list(entry.get("argv") or [])[1:], int(entry.get("pid") or 0)++ def matches(pid: int) -> bool:+ if pid == old or pid in taken:+ return False+ try:+ return list(psutil.Process(pid).cmdline() or [])[1:] == tail+ except Exception:+ return False+ return lambda pids: [pid for pid in _owned_gateway_pids(pids) if matches(int(pid))]++def _verify_relaunched_gateways_alive(token: dict, profiles: dict, unmapped: list) -> None:- """Gate success on the shared liveness poll: a truthy launch only proves the watcher was created.+ """Retire each relaunched runtime on ITS OWN readiness: a profile on a stable gateway in its+ profile home, an unmapped entry on a stable gateway running its argv. A watcher only proves a+ relaunch was scheduled, and another target's readiness proves nothing about this one.- A parent Job Object denying CREATE_BREAKAWAY_FROM_JOB can kill the gateway on updater teardown;- ``all_profiles=True`` covers the fleet. Vouched PIDs are persisted so a death AFTER updater exit- is reported by the next CLI invocation (best-effort)."""+ A parent Job Object denying CREATE_BREAKAWAY_FROM_JOB can kill the gateway on updater teardown.+ Vouched PIDs are persisted so a death AFTER updater exit is reported by the next CLI invocation."""with _abort_on_error("Could not load Windows gateway liveness helpers"):from gateway.status import _pid_existsfrom hermes_cli import gateway_windows- timeout_s = _relaunch_verify_timeout_s(profiles, unmapped, _pid_exists)- ready_pids = gateway_windows._wait_for_gateway_ready(- timeout_s=timeout_s, all_profiles=True, pid_filter=_owned_gateway_pids- )- if not ready_pids:- token["profiles"] = dict(profiles)- token["unmapped"] = list(unmapped)+ from hermes_cli.profiles import get_profile_dir+ deadline = _time.monotonic() + _relaunch_verify_timeout_s(profiles, unmapped, _pid_exists)++ def budget() -> float:+ return max(deadline - _time.monotonic(), _PER_TARGET_FLOOR_S)++ ready_pids: list[int] = []+ ready_profiles = []+ for name, old_pid in sorted(profiles.items()):+ pids = _try_call(lambda n=name, o=old_pid: gateway_windows._wait_for_gateway_ready(+ timeout_s=budget(), home=Path(get_profile_dir(n)), pid_filter=lambda ps, o=o: [p for p in ps if int(p) != int(o)]),+ "Could not verify Windows gateway profile %s after update: %s", name, default=[])+ if pids:+ ready_profiles.append(name)+ ready_pids.extend(pids)+ ready_unmapped = []+ for entry in unmapped:+ pids = _try_call(lambda e=entry: gateway_windows._wait_for_gateway_ready(+ timeout_s=budget(), all_profiles=True, pid_filter=_unmapped_ready_filter(e, set(ready_pids))),+ "Could not verify unmapped Windows gateway (pid %s) after update: %s", entry.get("pid"), default=[])+ if pids:+ ready_unmapped.append(entry)+ ready_pids.extend(pids[:1])+ # Fleet reconciliation (#91277) cross-checks every planned runtime against relaunched_profiles:+ # only a verified one is listed, so an unready one still surfaces as unaccounted.+ token["relaunched_profiles"] = ready_profiles+ token["profiles"] = {n: pid for n, pid in (token.get("profiles") or {}).items() if n not in ready_profiles}+ token["unmapped"] = [u for u in (token.get("unmapped") or []) if u not in ready_unmapped]+ if ready_pids:+ with suppress(Exception):+ gateway_windows._write_start_attestation(sorted(set(ready_pids)), "post-update relaunch")+ if ready_profiles:+ print(f"\n ✓ Restarting Windows gateway profile(s): {', '.join(ready_profiles)}")+ if ready_unmapped:+ print(f" ✓ Restarting {len(ready_unmapped)} unmapped Windows gateway process(es)")+ unready = sorted(set(profiles) - set(ready_profiles)) + [f"pid {u.get('pid')}" for u in unmapped if u not in ready_unmapped]+ if unready:print(- "\n ⚠ Windows gateway restart could not be verified — no stable gateway process appeared after relaunch.\n"+ "\n ⚠ Windows gateway restart could not be verified for: " + ", ".join(unready) + "\n"" (The respawned gateway may have been killed by a parent Job Object during updater teardown, #48820.)\n"" Recover with: hermes gateway restart")- raise RuntimeError("Windows gateway relaunch after update was not verified alive")- with suppress(Exception):- gateway_windows._write_start_attestation(ready_pids, "post-update relaunch")+ raise RuntimeError("Windows gateway relaunch after update was not verified alive: " + ", ".join(unready))def _resume_windows_gateways_after_update(token: dict | None) -> None:@@ -1359,33 +1388,45 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:def _resume_paused_set(token: dict) -> None:+ """Bring every paused runtime back; each one is retired from *token* only on its own verified+ start, and one failure (an SCM service, a profile) never keeps the others stopped."""from hermes_cli.update_cmd import _m# Regenerate launcher scripts before respawning so a legacy pythonw-era# autostart entry comes back on the current design at next login too._m()._refresh_windows_gateway_launchers()- _resume_windows_services(token)- profiles = token.get("profiles") or {}- unmapped = token.get("unmapped") or []- if not profiles and not any(u.get("argv") for u in unmapped):- if token.get("cold_start_if_installed"):- # Before the per-profile spawns: this guard is fleet-wide (any live gateway ⇒ done).+ failures: list[str] = []++ def attempt(step) -> None:+ try:+ step()+ except Exception as exc:+ failures.append(str(exc))++ attempt(lambda: _resume_windows_services(token))+ profiles = dict(token.get("profiles") or {})+ unmapped = list(token.get("unmapped") or [])+ if profiles or any(u.get("argv") for u in unmapped):+ launched, launched_unmapped = _relaunch_paused_gateways(profiles, unmapped)+ if launched or launched_unmapped:+ attempt(lambda: _verify_relaunched_gateways_alive(token, launched, launched_unmapped))+ else:+ token["relaunched_profiles"] = []+ not_launched = sorted(set(profiles) - set(launched)) + [+ f"pid {u.get('pid')}" for u in unmapped if u not in launched_unmapped]+ if not_launched:+ failures.append("Could not restart every paused Windows gateway: " + ", ".join(not_launched))+ elif token.get("cold_start_if_installed"):+ # Before the per-profile spawns: this guard is fleet-wide (any live gateway ⇒ done).+ def cold_start() -> None:if not _m()._cold_start_windows_gateway_after_update(token):raise RuntimeError("Windows gateway cold-start was not verified")token["cold_start_if_installed"] = False- _cold_start_attested_profiles(token)- token["resume_needed"] = False- return- relaunched, unmapped_relaunched = _relaunch_paused_gateways(token, profiles, unmapped)- if relaunched or unmapped_relaunched:- _verify_relaunched_gateways_alive(token, profiles, unmapped)- if relaunched:- print(f"\n ✓ Restarting Windows gateway profile(s): {', '.join(relaunched)}")- if unmapped_relaunched:- lead = "" if relaunched else "\n"- print(f"{lead} ✓ Restarting {unmapped_relaunched} unmapped Windows gateway process(es)")+ attempt(cold_start)# After the paused profiles are back: a dead-attested sibling that fails to cold-start must not# keep the profiles that WERE running from being relaunched.- _cold_start_attested_profiles(token)+ attempt(lambda: _cold_start_attested_profiles(token))+ if failures:+ raise RuntimeError("; ".join(failures))token["resume_needed"] = Falsediff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex 07ed56a2dc5..5e2ee0c196e 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -7,41 +7,58 @@ home BEFORE anything is stopped, names its owner (pid + creation time, the updatidentity format), is rewritten as the token changes, and is removed only after a verifiedresume. A later launch whose owner check finds the updater dead (and no update live) resumes it.+One record per checkout (the file name carries a key of the install root): a checkout sharing+the home never imports, relabels or certifies another checkout's paused set — its tree gate+says nothing about the other tree.+Resuming is gated on a whole tree: no interrupted-pull marker; at the pre-update HEAD, no trackedchange beyond the ones present at pause time (git died before moving HEAD); at a moved HEAD,dependencies current for it (a build step may rewrite tracked files there). Otherwise the recordstays for the next launch, which runs after the interrupted-pull restore and the dependency sync.-A recovering launch claims the record by renaming it to ``<record>.<pid>.<nonce>.claim`` and names-itself inside; a claim whose claimer died (killed mid-resume) is re-adopted like a dead owner's-record. ``write`` never overwrites another pause: an orphan's set is merged in, a live one refuses.+Custody: every mutation (write, claim, retire, discharge) happens while holding a kernel lock on+``<record dir>/.hermes-update-paused-gateways.lock`` (flock / msvcrt, released by the kernel when+the holder dies; the file is never deleted), and the read → judge → mutate decision is made+inside that hold. A recovering launch claims a record by publishing ``<record>.<pid>.<nonce>.claim``+with its own identity already inside (atomic replace), then retires the source; a crash between the+two leaves two files with ONE obligation id (``pause_id``), and an update that folds orphaned sets+into its own record lists their ids under ``absorbed`` before retiring them. Readers treat a file+whose id another file carries as a copy, never as a second obligation, and the next mutator+retires it."""from __future__ import annotationsimport glob+import hashlibimport jsonimport osimport subprocessimport sys+import timeimport uuid-from contextlib import suppress+from contextlib import contextmanager, suppressfrom pathlib import Path-RECORD_NAME = ".hermes-update-paused-gateways.json"-# Same tolerance as the update marker's creation-time identity (C1 rule 3).-_CT_TOLERANCE_S = 2.0---def record_path() -> Path:- from hermes_constants import get_default_hermes_root- return get_default_hermes_root() / RECORD_NAME+RECORD_STEM = ".hermes-update-paused-gateways"+MUTEX_NAME = RECORD_STEM + ".lock"+_MUTEX_WAIT_S = 10.0+_mutex_depth = 0def install_root() -> Path:return Path(__file__).resolve().parents[1]+def _install_key(root: Path | None = None) -> str:+ return hashlib.sha256(os.path.normcase(str(root or install_root())).encode("utf-8")).hexdigest()[:12]+++def record_path() -> Path:+ from hermes_constants import get_default_hermes_root+ return get_default_hermes_root() / f"{RECORD_STEM}.{_install_key()}.json"++def _create_time(pid: int) -> float | None:from hermes_cli.process_identity import _process_create_timereturn _process_create_time(pid)@@ -55,24 +72,57 @@ def identity(pid: int | None = None) -> dict:def identity_is_live(ident: dict | None) -> bool:- """Alive (not a zombie) and, when a creation time was recorded, the same incarnation."""- from hermes_cli._early_recovery import _pid_is_running+ """The update marker's incarnation rule (``update_lock``), applied to a recorded identity."""+ from hermes_cli import update_locktry:pid = int((ident or {}).get("pid") or 0)except (TypeError, ValueError):return False- if pid <= 0 or not _pid_is_running(pid):- return Falserecorded = str((ident or {}).get("ct") or "")- if not recorded.startswith("ct:"):- return True- actual = _create_time(pid)- if actual is None:- return Truetry:- return abs(float(recorded[3:]) - actual) <= _CT_TOLERANCE_S+ created = float(recorded[3:]) if recorded.startswith("ct:") else Noneexcept ValueError:- return True+ created = None+ return pid > 0 and update_lock._identity_live(pid, created, 0.0)+++class RecordConflict(OSError):+ """The record names another pause whose owner is still live."""+++class RecordBusy(OSError):+ """Another process held the record mutex past the bounded wait."""+++@contextmanager+def _mutex():+ """Exclusive kernel lock on the record directory's sidecar (A7). Re-entrant in-process."""+ global _mutex_depth+ if _mutex_depth:+ _mutex_depth += 1+ try:+ yield+ finally:+ _mutex_depth -= 1+ return+ from hermes_cli import update_lock+ path = record_path().with_name(MUTEX_NAME)+ path.parent.mkdir(parents=True, exist_ok=True)+ fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_BINARY", 0), 0o644)+ try:+ deadline = time.monotonic() + _MUTEX_WAIT_S+ while not update_lock._try_lock(fd):+ if time.monotonic() > deadline:+ raise RecordBusy(f"{path} is held by another process")+ time.sleep(0.05)+ _mutex_depth = 1+ try:+ yield+ finally:+ _mutex_depth = 0+ update_lock._unlock(fd)+ finally:+ os.close(fd)def _git(root: Path, *args: str) -> subprocess.CompletedProcess | None:@@ -174,32 +224,39 @@ def read(path: Path | None = None) -> dict | None:UNOWNED = {"pid": 0, "ct": None}-class RecordConflict(OSError):- """The record names another pause whose owner is still live."""--def write(token: dict, *, owner: dict | None = None, path: Path | None = None) -> None:"""Persist *token*. The owner of the same pause is kept; another pause's orphaned set is mergedinto *token* (in place, so this run's resume brings it back); a live one refuses."""path = path or record_path()- existing = read(path)- same = existing is not None and existing["token"].get("pause_id") == token.get("pause_id")- if existing is not None and not same:- if identity_is_live(existing.get("owner")):- raise RecordConflict(f"{path} holds gateways paused by live process {existing['owner'].get('pid')}")- merge_into(token, drop_never_stopped(dict(existing["token"])))- if owner is None:- owner = existing["owner"] if same else identity()- _atomic_write(path, {"schema": 1, "owner": owner, "install_root": str(install_root()), "token": token})+ with _mutex():+ existing = read(path)+ same = existing is not None and existing["token"].get("pause_id") == token.get("pause_id")+ if existing is not None and not same:+ if existing.get("install_root") != str(install_root()):+ raise RecordConflict(f"{path} holds gateways paused for another checkout ({existing.get('install_root')})")+ if identity_is_live(existing.get("owner")):+ raise RecordConflict(f"{path} holds gateways paused by live process {existing['owner'].get('pid')}")+ merge_into(token, drop_never_stopped(dict(existing["token"])))+ if owner is None:+ owner = existing["owner"] if same and existing is not None else identity()+ _atomic_write(path, {"schema": 1, "owner": owner, "install_root": str(install_root()), "token": token})+++def mark_stop_requested(token: dict, pids) -> None:+ """Persist, BEFORE the first stop request, that these processes are being asked to stop: one+ that acknowledged and is still draining keeps its restart obligation after a crash."""+ token["stop_requested"] = sorted({*map(str, token.get("stop_requested") or []), *(str(int(p)) for p in pids)})+ write(token, owner=identity())def discharge(token: dict, path: Path | None = None) -> None:- """Compare-and-delete: remove the record only while it still names this pause."""+ """Remove the record only while it still names this pause (decided under the mutex)."""path = path or record_path()- existing = read(path)- if existing is not None and existing["token"].get("pause_id") == token.get("pause_id"):- with suppress(OSError):- path.unlink()+ with _mutex():+ existing = read(path)+ if existing is not None and existing["token"].get("pause_id") == token.get("pause_id"):+ with suppress(OSError):+ path.unlink()def sync(token: dict) -> None:@@ -229,27 +286,57 @@ def _claims(path: Path) -> list[Path]:return sorted(path.parent.glob(f"{glob.escape(path.name)}.*.claim"))-def _claimer(claim: Path, body: dict) -> dict:- """Who holds a claim: the identity it wrote, else (killed before writing it) its name's pid."""- if isinstance(body.get("claimer"), dict):- return body["claimer"]- pid = claim.name[len(RECORD_NAME) + 1:].split(".", 1)[0]- return {"pid": int(pid) if pid.isdigit() else 0, "ct": None}+def _holder(src: Path, body: dict) -> dict:+ """Who holds *src*: a record's owner, a claim's claimer (published with the claim itself)."""+ held_by = body.get("owner") if src.suffix == ".json" else body.get("claimer")+ return held_by if isinstance(held_by, dict) else UNOWNED+++def _files(path: Path) -> list[tuple[Path, dict]]:+ """This checkout's record and claims, readable ones only."""+ found = []+ for src in (path, *_claims(path)):+ body = read(src)+ if body is not None and body.get("install_root") == str(install_root()):+ found.append((src, body))+ return found+++def _redundant(found: list[tuple[Path, dict]], held: set[Path]) -> set[Path]:+ """Files that only copy an obligation another file carries: a source an update absorbed but+ died before retiring, or one of two same-id files a claim transfer left. Never a held file."""+ carriers: dict[str, Path] = {}+ for src, body in found:+ for oid in body["token"].get("absorbed") or []:+ carriers.setdefault(str(oid), src)+ redundant: set[Path] = set()+ by_id: dict[str, list[Path]] = {}+ for src, body in found:+ oid = str(body["token"].get("pause_id") or "")+ if not oid:+ continue+ if oid in carriers and carriers[oid] != src:+ redundant.add(src)+ else:+ by_id.setdefault(oid, []).append(src)+ for copies in by_id.values():+ keep = next((s for s in copies if s in held), copies[0])+ redundant.update(s for s in copies if s != keep)+ return redundant - held+++def _survey(path: Path) -> tuple[list[tuple[Path, dict]], set[Path], set[Path]]:+ found = _files(path)+ held = {src for src, body in found if identity_is_live(_holder(src, body))}+ return found, held, _redundant(found, held)def orphans(path: Path | None = None) -> list[tuple[Path, dict]]:- """``(file, body)`` for this install's record whose owner is dead and every claim whose claimer- is dead — empty while another update is live (it adopts them itself)."""+ """``(file, body)`` for every obligation of this checkout whose holder is dead — one file per+ obligation id; empty while another update is live (it adopts them itself)."""path = path or record_path()- found = []- body = read(path)- if body is not None and not identity_is_live(body.get("owner")):- found.append((path, body))- for claim in _claims(path):- claimed = read(claim)- if claimed is not None and not identity_is_live(_claimer(claim, claimed)):- found.append((claim, claimed))- found = [(src, b) for src, b in found if b.get("install_root") == str(install_root())]+ found, held, redundant = _survey(path)+ found = [(src, body) for src, body in found if src not in held and src not in redundant]if not found or _live_update_elsewhere():return []return found@@ -260,28 +347,45 @@ def orphaned_record(path: Path | None = None) -> dict | None:return found[0][1] if found else None+def retire_redundant(path: Path | None = None) -> None:+ """Delete copies of obligations another file already carries (crash leftovers of a transfer)."""+ path = path or record_path()+ if not path.exists() and not _claims(path):+ return+ with suppress(RecordBusy), _mutex():+ _found, _held, redundant = _survey(path)+ for src in redundant:+ with suppress(OSError):+ src.unlink()++def claim(src: Path) -> tuple[Path, dict] | None:"""Take *src* (an orphaned record or a dead claimer's claim) for this process; ``None`` when a- concurrent launch won it. The rename is the arbiter; the claimer line names our incarnation."""+ concurrent launch won it or holds the mutex. The claim is published with our identity inside,+ then the source is retired; a crash between leaves a same-id copy :func:`_redundant` drops."""path = record_path()mine = path.with_name(f"{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.claim")try:- os.rename(src, mine)+ with _mutex():+ body = read(src)+ if body is None or body.get("install_root") != str(install_root()):+ return None+ _found, held, redundant = _survey(path)+ if src in held or src in redundant or src not in {s for s, _ in _found}:+ return None+ body["claimer"] = identity()+ _atomic_write(mine, body)+ with suppress(OSError):+ src.unlink()except OSError:return None- body = read(mine)- if body is None:- with suppress(OSError):- mine.unlink()- return None- body["claimer"] = identity()- _atomic_write(mine, body)return mine, bodydef adopt_orphans() -> tuple[dict | None, list[Path]]:"""For ``hermes update``: claim every orphaned pause and merge their sets. The caller records the- merged set durably, then :func:`release_claims` — a crash in between leaves claims to re-adopt."""+ merged set durably (its ``absorbed`` ids name the claims), then :func:`release_claims`."""+ retire_redundant()adopted, claims = None, []for src, _body in orphans():won = claim(src)@@ -293,26 +397,32 @@ def adopt_orphans() -> tuple[dict | None, list[Path]]:def release_claims(claims: list[Path]) -> None:- for path in claims:- with suppress(OSError):- path.unlink()+ with suppress(RecordBusy), _mutex():+ for path in claims:+ with suppress(OSError):+ path.unlink()def record_pause(token: dict, adopted: dict | None, claims: list[Path]) -> dict:- """Merge the adopted set, stamp the tree and persist under this process BEFORE the first stop."""+ """Merge the adopted set, stamp the tree and persist under this process BEFORE the first stop.+ Publish then retire: a crash between leaves claims whose ids the record lists as absorbed."""if adopted is not None:merge_into(token, adopted)stamp_tree(token)+ token.setdefault("stop_requested", [])write(token, owner=identity())release_claims(claims)return token+_CARRIED = ("pause_id", "pre_sha", "dirty_at_pause", "identities", "stop_requested", "absorbed")++def finish_pause(token: dict, intended: dict, adopted: dict | None) -> dict:"""Carry the recorded pause identity onto the final token and mirror it to disk."""if adopted is not None:merge_into(token, adopted)- token.update({key: intended[key] for key in ("pause_id", "pre_sha", "dirty_at_pause", "identities") if key in intended})+ token.update({key: intended[key] for key in _CARRIED if key in intended})sync(token)return token@@ -323,28 +433,60 @@ def abandon_pause(intended: dict, adopted: dict | None) -> None:if adopted is None:discharge(intended)return- carried = {key: intended[key] for key in ("pause_id", "pre_sha", "dirty_at_pause") if key in intended}+ carried = {key: intended[key] for key in ("pause_id", "pre_sha", "dirty_at_pause", "absorbed") if key in intended}write({**adopted, **carried}, owner=UNOWNED)-def drop_never_stopped(token: dict) -> dict:- """Entries whose recorded process is still the same live incarnation were never stopped."""- alive = {pid for pid, ct in (token.get("identities") or {}).items()- if identity_is_live({"pid": pid, "ct": ct})}- token["profiles"] = {p: pid for p, pid in (token.get("profiles") or {}).items() if str(pid) not in alive}- token["unmapped"] = [u for u in (token.get("unmapped") or []) if str(u.get("pid")) not in alive]+def _live_pids(token: dict) -> set[str]:+ return {str(pid) for pid, ct in (token.get("identities") or {}).items()+ if identity_is_live({"pid": pid, "ct": ct})}+++def _without(token: dict, pids: set[str]) -> dict:+ token["profiles"] = {p: pid for p, pid in (token.get("profiles") or {}).items() if str(pid) not in pids}+ token["unmapped"] = [u for u in (token.get("unmapped") or []) if str(u.get("pid")) not in pids]return token+def drop_never_stopped(token: dict) -> dict:+ """Drop entries whose recorded process is the same live incarnation AND was never asked to stop+ (the update died before its first stop request). One it asked to stop may be draining: it keeps+ its restart debt (:func:`split_draining`). No stop record at all: nothing can be told apart."""+ if token.get("stop_requested") is None:+ return token+ return _without(token, _live_pids(token) - {str(p) for p in token["stop_requested"]})+++def split_draining(token: dict) -> dict:+ """Remove and return ``{"profiles", "unmapped"}`` whose recorded process is still running: it was+ asked to stop and has not exited yet, so it can only be restarted once it has."""+ live = _live_pids(token)+ draining = {"profiles": {p: pid for p, pid in (token.get("profiles") or {}).items() if str(pid) in live},+ "unmapped": [u for u in (token.get("unmapped") or []) if str(u.get("pid")) in live]}+ _without(token, live)+ return draining++def merge_into(token: dict | None, adopted: dict) -> dict:- """Fold an orphaned pause into this update's token so its resume brings both sets back."""+ """Fold an orphaned pause into this update's token so its resume brings both sets back; its+ obligation id (and every id it absorbed) is recorded so a leftover copy is never resumed twice."""token = token if token is not None else {"resume_needed": True, "profiles": {}, "unmapped_pids": [], "unmapped": []}token["resume_needed"] = True+ absorbed = token.setdefault("absorbed", [])+ absorbed.extend(i for i in [adopted.get("pause_id"), *(adopted.get("absorbed") or [])] if i and i not in absorbed)profiles = token.setdefault("profiles", {})for name, pid in (adopted.get("profiles") or {}).items():profiles.setdefault(name, pid)unmapped = token.setdefault("unmapped", [])unmapped.extend(u for u in adopted.get("unmapped") or [] if u not in unmapped)+ identities = token.setdefault("identities", {})+ for pid, ct in (adopted.get("identities") or {}).items():+ identities.setdefault(pid, ct)+ if "stop_requested" in adopted or "stop_requested" in token:+ requested = adopted.get("stop_requested")+ if requested is None: # a set with no stop record keeps every live entry: all count as asked+ requested = list(adopted.get("identities") or {})+ token["stop_requested"] = sorted({*map(str, token.get("stop_requested") or []), *map(str, requested)})services = token.setdefault("services", [])services.extend(s for s in adopted.get("services") or [] if s not in services)if services:@@ -354,26 +496,42 @@ def merge_into(token: dict | None, adopted: dict) -> dict:return token+def _has_work(token: dict) -> bool:+ return bool(token.get("profiles") or any(u.get("argv") for u in token.get("unmapped") or [])+ or token.get("services") or token.get("cold_start_if_installed") or token.get("cold_start_profiles"))++def _resume_claimed(claim_path: Path, body: dict) -> None:token = drop_never_stopped(dict(body["token"]))+ draining = split_draining(token)token.update(resume_needed=True, recovery=True)- print("→ Restarting gateway(s) paused by an interrupted `hermes update`...", file=sys.stderr)try:- from hermes_cli.update_cmd_windows import _resume_windows_gateways_after_update- _resume_windows_gateways_after_update(token)+ if _has_work(token):+ print("→ Restarting gateway(s) paused by an interrupted `hermes update`...", file=sys.stderr)+ from hermes_cli.update_cmd_windows import _resume_windows_gateways_after_update+ _resume_windows_gateways_after_update(token)+ else:+ token["resume_needed"] = Falseexcept Exception as exc:print(f" ⚠ Could not restart every paused gateway: {exc}. Run `hermes update` or ""`hermes gateway start`.", file=sys.stderr)finally:- with suppress(OSError):- if token.get("resume_needed") or token.get("resume_deferred"):- # Still owed: hand the claim back unowned so the next launch retries at once — this- # launch may live for hours (a chat). A failed rewrite leaves our claimer line, which- # turns dead (re-adoptable) when we exit.- owed = {key: value for key, value in token.items() if key not in ("recovery", "resume_deferred")}- _atomic_write(claim_path, {**body, "token": {**owed, "resume_needed": True}, "claimer": UNOWNED})- else:- claim_path.unlink()+ _hand_back(claim_path, body, token, draining)+++def _hand_back(claim_path: Path, body: dict, token: dict, draining: dict) -> None:+ """Retire the claim when nothing is owed; else hand it back unowned so the next launch retries+ at once — this launch may live for hours (a chat). A draining process stays owed until it has+ exited and been restarted. A failed rewrite leaves our claimer line, dead once we exit."""+ token["profiles"] = {**(token.get("profiles") or {}), **draining["profiles"]}+ token["unmapped"] = [*(token.get("unmapped") or []), *draining["unmapped"]]+ owed = bool(token.get("resume_needed") or token.get("resume_deferred") or draining["profiles"] or draining["unmapped"])+ with suppress(OSError), _mutex():+ if owed:+ kept = {key: value for key, value in token.items() if key not in ("recovery", "resume_deferred")}+ _atomic_write(claim_path, {**body, "token": {**kept, "resume_needed": True}, "claimer": UNOWNED})+ else:+ claim_path.unlink()def recover(argv: list[str] | None = None) -> None:@@ -383,6 +541,7 @@ def recover(argv: list[str] | None = None) -> None:if command[:1] == ["update"] or command[:2] == ["gateway", "run"]:return # the update adopts it itself; a booting gateway must not block on its siblingstry:+ retire_redundant()for src, _body in orphans():won = claim(src)if won is not None:diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex 2e5601fff26..2d17fbd5630 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -197,3 +197,197 @@ def test_update_started_from_a_relaunched_gateway_does_not_share_the_claim(tmp_pout, _ = holder.communicate(timeout=60)assert holder.returncode == 0, outassert out.strip() == ("True False" if adopts else "False True"), out+++# --- R7: restart debt is conserved across custody transfers ------------------------------------+# A child stops ITSELF at the named line of the real module (settrace), so a kill or a rival lands+# exactly on the transfer boundary; nothing in the module under test is replaced.+_AT_LINE = """+ import inspect, json, os, sys, time+ from pathlib import Path+ from hermes_cli import update_pause_record as r+ def stop_at(fn, text, action, flag=None):+ lines, start = inspect.getsourcelines(fn)+ line = start + next(i for i, t in enumerate(lines) if text in t)+ def trace(frame, event, arg):+ if event == "line" and frame.f_code is fn.__code__ and frame.f_lineno == line:+ if action == "kill":+ os._exit(71)+ print("paused", flush=True)+ while not Path(flag).exists():+ time.sleep(0.01)+ return trace+ sys.settrace(trace)+"""+_RESUMES = """+ import hermes_cli.update_cmd_windows as w+ def resume(token):+ print("resume", sorted(token.get("profiles") or {}), flush=True)+ token["resume_needed"] = False+ w._resume_windows_gateways_after_update = resume+ r.recover(["status"])+ print("done", flush=True)+"""+++def _launches(tmp_path: Path, n: int) -> list[list[str]]:+ """What each of *n* successive fresh launches resumed."""+ seen = []+ for _ in range(n):+ out, _ = _child(_AT_LINE + _RESUMES, env={"HERMES_HOME": str(tmp_path)}).communicate(timeout=60)+ seen.append([line for line in out.splitlines() if line.startswith("resume")])+ return seen+++def _record_files(tmp_path: Path) -> list[str]:+ return sorted(p.name for p in tmp_path.iterdir() if p.name.startswith(pause_record.RECORD_STEM)+ and p.suffix in (".json", ".claim"))++[email protected]_system_guard_bypass+def test_a_claim_in_transfer_cannot_be_taken_by_a_second_launch(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(pause_record, "_MUTEX_WAIT_S", 0.5)+ _orphan(tmp_path, {"default": 4242})+ src = pause_record.record_path()+ flag = tmp_path / "go"+ first = _child(_AT_LINE + """+ stop_at(r.claim, "src.unlink()", "pause", sys.argv[2])+ won = r.claim(Path(sys.argv[1]))+ sys.settrace(None)+ print(json.dumps(won and str(won[0])), flush=True)+ """, str(src), str(flag), env={"HERMES_HOME": str(tmp_path)})+ try:+ assert first.stdout.readline().strip() == "paused"+ rivals = [pause_record.claim(p) for p in (src, *pause_record._claims(src))]+ assert rivals == [None] * len(rivals), "a second launch took a claim whose transfer was in flight"+ finally:+ flag.touch()+ won = json.loads(first.stdout.readline())+ first.wait(timeout=30)+ assert _record_files(tmp_path) == [Path(won).name], "the paused set is now carried by two files"++[email protected]_system_guard_bypass+def test_a_launch_killed_between_claim_and_retire_resumes_the_set_once(tmp_path):+ _orphan(tmp_path, {"default": 4242})+ killed = _child(_AT_LINE + """+ stop_at(r.claim, "src.unlink()", "kill")+ r.recover(["status"])+ """, env={"HERMES_HOME": str(tmp_path)})+ killed.wait(timeout=60)+ assert killed.returncode == 71 and len(_record_files(tmp_path)) == 2, "premise: killed after publishing the claim"+ assert _launches(tmp_path, 2) == [["resume ['default']"], []]+ assert _record_files(tmp_path) == []++[email protected]_system_guard_bypass+def test_an_update_killed_after_publishing_its_record_never_restarts_a_set_twice(tmp_path):+ _orphan(tmp_path, {"default": 4242})+ killed = _child(_AT_LINE + """+ adopted, claims = r.adopt_orphans()+ stop_at(r.record_pause, "release_claims(claims)", "kill")+ r.record_pause({"resume_needed": True, "profiles": {"beta": 99}}, adopted, claims)+ """, env={"HERMES_HOME": str(tmp_path)})+ killed.wait(timeout=60)+ assert killed.returncode == 71 and len(_record_files(tmp_path)) == 2, "premise: killed before retiring the claim"+ assert _launches(tmp_path, 2) == [["resume ['beta', 'default']"], []]+ assert _record_files(tmp_path) == []+++_DRAINING = """+ import os, signal, sys, time+ from pathlib import Path+ flag = Path(sys.argv[1])+ def stop(*_):+ print("stopping", flush=True) # acknowledged; drains until the flag appears+ while not flag.exists():+ time.sleep(0.01)+ sys.exit(0)+ signal.signal(signal.SIGTERM, stop)+ print("up", flush=True)+ while True:+ time.sleep(0.1)+"""++[email protected]_system_guard_bypass+def test_a_gateway_draining_after_the_stop_request_keeps_its_restart_debt(tmp_path):+ flag = tmp_path / "drained"+ gateway = _child(_DRAINING, str(flag), env={"HERMES_HOME": str(tmp_path)})+ assert gateway.stdout.readline().strip() == "up"+ updater = _child(_AT_LINE + """+ pid = int(sys.argv[1])+ token = r.record_pause({"resume_needed": True, "profiles": {"default": pid},+ "identities": {str(pid): r.identity(pid)["ct"]}}, None, [])+ r.mark_stop_requested(token, [pid])+ os.kill(pid, 15)+ print("asked", flush=True)+ time.sleep(120)+ """, str(gateway.pid), env={"HERMES_HOME": str(tmp_path)})+ try:+ assert updater.stdout.readline().strip() == "asked"+ assert gateway.stdout.readline().strip() == "stopping"+ finally:+ updater.send_signal(signal.SIGKILL) # windows-footgun: ok — module skips on Windows+ updater.wait(timeout=10)+ try:+ assert gateway.poll() is None, "premise: the gateway is still draining"+ assert _launches(tmp_path, 1) == [[]], "a draining gateway was restarted before it exited"+ assert len(_record_files(tmp_path)) == 1, "a draining gateway's restart debt was dropped"+ finally:+ flag.touch()+ gateway.wait(timeout=10)+ assert _launches(tmp_path, 2) == [["resume ['default']"], []]++[email protected]_system_guard_bypass+def test_a_gateway_never_asked_to_stop_is_not_restarted(tmp_path):+ gateway = _child(_DRAINING, str(tmp_path / "unused"), env={"HERMES_HOME": str(tmp_path)})+ assert gateway.stdout.readline().strip() == "up"+ updater = _child(_AT_LINE + """+ pid = int(sys.argv[1])+ r.record_pause({"resume_needed": True, "profiles": {"default": pid},+ "identities": {str(pid): r.identity(pid)["ct"]}}, None, [])+ print("recorded", flush=True)+ time.sleep(120)+ """, str(gateway.pid), env={"HERMES_HOME": str(tmp_path)})+ try:+ assert updater.stdout.readline().strip() == "recorded"+ updater.send_signal(signal.SIGKILL) # windows-footgun: ok — killed before its first stop request+ updater.wait(timeout=10)+ assert _launches(tmp_path, 1) == [[]]+ assert _record_files(tmp_path) == [], "a still-serving gateway's entry stayed owed"+ finally:+ gateway.kill()+ gateway.wait(timeout=10)+++# --- R13: a checkout sharing the home never takes another checkout's paused set --------------+def _checkout_copy(root: Path) -> Path:+ """A second checkout: the real module file under another install root."""+ (root / "hermes_cli").mkdir(parents=True)+ (root / "hermes_cli" / "update_pause_record.py").write_bytes(Path(pause_record.__file__).read_bytes())+ _git(root, "init", "-q")+ _git(root, "add", ".")+ _git(root, "commit", "-qm", "b")+ return root++[email protected]_system_guard_bypass+def test_another_checkouts_writer_never_imports_or_relabels_this_checkouts_debt(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _orphan(tmp_path, {"alpha": 4242})+ other = _checkout_copy(tmp_path / "other")+ writer = _child("""+ import importlib.util, json, sys+ spec = importlib.util.spec_from_file_location("other_pause", sys.argv[1])+ b = importlib.util.module_from_spec(spec); spec.loader.exec_module(b)+ b.write(b.stamp_tree({"resume_needed": True, "profiles": {"beta": 1}}), owner=b.UNOWNED)+ print(json.dumps([len(b.orphans()), b.read()]), flush=True)+ """, str(other / "hermes_cli" / "update_pause_record.py"), env={"HERMES_HOME": str(tmp_path)})+ out, _ = writer.communicate(timeout=60)+ seen, theirs = json.loads(out.strip().splitlines()[-1])+ assert seen == 1 and sorted(theirs["token"]["profiles"]) == ["beta"], f"imported this checkout's set: {theirs}"+ ours = pause_record.read()+ assert ours["install_root"] == str(REPO) and sorted(ours["token"]["profiles"]) == ["alpha"], ours