The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): after the commit point nothing fails hermes update (C3)
Teknium045615ac5a3c
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex 5a5ca614f41..0b884efd905 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -515,10 +515,11 @@ def _install_hangup_protection(gateway_mode: bool = False):# Any failure here is non-fatal; we just skip the wrap.try:- # Late-bound import so tests can monkeypatch- # hermes_cli.config.get_hermes_home to simulate setup failure.- from hermes_cli.config import get_hermes_home as _get_hermes_home- logs_dir = _get_hermes_home() / "logs"+ # Late-bound import so tests can monkeypatch it to simulate setup failure. The ROOT+ # home, never a sticky profile's: the update mutates the shared checkout, and the+ # Desktop and the hand-off scripts read <root>/logs/update.log.+ from hermes_constants import get_default_hermes_root as _get_root_home+ logs_dir = _get_root_home() / "logs"logs_dir.mkdir(parents=True, exist_ok=True)log_file = open(logs_dir / "update.log", "a", buffering=1, encoding="utf-8")diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.pyindex 2559379ab2e..f9208d71bd8 100644--- a/hermes_cli/source_build.py+++ b/hermes_cli/source_build.py@@ -99,66 +99,70 @@ def source_frontends(project_root: Path) -> tuple[str, ...]:return tuple(name for name in ("ui-tui", "web") if (project_root / name / "package.json").is_file())+class ProductBuildError(RuntimeError):+ """One or more products failed; every independent product was still attempted."""++ def __init__(self, failures: list[tuple[str, BaseException]]):+ self.failures = failures+ super().__init__("; ".join(f"{name}: {_failure_text(exc)}" for name, exc in failures))+++def _failure_text(exc: BaseException) -> str:+ if isinstance(exc, subprocess.CalledProcessError):+ return f"{' '.join(map(str, exc.cmd)) if isinstance(exc.cmd, (list, tuple)) else exc.cmd} exited {exc.returncode}"+ return f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__++def build_update_products(project_root: Path, *, desktop: bool) -> None:- """Prepare the selected union once; a failed product aborts the update."""+ """Prepare the selected union once, attempting every independent product.++ A failed product never skips the next one (a broken web build must not leave the TUI or the+ desktop app stale); the failures are raised together at the end as ``ProductBuildError``.+ """# Both current updates and historical takeover reach this in a fresh target# interpreter, never in the updater's pre-sync import graph.from hermes_cli.main_install_repair import _install_configured_features_missing_depsfrom hermes_cli.update_stage import publish_stage- _install_configured_features_missing_deps(project_root)+ failures: list[tuple[str, BaseException]] = []++ def attempt(name: str, step) -> bool:+ try:+ step()+ return True+ except Exception as exc: # noqa: BLE001 — collected and raised after the independent steps+ print(f" ⚠ {name} failed: {_failure_text(exc)}")+ failures.append((name, exc))+ return False++ attempt("feature dependencies", lambda: _install_configured_features_missing_deps(project_root))frontends = source_frontends(project_root)- if not frontends:- return- env = source_build_env(explicit=True)- workspaces = frontends + (("apps/desktop",) if desktop else ())- publish_stage("Updating Node dependencies")- prepare_source_dependencies(project_root, workspaces, env=env, explicit=True)- # An update that changed no TUI/web input reuses the receipted output, as the- # launch path already does; recompiling it produces the same bytes. Desktop- # additionally needs the packaged app to name HEAD (its baked stamp carries the- # commit), so it is reused only when HEAD did not move: "Already up to date",- # a retried tail, a takeover re-entry.- if "ui-tui" in frontends:- if source_product_current(project_root, "tui", project_root / "ui-tui/dist"):- print(" ✓ TUI is up to date")- else:- publish_stage("Building the TUI")- build_source_tui(project_root, env=env)- if "web" in frontends:- if source_product_current(project_root, "web", project_root / "hermes_cli/web_dist"):- print(" ✓ Web UI is up to date")- else:- publish_stage("Building the web UI")- build_source_web(project_root, env=env)- if desktop:- from hermes_cli.main_desktop import (- _packaged_desktop_current_for_head, _refresh_installed_desktop_apps, build_prepared_desktop)-- desktop_dir = project_root / "apps/desktop"- if _packaged_desktop_current_for_head(desktop_dir, project_root):- print(" ✓ Desktop app is up to date")- else:- publish_stage("Building the desktop app")- # The desktop build mutates checkout-scoped node_modules and- # apps/desktop/release; serialize it against a concurrent manual- # `hermes desktop` (#93940). The update path waits rather than exits:- # the in-flight build it queues behind produces the same fresh tree- # this update needs.- from hermes_cli.desktop_build_lock import DesktopBuildLock-- build_lock = DesktopBuildLock(project_root)- build_lock.acquire(wait=True)- try:- build_prepared_desktop(- desktop_dir, source_mode=False,- npm=shutil.which("npm", path=env["PATH"]), env=env, icons=project_root,- )- finally:- build_lock.release()- # A current release/ can still sit beside a stale installed copy (an earlier- # update rebuilt but never installed); healing must not wait for the next build.- _refresh_installed_desktop_apps(desktop_dir)+ if frontends:+ env = source_build_env(explicit=True)+ workspaces = frontends + (("apps/desktop",) if desktop else ())+ publish_stage("Updating Node dependencies")+ # Every product compiles from these node_modules: without them there is nothing to build.+ if attempt("Node dependencies", lambda: prepare_source_dependencies(+ project_root, workspaces, env=env, explicit=True)):+ # An update that changed no TUI/web input reuses the receipted output, as the+ # launch path already does; recompiling it produces the same bytes. Desktop+ # additionally needs the packaged app to name HEAD (its baked stamp carries the+ # commit), so it is reused only when HEAD did not move: "Already up to date",+ # a retried tail, a takeover re-entry.+ if "ui-tui" in frontends:+ if source_product_current(project_root, "tui", project_root / "ui-tui/dist"):+ print(" ✓ TUI is up to date")+ else:+ publish_stage("Building the TUI")+ attempt("TUI build", lambda: build_source_tui(project_root, env=env))+ if "web" in frontends:+ if source_product_current(project_root, "web", project_root / "hermes_cli/web_dist"):+ print(" ✓ Web UI is up to date")+ else:+ publish_stage("Building the web UI")+ attempt("web UI build", lambda: build_source_web(project_root, env=env))+ if desktop:+ attempt("desktop app build", lambda: _build_desktop_product(project_root, env, publish_stage))# A configured memory provider that no longer ships in core is installed from the# catalog for every profile home sharing this venv (config, data and tool names# unchanged). The update must finish even if the migration blows up.@@ -176,6 +180,38 @@ def build_update_products(project_root: Path, *, desktop: bool) -> None:migrate_left_core()except Exception as exc:print(f" ⚠ Plugin migration skipped: {exc}")+ if failures:+ raise ProductBuildError(failures)+++def _build_desktop_product(project_root: Path, env: dict, publish_stage) -> None:+ from hermes_cli.main_desktop import (+ _packaged_desktop_current_for_head, _refresh_installed_desktop_apps, build_prepared_desktop)++ desktop_dir = project_root / "apps/desktop"+ if _packaged_desktop_current_for_head(desktop_dir, project_root):+ print(" ✓ Desktop app is up to date")+ else:+ publish_stage("Building the desktop app")+ # The desktop build mutates checkout-scoped node_modules and+ # apps/desktop/release; serialize it against a concurrent manual+ # `hermes desktop` (#93940). The update path waits rather than exits:+ # the in-flight build it queues behind produces the same fresh tree+ # this update needs.+ from hermes_cli.desktop_build_lock import DesktopBuildLock++ build_lock = DesktopBuildLock(project_root)+ build_lock.acquire(wait=True)+ try:+ build_prepared_desktop(+ desktop_dir, source_mode=False,+ npm=shutil.which("npm", path=env["PATH"]), env=env, icons=project_root,+ )+ finally:+ build_lock.release()+ # A current release/ can still sit beside a stale installed copy (an earlier+ # update rebuilt but never installed); healing must not wait for the next build.+ _refresh_installed_desktop_apps(desktop_dir)if __name__ == "__main__":diff --git a/hermes_cli/source_completion.py b/hermes_cli/source_completion.pyindex f3df7d9cf47..603690ea25d 100644--- a/hermes_cli/source_completion.py+++ b/hermes_cli/source_completion.py@@ -36,11 +36,13 @@ def complete_source_checkout(pre_update_version: str | None = None,completion_message: str | None = None,announce: str | None = None,+ followups: list[tuple[str, str]] | None = None,) -> bool:"""Publish commands, build the products, then run post-build maintenance.- Returns the SQLite runtime verdict: a positive unsafe-runtime probe withholds- success here exactly as it does at the end of an update.+ Every step runs even when an earlier one failed; each failure is printed as ``⚠``,+ recorded on the open update receipt and appended to ``followups`` as ``(step, reason)``.+ Returns True only when every step finished and the SQLite runtime is not unsafe."""from hermes_cli.update_lock import UpdateLock, describe_holder@@ -65,7 +67,7 @@ def complete_source_checkout(root, desktop=desktop, assume_yes=assume_yes, gateway_mode=gateway_mode,pre_update_snapshot_id=pre_update_snapshot_id,pre_update_version=pre_update_version,- completion_message=completion_message, announce=announce,+ completion_message=completion_message, announce=announce, followups=followups,)finally:lock.release()@@ -81,6 +83,7 @@ def _complete_locked(pre_update_version: str | None,completion_message: str | None,announce: str | None,+ followups: list[tuple[str, str]] | None = None,) -> bool:"""The completion body; callers hold the update lock already."""from hermes_cli.source_build import build_update_products@@ -95,19 +98,36 @@ def _complete_locked(expose_pm_git(root)except Exception as exc: # noqa: BLE001 — git-less steps below still completeprint(f"⚠ Could not provide git for the source completion: {exc}", file=sys.stderr)- publish_launchers(root)- build_update_products(root, desktop=desktop)+ owed: list[tuple[str, str]] = []++ def step(name: str, run) -> None:+ # Each step is independent: a failed launcher publish or web build must not skip the+ # config migration, the maintenance, or (in an update) the gateway restart after it.+ try:+ run()+ except (Exception, SystemExit) as exc: # noqa: BLE001 — reported as an owed follow-up+ from hermes_cli.update_receipt import record_followup++ reason = str(exc) or type(exc).__name__+ record_followup(name, reason)+ owed.append((name, reason))++ step("launchers", lambda: publish_launchers(root))+ step("build", lambda: build_update_products(root, desktop=desktop))if announce:print(announce)- complete = _run_post_update_maintenance(+ verdict: list[bool] = []+ step("maintenance", lambda: verdict.append(_run_post_update_maintenance(assume_yes=assume_yes,gateway_mode=gateway_mode,pre_update_snapshot_id=pre_update_snapshot_id,had_desktop_app_before_update=desktop,pre_update_version=pre_update_version,completion_message=completion_message,- )- if complete:+ followups=owed,+ )))+ tail_done = not owed+ if tail_done:from hermes_cli.source_stamp import write_source_stamptry:@@ -115,7 +135,11 @@ def _complete_locked(except (OSError, ValueError) as exc:print(f"⚠ Source update completed, but the install stamp could not be written: {exc}",file=sys.stderr)- return complete+ if followups is not None:+ followups.extend(owed)+ # The SQLite verdict is not tail work (re-running the tail cannot fix the interpreter); it+ # is reported by the maintenance step itself and only withholds an install's success.+ return tail_done and all(verdict)def _bootstrap_command(root: Path, argv: list[str]) -> list[str]:@@ -155,11 +179,14 @@ def main(argv: list[str] | None = None) -> int:# pre-handoff release cannot flip during `hermes update`, so its# update ends with the tree at HEAD and nothing built -- lands here# on the next ordinary startup. Same tail as an install, so the two- # states cannot drift apart.- ok = complete_source_checkout(+ # states cannot drift apart. Only owed TAIL work keeps it pending: an+ # unsafe SQLite runtime is reported, but re-running the tail cannot fix it.+ owed: list[tuple[str, str]] = []+ complete_source_checkout(root, desktop=args.desktop, assume_yes=True,- completion_message=None, announce="\n✓ Code updated!",+ completion_message=None, announce="\n✓ Code updated!", followups=owed,)+ ok = not owedelse:ok = complete_source_checkout(root, desktop=args.desktop, assume_yes=not args.interactive,diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 13509f0674d..2d82730d867 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -544,7 +544,9 @@ def _log_only_write(text: str) -> None:log_file = getattr(stream, "_log", None)with suppress(Exception):if log_file is None:- log_path = get_hermes_home() / "logs" / "update.log"+ from hermes_constants import get_default_hermes_root++ log_path = get_default_hermes_root() / "logs" / "update.log" # the root home's teelog_path.parent.mkdir(parents=True, exist_ok=True)with log_path.open("a", encoding="utf-8") as fallback:fallback.write(text)@@ -749,8 +751,15 @@ def _complete_source_update(request: dict | None) -> None:_completion_receipt._current.reset(current.current_token)if result["exit_code"]:raise SystemExit(result["exit_code"])- if adopt_retired_channel(request):- print(f"→ Source subscription moved to {request['channel_retirement']['destination']}")+ try:+ if adopt_retired_channel(request):+ print(f"→ Source subscription moved to {request['channel_retirement']['destination']}")+ except Exception as exc: # noqa: BLE001 — the code is committed (C3); the next update re-adopts+ from hermes_cli.update_receipt import amend_terminal_followup, record_followup++ reason = str(exc) or type(exc).__name__+ record_followup("channel_adoption", reason, retry="the next `hermes update` adopts it again")+ amend_terminal_followup(request["receipt"]["update_id"], "channel_adoption", reason)def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_ref=None) -> None:diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex aec6e660123..1ebb1f3089b 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -401,7 +401,7 @@ def _marker_only_restart_obsolete() -> bool:undischargeable on every host that runs a dashboard. A manual-serve row still needs itsdurable handoff (``defer_manual_serve``), and an unclassified backend stays fail-closed.Discharging here strands nobody: the same row is still accounted at update time by- ``update_inventory.report_unaccounted_runtimes``, which prints it and exits 1 when the restart+ ``update_inventory.report_unaccounted_runtimes``, which prints it and records an owed restart when the restartphase never touched it — this marker only stops re-warning about it on every later startup."""from hermes_cli.update_cmd_fleet_checkout import checkout_contains@@ -1839,7 +1839,7 @@ def _collect_fleet_snapshot(restart, rows_expected: bool) -> list:Gateways need time to rewrite gateway_state.json; Windows resumes DETACHED (~10s boot),so a single 2s sleep reported "no rows" on healthy resumes. A "down" row may be adetached replacement still booting: poll until none remain or the deadline passes.- Pre-restart PIDs make a gateway stopped WITHOUT verified replacement a DOWN row (exit 1)+ Pre-restart PIDs make a gateway stopped WITHOUT verified replacement a DOWN row (owed restart)instead of no row at all. An ``unknown`` row whose pid is NOT a pre-restart pid is a successorthat has not published its code identity yet (a relaunched gateway can sit ~10s between processstart and its first runtime-status write, #112634) — keep polling; at the deadline it is flagged@@ -1917,13 +1917,52 @@ def _live_gateway_pids_from_fleet(fleet_rows: list) -> dict:return live+def _record_owed_gateway_inventory(plan) -> None:+ """Name the pre-update gateways on an inventory-less obligation once their restart is owed.++ The pull arms the obligation before the restart phase knows what it owes. An inventory-less+ record on a host whose gateway then died at boot is settled by the gateway-less discharge+ (nothing live, nothing named), which would silence the owed-restart warning that replaces a+ failed update under contract C3. A named inventory keeps it until those gateways run HEAD.+ """+ if plan is None:+ return+ armed = _fleet_restart_obligation_armed()+ fields = _obligation_fields() if armed else {}+ if fields is None or fields.get("inventory") not in (None, "", "null"):+ return # unreadable terms stay fail-closed; a recorded inventory is never rewritten+ from dataclasses import asdict+ rows = [+ asdict(runtime) for runtime in getattr(plan, "runtimes", ()) or ()+ if getattr(runtime, "kind", None) == "gateway"+ and isinstance(getattr(runtime, "profile", None), str)+ and runtime.profile.strip() and runtime.profile != "unknown"+ ]+ if rows:+ # Not armed any more (a pre-restart probe settled an inventory-less record): re-arm, the+ # restart is owed. The SHA is the code the fleet must be proven current on.+ sha = fields.get("expected_sha", "") if armed else (_current_checkout_sha() or "")+ _write_fleet_restart_pending_marker(expected_sha=sha, runtimes=rows)+++def _named_gateways_still_owed() -> bool:+ """True when the armed obligation NAMES gateways (recorded by an earlier owed restart) and the+ live fleet still does not prove them current. An inventory-less record keeps its old rules."""+ if not _fleet_restart_obligation_armed():+ return False+ fields = _obligation_fields()+ if fields is None or fields.get("inventory") in (None, "", "null"):+ return False+ return not _marker_only_restart_obsolete()++def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_resume, update_complete):"""Post-restart verification: legacy-unit warning, dashboard cleanup, stale serveprobe, fleet version matrix, plan-vs-execution reconciliation, receipt finalize.- Exits 1 (leaving ``fleet_restart_pending`` for the next catch-up) when any gateway- may still be stale; otherwise clears the marker. A failed SQLite verdict also- exits 1, without retaining a fulfilled fleet-restart obligation.+ Never fails the committed update (contract C3): when any gateway may still be stale it+ records a ``gateway_restart`` follow-up and leaves ``fleet_restart_pending`` armed for the+ next catch-up and the startup warning; otherwise clears the marker."""from hermes_cli.update_cmd import (_m, _surviving_pre_update_serve_runtimes, _warn_stale_serve_runtimes,@@ -1943,13 +1982,13 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_re# Success-path twin of the abort-recovery probe: the restart phase only touches# units, so a unit-less `hermes serve` keeps stale sys.modules. Runs AFTER# dashboard cleanup so a respawned manual dashboard isn't a survivor. Rows feed- # reconciliation (survivor → exit 1); ``None`` = probe failed, stays fail-closed.+ # reconciliation (survivor → owed restart); ``None`` = probe failed, stays fail-closed.# Check if any pre-update serve/dashboard runtimes survived on pre-update code generations (#100479).# This is the SUCCESS-path twin of the abort-recovery probe above: the restart phase only restarts# units, so an sshd-spawned `serve --isolated` or a manual `hermes serve` (no unit) is left running its# pre-update sys.modules graph — and its cron ticker keeps firing agent jobs that ImportError on every# symbol added in the pulled range. The rows also feed the plan-vs-execution reconciliation below, so a- # survivor is escalated (exit 1) instead of merely printed.+ # survivor is escalated (an owed gateway_restart follow-up) instead of merely printed._stale_serve_rows: "list | None" = Nonewith _best_effort('Failed to check for surviving serve runtimes: %s'):_stale_serve_rows = _surviving_pre_update_serve_runtimes(_pre_update_plan)@@ -1972,7 +2011,7 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_re# See #93406.# A gateway stopped WITHOUT a successor ("Restart manually") publishes no row by design,# so it must not count as an expected one — otherwise an update whose only live gateways- # were unmapped exits 1 with "no rows" after correctly stopping them.+ # were unmapped reports "no rows" after correctly stopping them._pre_restart, _killed = restart.fleet_probe_signals()_fleet_rows_expected = _m()._fleet_probe_expected_runtimes(_pre_update_plan, _pre_restart, _windows_gateway_resume, restart.restarted_services, _killed,@@ -1986,14 +2025,14 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_resignal_stale_fleet_survivors(_fleet_snapshot, restart, _gateway_drain_budget())elif not _fleet_snapshot and _fleet_rows_expected:# collect_fleet_versions() swallows every failure, so zero rows with- # expected runtimes is indistinguishable from health — fail (partial, exit 1).+ # expected runtimes is indistinguishable from health — keep the restart owed.print(# Fleet probe returned zero rows even though at least one gateway runtime was (or may have# been) live pre-update — POSIX restart bookkeeping, the pre-restart PID snapshot, the# pre-update plan inventory, or the Windows pause/resume token all count as that signal.# Every failure path inside collect_fleet_versions() is swallowed via logger.debug(), so an# empty list is indistinguishable from a healthy fleet in the current output. Treat it as- # verification failure so the receipt records "partial" and the exit code is 1 (#93406).+ # verification failure so the receipt carries a gateway_restart follow-up (#93406)."\n⚠ Fleet version check returned no rows even though"" gateway runtimes were expected — verification incomplete.")@@ -2047,28 +2086,54 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_reif _active is not None:_active.data["runtime_outcomes"] = _runtime_outcomes+ if not restart.incomplete:+ with _best_effort('Owed-gateway check failed: %s'):+ if _named_gateways_still_owed():+ # A gateway a previous run could not restart is still not serving HEAD (nothing+ # live to restart this time): keep owing it rather than clearing the obligation.+ print(" ⚠ A gateway owed a restart by a previous update is still not serving this checkout.")+ restart.incomplete = True+ if getattr(restart, "stopped_unmapped_pids", None):+ # A gateway stopped with no successor is owed a restart, not "accounted for": keep the+ # fleet obligation armed so the startup warning names it until someone restarts it.+ restart.incomplete = True+ if restart.incomplete:+ # Code is committed (contract C3): a gateway that may still run stale modules is a+ # follow-up, never a failed update. The fleet obligation stays armed, every CLI start+ # warns about it, and the next `hermes update` retries the restart.+ from hermes_cli.update_receipt import record_followup+ stopped = sorted(getattr(restart, "stopped_unmapped_pids", None) or ())+ record_followup(+ "gateway_restart",+ "gateways may still run pre-update code or were stopped without a successor"+ + (f" (stopped PIDs {', '.join(map(str, stopped))})" if stopped else "")+ + "; recover with `hermes gateway restart`",+ )+ with _best_effort('Fleet restart inventory not recorded: %s'):+ _record_owed_gateway_inventory(_pre_update_plan)with _best_effort('Update receipt finalize failed: %s'):from hermes_cli.update_receipt import finalize_update_receipt- _receipt_path = finalize_update_receipt(- "partial" if restart.incomplete or not update_complete else "success",- fleet=_fleet_snapshot,- )+ # ``update_complete`` is kept for the historical takeover caller; a False verdict (the+ # SQLite runtime) is reported as a follow-up by the maintenance step, not a failed run.+ _receipt_path = finalize_update_receipt("success", fleet=_fleet_snapshot)if _receipt_path is not None:logger.info("Update receipt written: %s", _receipt_path)if restart.incomplete:- # Code updated but a gateway may still run stale modules: fail so automation- # doesn't treat the fleet as healthy; leave the pending marker for catch-up.- sys.exit(1)+ return_clear_fleet_restart_pending_marker()if not update_complete:- # Fleet caught up, but the independently checked SQLite runtime is unsafe.- sys.exit(1)+ # Fleet caught up, but the selected runtime's SQLite is unsafe (reported by maintenance):+ # leave the topology alone until the runtime is repaired.+ return# Fleet is healthy on the new code: fold per-profile gateways into one multiplexer when nothing# blocks it (deterministic; never prompts), else print the blockers and the one-liner to run later.- with _best_effort('Multiplex auto-migration after update failed: %s'):+ try:from hermes_cli.gateway_migrate import maybe_auto_migrate_after_updatemaybe_auto_migrate_after_update()+ except (Exception, SystemExit) as exc: # noqa: BLE001 — a SystemExit here must not fail a committed update+ logger.warning('Multiplex auto-migration after update failed: %s', exc)+ print(f" ⚠ Gateway multiplex migration did not finish: {exc} (run `hermes gateway migrate` later)")def _restart_phase_failure_is_incomplete(surviving, pre_restart_pids) -> bool:diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex 193ac25e27a..3cb353f7b5a 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -289,7 +289,7 @@ def _refresh_dashboard_after_update(*, already_restarted_units: set[str] | None# Isolated like every sibling post-update step: a failure here (#112604) used to abort# the fleet matrix, reconciliation and the inner receipt finalize that follow it. A# dashboard/serve left on pre-update code is still caught by the survivor probe →- # reconciliation (exit 1).+ # reconciliation (an owed gateway_restart follow-up).logger.warning("Post-update dashboard cleanup failed: %s", exc)_record_update_step("dashboard_cleanup", False, f"{type(exc).__name__}: {exc}")print()@@ -809,14 +809,26 @@ def _run_pre_update_backup(args) -> Optional[str]:def _sweep_bytecode_after_update(branch: str) -> None:"""Clear stale ``__pycache__`` (else gateway restart ImportErrors on names absent from old- bytecode), re-stamp the fingerprint, refresh the bootstrap cache scripts."""+ bytecode), re-stamp the fingerprint, refresh the bootstrap cache scripts.++ Never fails the committed update: a failed sweep is a ``bytecode_sweep`` follow-up and the+ fingerprint stays un-stamped, so the launch-time sweep (fingerprint mismatch) retries it.+ """from hermes_cli.update_cmd import _m+ from hermes_cli.update_receipt import record_followup# Timestamp-based .pyc validation can accept old bytecode after the source swap.- removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)- if removed:- print(f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}")- _m()._record_bytecode_fingerprint()- _m()._refresh_bootstrap_cache_scripts(branch)+ try:+ removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)+ if removed:+ print(f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}")+ _m()._record_bytecode_fingerprint()+ except Exception as exc: # noqa: BLE001 — owed to the next launch's fingerprint sweep+ record_followup("bytecode_sweep", str(exc) or type(exc).__name__)+ try:+ _m()._refresh_bootstrap_cache_scripts(branch)+ except Exception as exc: # noqa: BLE001 — refreshed again by the next update+ record_followup("bootstrap_scripts", str(exc) or type(exc).__name__,+ retry="the next `hermes update` refreshes them")def _profile_skill_sync_status(r) -> str:@@ -967,12 +979,26 @@ def _migrate_relay_exporter_env() -> None:def _run_post_update_maintenance(*, assume_yes, gateway_mode, pre_update_snapshot_id, had_desktop_app_before_update,- pre_update_version, completion_message=None,+ pre_update_version, completion_message=None, followups=None,) -> bool:"""Post-build housekeeping and completion, returning the SQLite runtime verdict.- Ancillary repairs and notices are best-effort; an unsafe runtime withholds success.+ Ancillary repairs and notices are best-effort. The profile sync and the config migration run+ after a failed build too and never fail the committed update: a failure is printed as ``⚠``,+ recorded as a receipt follow-up and appended to ``followups`` so the tail stays owed. An+ unsafe runtime withholds success (and is reported) but is not tail work."""+ from hermes_cli.update_receipt import record_followup++ def owed_step(name, run):+ try:+ run()+ except (Exception, SystemExit) as exc: # noqa: BLE001 — the code is committed; retry later+ reason = str(exc) or type(exc).__name__+ record_followup(name, reason)+ if followups is not None:+ followups.append((name, reason))+from hermes_cli.update_cmd import _check_and_apply_config_migration, _m# macOS TCC: Desktop bundles are re-signed each update, so old grants can go stale# (toggle ON, yet macOS re-prompts with no Allow button). Tell users how to re-grant.@@ -1030,11 +1056,11 @@ def _run_post_update_maintenance(print("→ Syncing bundled skills...")_print_bundled_skills_sync_report()- _sync_profiles_after_update()+ owed_step("profile_sync", _sync_profiles_after_update)- _check_and_apply_config_migration(+ owed_step("config_migration", lambda: _check_and_apply_config_migration(assume_yes=assume_yes, gateway_mode=gateway_mode, pre_update_snapshot_id=pre_update_snapshot_id,- )+ ))print()update_complete = _print_verified_update_completion(completion_message or _update_complete_message(pre_update_version))@@ -1045,5 +1071,9 @@ def _run_post_update_maintenance(for line in [*consume_rewritten_notice(), *recorded_standalone_warning_lines()]:print(line)- _print_post_update_notices_and_self_heals()+ with _best_effort('Post-update notices failed: %s'):+ _print_post_update_notices_and_self_heals()+ if not update_complete:+ record_followup("sqlite_runtime", "the selected Python links an unsafe SQLite runtime",+ retry="run the installer again")return update_completediff --git a/hermes_cli/update_cmd_stale_survivors.py b/hermes_cli/update_cmd_stale_survivors.pyindex e1716ff8143..d70c408117d 100644--- a/hermes_cli/update_cmd_stale_survivors.py+++ b/hermes_cli/update_cmd_stale_survivors.py@@ -1,7 +1,7 @@"""Post-update escalation for gateways the fleet matrix proved stale.``_verify_fleet_after_update`` compares every live gateway's stamped ``code_sha`` against the-fresh checkout. Until now a ``stale`` row only failed the update (exit 1) and left the process+fresh checkout. A ``stale`` row once only failed the update (exit 1) and left the processrunning pre-update modules: its cron ticker then yields every tick to the "fresh gateway" itassumes exists, and nothing ever restarts it (#117275). A proven-stale survivor is now handed tothe same drain-first ``request_restart`` path (SIGUSR1) the restart phase uses — a supervised@@ -29,7 +29,7 @@ def signal_stale_fleet_survivors(fleet: list, restart, drain_budget: float) -> l"""Drain-first restart every proven-stale gateway; returns the PIDs signalled.Bookkeeping lands in ``restart.killed_pids`` so the receipt and the survivor sweep see them.- Never raises: verification must still finalize the receipt and exit 1.+ Never raises: verification must still finalize the receipt (with an owed restart)."""from hermes_cli.update_cmd_fleet import _drain_or_signal_gateway_for_update@@ -58,6 +58,11 @@ def signal_stale_fleet_survivors(fleet: list, restart, drain_budget: float) -> llogger.warning("Could not signal stale gateway PID %s: %s", pid, exc)print(f" ⚠ {label}: could not be signalled ({exc}) — restart it by hand")if manual:+ # No successor: the receipt's gateway_restart follow-up names them and the fleet+ # obligation stays armed, so the stop is never silent (codemap §6 V7).+ stopped = getattr(restart, "stopped_unmapped_pids", None)+ if isinstance(stopped, set):+ stopped.update(manual)print(f" → Stopped {len(manual)} manual gateway process(es) that had no supervisor to respawn them")print(" Restart manually: hermes gateway run")if len(manual) > 1:diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex 011e57a8933..d3732b72440 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -132,8 +132,11 @@ def _resume_receipt(data: dict) -> None:def _read_terminal_receipt(request: dict) -> dict | None:- directory = Path(request["home"]) / "logs/update_receipts"- # Never latest.json: another profile/context may have finalized more recently.+ from hermes_cli.update_receipt import _receipt_dir++ # The ROOT home's receipts (the run's own file), never latest.json: another+ # profile/context may have finalized more recently.+ directory = _receipt_dir()for path in directory.glob(f"update_*_{request['receipt']['update_id']}.json"):data = json.loads(path.read_text(encoding="utf-8-sig"))if data.get("update_id") == request["receipt"]["update_id"] and data.get("finished_at"):@@ -181,9 +184,16 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:def _complete_selected(request: dict) -> None:+ """Everything after the commit point. Nothing here fails the update (contract C3).++ Each step is independent; a failed one prints ``⚠``, lands on the receipt as a follow-up+ and keeps its own obligation armed (``source-completion-pending`` for the tail, the fleet+ restart obligation for gateways), so the next launch or ``hermes update`` retries it.+ """from hermes_cli import main, update_cmd, update_cmd_configfrom hermes_cli.source_completion import complete_source_checkoutfrom hermes_cli.update_inventory import RuntimeRecord, UpdatePlan+ from hermes_cli.update_receipt import TAIL_FOLLOWUPS, record_followup, record_skip, record_stageroot = Path(request["source"])main.PROJECT_ROOT = root@@ -194,50 +204,49 @@ def _complete_selected(request: dict) -> None:update_cmd._sweep_bytecode_after_update(request["branch"])# Launchers, products and post-build maintenance live in one place so an# install and an update cannot end in different states.- complete = complete_source_checkout(- root, desktop=request["desktop"], assume_yes=request["assume_yes"],- gateway_mode=request["gateway_mode"], pre_update_snapshot_id=request["snapshot_id"],- pre_update_version=request["pre_update_version"],- completion_message=request.get("completion_message"),- announce=None if request.get("completion_message") else "\n✓ Code updated!")- from hermes_cli.update_receipt import record_stage- record_stage("build", "success" if complete else "failed")- if complete:+ followups: list[tuple[str, str]] = []+ try:+ complete_source_checkout(+ root, desktop=request["desktop"], assume_yes=request["assume_yes"],+ gateway_mode=request["gateway_mode"], pre_update_snapshot_id=request["snapshot_id"],+ pre_update_version=request["pre_update_version"],+ completion_message=request.get("completion_message"),+ announce=None if request.get("completion_message") else "\n✓ Code updated!",+ followups=followups)+ except (Exception, SystemExit) as exc: # noqa: BLE001 — e.g. the shared update lock refused the tail+ reason = str(exc) or type(exc).__name__+ record_followup("completion", reason)+ followups.append(("completion", reason))+ tail_owed = any(step in TAIL_FOLLOWUPS for step, _ in followups)+ record_stage("build", "failed" if tail_owed else "success")+ if not tail_owed:from hermes_cli.venv_sync import clear_completionclear_completion(root)# systemctl's KillMode=mixed fallback can kill this whole cgroup. Publish the- # gateway watcher's status BEFORE that operation, and demote on later failure.+ # gateway watcher's status BEFORE that operation: the code is committed, so it is 0.if request["gateway_mode"]:- update_cmd._write_gateway_update_exit_code(complete)+ update_cmd._write_gateway_update_exit_code(True)if request.get("no_gateway_restart", False):- from hermes_cli.update_receipt import record_skip-record_skip("gateway_restart", "--no-gateway-restart: deferred, marker kept")record_stage("restart", "skipped")print("→ Gateway restart deferred (--no-gateway-restart); restart gateways separately.")- if not complete:- raise SystemExit(1)returnskip = update_cmd._fleet_restart_skip_reason(plan)+ if skip and update_cmd._pending_fleet_restart_needed():+ # A host already stamped "restarted" for this SHA whose fleet is still off the checkout+ # (a stale sibling, a failed resume) gets the restart again instead of a dead end.+ print(f" → Gateway restart not skipped ({skip}): gateways are still off the checkout code.")+ skip = Noneif skip:- from hermes_cli.update_receipt import record_skip-record_skip("gateway_restart", skip)record_stage("restart", "skipped")print(f" ✓ Gateway restart skipped: {skip}.")- # Discharges the obligation this run armed when the live fleet vouches for it; a- # fleet still owing the restart fails closed exactly like a stale matrix would.- if update_cmd._pending_fleet_restart_needed():- print(" ⚠ Gateways are still off the checkout code. Recover with: hermes gateway restart")- raise SystemExit(1)- if not complete:- raise SystemExit(1)returnrestart = update_cmd._restart_gateway_fleet_after_update(plan, request["gateway_mode"])record_stage("restart", "failed" if getattr(restart, "incomplete", False) else "success")update_cmd._resume_windows_gateways_and_merge_outcome(restart, request["windows_resume"], request["gateway_mode"])update_cmd._verify_fleet_after_update(- restart, _pre_update_plan=plan, _windows_gateway_resume=request["windows_resume"], update_complete=complete)+ restart, _pre_update_plan=plan, _windows_gateway_resume=request["windows_resume"], update_complete=True)class _ForwardedOutput:@@ -263,13 +272,15 @@ def _finish(request: dict, result_path: Path) -> int:code, reason = 0, "source update completion"try:_complete_selected(request)+ except KeyboardInterrupt:+ # An operator interrupt is not a step failure; the armed obligations finish the tail.+ code, reason = 1, "KeyboardInterrupt: completion interrupted"+ print("✗ Source update completion interrupted; the next launch or `hermes update` finishes it")except SystemExit as exc:- code = _exit_status(exc.code) if isinstance(exc.code, int) else 1- reason = f"completion exited {code}"- except BaseException as exc:- code = _exit_status(exc.returncode) if isinstance(exc, subprocess.CalledProcessError) else 1- reason = f"{type(exc).__name__}: {exc}"- print(f"✗ Source update completion failed: {reason}")+ if exc.code not in (0, None):+ update_receipt.record_followup("completion", f"completion exited {exc.code}")+ except BaseException as exc: # noqa: BLE001 — after the commit point nothing fails the update+ update_receipt.record_followup("completion", f"{type(exc).__name__}: {exc}")finally:if code and request["gateway_mode"]:from hermes_cli.update_cmd import _write_gateway_update_exit_code@@ -280,8 +291,10 @@ def _finish(request: dict, result_path: Path) -> int:from hermes_cli.update_cmd import _resume_windows_gateways_after_update_resume_windows_gateways_after_update(request["windows_resume"])except Exception as exc:- code, reason = 1, f"Windows gateway recovery failed: {exc}"- print(f"✗ {reason}")+ step_reason = f"Windows gateway recovery failed: {exc}"+ update_receipt.record_followup("windows_resume", step_reason)+ if update_receipt._current.get() is None: # verification already finalized this run+ update_receipt.amend_terminal_followup(request["receipt"]["update_id"], "windows_resume", step_reason)update_receipt.finalize_pending_update_receipt(code, reason)terminal_receipt = _read_terminal_receipt(request)if not terminal_receipt:diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.pyindex a5762a519dd..fac8b12a26c 100644--- a/hermes_cli/update_inventory.py+++ b/hermes_cli/update_inventory.py@@ -542,7 +542,7 @@ def report_unaccounted_runtimes(outcomes: list[dict[str, Any]]) -> bool:"""Print a loud warning for runtimes the restart phase never touched.Returns True when at least one planned runtime is unaccounted; the caller escalates like a- STALE/DOWN fleet row (exit 1) — a promised restart silently missed is the class this phase+ STALE/DOWN fleet row (an owed ``gateway_restart`` follow-up) — a promised restart silently missed is the class this phaseexists to kill."""manual = [o for o in outcomes if o.get("outcome") == "deferred" and o.get("mechanism") == "respawn-argv"]diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex b1a6c72c7dc..1f479bc5280 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -33,6 +33,7 @@ import copyimport jsonimport loggingimport os+import reimport sysimport timeimport uuid@@ -142,6 +143,9 @@ class UpdateReceipt:def fact(self, key: str, value: Any) -> None:self.data[key] = value+ def followup(self, step: str, reason: str) -> None:+ self.data.setdefault("followups", []).append({"step": step, "reason": reason, "at": _utc_now_iso()})+def gateway_restart_result(self, *, restarted_services: list | None = None, relaunched_profiles: list | None = None,externally_supervised_profiles: list | None = None, killed_pids: list | None = None,@@ -192,14 +196,78 @@ class UpdateReceipt:def _receipt_dir() -> Path:# ``hermes_constants`` (stdlib-only), never ``hermes_cli.config``: the receipt must be# writable from the refused/failed paths where config loading itself may be what broke- # (#112465, #112558).- from hermes_constants import get_hermes_home+ # (#112465, #112558). The ROOT home, never a sticky profile's: an update mutates the+ # checkout every profile shares, and the Desktop and the hand-off scripts read the root.+ from hermes_constants import get_default_hermes_root++ return get_default_hermes_root() / "logs" / "update_receipts"+++def _run_file(directory: Path, data: dict[str, Any]) -> Path:+ """One archive file per run, named at begin so the running and terminal records coincide."""+ stamp = re.sub(r"[^0-9]", "", str(data.get("started_at") or ""))[:14] or time.strftime("%Y%m%d%H%M%S")+ return directory / f"update_{stamp[:8]}_{stamp[8:]}_{data.get('pid') or os.getpid()}_{data.get('update_id')}.json"+++def _persist_running(data: dict[str, Any]) -> None:+ """Write the open run to disk: a killed update still leaves its own record. Never raises."""+ with suppress(Exception):+ from hermes_cli.runtime_state import _atomic_bytes++ directory = _receipt_dir()+ directory.mkdir(parents=True, exist_ok=True)+ payload = (json.dumps({**data, "writer_pid": os.getpid()}, indent=2, default=str) + "\n").encode("utf-8")+ _atomic_bytes(_run_file(directory, data), payload)+ _atomic_bytes(directory / "latest.json", payload)- return get_hermes_home() / "logs" / "update_receipts"++def _owner_alive(record: dict[str, Any]) -> bool:+ from hermes_cli.process_identity import _pid_alive_matches++ for key in ("pid", "writer_pid"):+ pid = record.get(key)+ if isinstance(pid, int) and pid > 0 and pid != os.getpid():+ create_time = record.get("pid_create_time") if key == "pid" else None+ if _pid_alive_matches(pid, create_time) is not False:+ return True+ return False+++def reconcile_interrupted_runs() -> list[dict[str, Any]]:+ """Mark ``running`` records whose processes are gone as ``interrupted``; returns them.++ The start-of-run reclaimer for the durable running receipt: the next update says plainly+ that the previous one was killed and at which stage, instead of reporting its outcome as+ whatever ran before it. Never raises.+ """+ interrupted: list[dict[str, Any]] = []+ with suppress(Exception):+ from hermes_cli.runtime_state import _atomic_bytes++ directory = _receipt_dir()+ latest = read_latest_receipt() or {}+ for path in sorted(directory.glob("update_*.json"), key=lambda p: p.stat().st_mtime)[-_RECEIPT_KEEP:]:+ with suppress(Exception):+ record = json.loads(path.read_text(encoding="utf-8-sig"))+ if not isinstance(record, dict) or record.get("outcome") != "running" or _owner_alive(record):+ continue+ stages = record.get("stages") or []+ last = stages[-1].get("name") if stages and isinstance(stages[-1], dict) else None+ record.update(outcome="interrupted", interrupted_detected_at=_utc_now_iso(),+ stop_reason=f"process exited during the update (last stage: {last or 'start'})")+ payload = (json.dumps(record, indent=2, default=str) + "\n").encode("utf-8")+ _atomic_bytes(path, payload)+ if latest.get("update_id") == record.get("update_id"):+ _atomic_bytes(directory / "latest.json", payload)+ interrupted.append(record)+ for record in interrupted:+ print(f"⚠ The previous update ({record.get('started_at')}) was interrupted before it finished "+ f"({record.get('stop_reason')}); this update completes the work it still owed.")+ return interrupteddef begin_update_receipt(*, previous: dict | None = None, correlation_id: str | None = None) -> None:- """Start recording a new update receipt.+ """Start recording a new update receipt, durably ``running`` until it finalizes.Nested updates are safe: the previous receipt (if any) is preservedbehind the ContextVar token and comes back when this one finalizes —@@ -213,10 +281,71 @@ def begin_update_receipt(*, previous: dict | None = None, correlation_id: str |receipt.data.update(update_id=receipt.correlation_id, outcome="running", finished_at=None)# A handoff receipt from an older interpreter may predate the field.receipt.data["correlation_id"] = receipt.data.get("correlation_id") or _launcher_correlation_id()+ with suppress(Exception):+ from hermes_cli.process_identity import _process_create_time++ receipt.data.setdefault("pid_create_time", _process_create_time(receipt.data["pid"]))+ if not previous:+ reconcile_interrupted_runs()+ # The running record is about to replace latest.json: snapshot the previous record's+ # manual serve rows (raw, no side effects) for finalize's carry-forward.+ with suppress(Exception):+ prior = read_latest_receipt() or {}+ rows = list((prior.get("plan") or {}).get("runtimes") or [])+ rows += list(prior.get("pending_manual_serves") or [])+ receipt.data["carried_manual_serves"] = [+ row for row in rows if isinstance(row, dict) and row.get("supervisor") == "manual-serve"]except Exception as exc: # pragma: no cover - defensivelogger.debug("Could not start update receipt: %s", exc)returnreceipt.current_token = _current.set(receipt)+ _persist_running(receipt.data)+++def persist_running_receipt() -> None:+ """Re-assert the open run on disk (the completion child calls this after resuming it)."""+ current = _current.get()+ if current is not None and current.data.get("outcome") == "running":+ _persist_running(current.data)+++#: Follow-up steps whose failure leaves the source-update tail owed (``source-completion-pending``).+TAIL_FOLLOWUPS = frozenset({"launchers", "build", "maintenance", "config_migration", "completion"})+++def record_followup(step: str, reason: str, *, retry: str = "the next launch or `hermes update` retries it") -> None:+ """A post-commit step failed: print ⚠, keep the run a success, and say what is still owed.++ The code already committed, so the update does not fail; the step's own obligation (the+ source tail, the fleet restart, the launch-time bytecode sweep) stays armed and the next+ launch or ``hermes update`` retries it. Never raises.+ """+ reason = " ".join(str(reason).split())[:500] or "failed"+ print(f" ⚠ Update follow-up '{step}' did not finish: {reason} ({retry})", flush=True)+ current = _current.get()+ if current is None:+ return+ _record("followup", f"update followup {step}", step, reason)+ current = _current.get()+ if current is not None:+ _persist_running(current.data)+++def amend_terminal_followup(update_id: str, step: str, reason: str) -> None:+ """A follow-up that failed after the run's receipt was finalized lands on that receipt. Never raises."""+ with suppress(Exception):+ from hermes_cli.runtime_state import _atomic_bytes++ directory = _receipt_dir()+ for path in directory.glob(f"update_*_{update_id}.json"):+ record = json.loads(path.read_text(encoding="utf-8-sig"))+ if record.get("update_id") != update_id:+ continue+ record.setdefault("followups", []).append({"step": step, "reason": reason, "at": _utc_now_iso()})+ payload = (json.dumps(record, indent=2, default=str) + "\n").encode("utf-8")+ _atomic_bytes(path, payload)+ if (read_latest_receipt() or {}).get("update_id") == update_id:+ _atomic_bytes(directory / "latest.json", payload)def _record(method: str, what: str, *args: Any, **kwargs: Any) -> None:@@ -254,6 +383,8 @@ def record_skip(name: str, reason: str) -> None:def record_stage(name: str, outcome: str, **facts: str) -> None:"""Mark the END of a pipeline stage (``success``/``failed``/``skipped``) with a timestamp."""_record("stage", f"update stage {name}", name, outcome, **facts)+ # Each stage boundary refreshes the durable running record (a kill names its last stage).+ persist_running_receipt()def record_fact(key: str, value: Any) -> None:@@ -299,7 +430,11 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason# receipt's still-pending rows forward so the startup warning survives (see# update_serve_obligations).from hermes_cli.update_serve_obligations import retain_receipt_manual_serves- pending = retain_receipt_manual_serves(read_latest_receipt() or {})+ if "carried_manual_serves" in receipt.data:+ prior = {"pending_manual_serves": receipt.data.pop("carried_manual_serves") or []}+ else: # a receipt begun before the running record existed+ prior = read_latest_receipt() or {}+ pending = retain_receipt_manual_serves(prior)if pending:receipt.data["pending_manual_serves"] = pending# EMBED the pm sync sections (the settled receipts contract): the@@ -335,10 +470,8 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason# latest.json pointer (no torn readers).from hermes_cli.runtime_state import _atomic_bytes- path = directory / (- f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}_"- f"{receipt.correlation_id}.json"- )+ # The run's own file (named at begin): the durable running record becomes terminal.+ path = _run_file(directory, receipt.data)payload = (json.dumps(receipt.data, indent=2, default=str) + "\n").encode("utf-8")_atomic_bytes(path, payload)with suppress(Exception): # stable pointer for the dashboard/desktop@@ -459,7 +592,7 @@ def settle_latest_receipt_fleet(fleet: list[dict[str, Any]], *, discharges) -> bmatrix as the receipt's post-restart ``fleet`` (and un-flagging ``gateway_restart``) is whatlets the stale-runtime readers see the recovery. ``discharges(settled_receipt)`` decides onthe in-memory copy; ``latest.json`` is rewritten only when it answers True, so a catch-up- that still exits 1 leaves the receipt byte-identical. Only the ``latest.json`` pointer is+ that still owes the restart leaves the receipt byte-identical. Only the ``latest.json`` pointer isrewritten; the archived per-run file keeps the original outcome. Never raises."""try:@@ -784,12 +917,11 @@ def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:print(" ⚠ Stale gateways keep serving pre-update code until restarted.")if "down" in states:print(" ⚠ Down gateways stopped serving messaging entirely.")- # ``✓ Update complete!`` was already printed before the restart phase (the exit code- # must land before a systemd restart can kill this process), so this verdict has to- # supersede it explicitly — otherwise the output says success while the exit code is 1.+ # The code is committed (the update exits 0), but the fleet is not on it yet: say what+ # is still owed after ``✓ Update complete!``; every CLI start repeats it until restarted.print()print(- f"✗ Update not complete: {stale_or_down} gateway(s) still running the old code (or stopped).")+ f"⚠ Gateway restart still owed: {stale_or_down} gateway(s) still running the old code (or stopped).")print(" Run `hermes gateway restart` (or `hermes -p <profile> gateway restart` for a named")print(" profile), then `hermes gateway status` to confirm.")return stale_or_down > 0diff --git a/tests/e2e/core/upgrade/git/test_hostile_post.py b/tests/e2e/core/upgrade/git/test_hostile_post.pynew file mode 100644index 00000000000..db598f6ef5e--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_hostile_post.py@@ -0,0 +1,533 @@+"""Once ``hermes update`` has committed the new code, the update never fails (contract C3).++One real HEAD install (``_git_world``: the real ``scripts/install.sh`` over real smart HTTP, every+command in a ``bwrap`` sandbox) is shared by the cells. Each cell publishes a hostile upstream+release and breaks something that runs AFTER the checkout moved, for real:++(a) the web UI build fails: the release's own ``scripts/build/web.mjs`` exits 1 while+ ``$HOME/.e2e-break-web-build`` exists, and the release changes a web build input (``web.mjs``+ itself lives under ``scripts/build``, plus a new file under ``web/``) so ``freshness.mjs`` reports+ the web UI stale and the updater must build it. A config migration is owed too+ (``_config_version`` lowered by one): one failed step must not skip later independent ones.+(b) a gateway that refuses to restart: a credential-free, platform-less (cron-only) ``hermes+ gateway run`` lives in the same PID namespace as the updater (``handoff._nshost``). The release+ makes ``hermes_cli.gateway.run_gateway`` exit 1 before booting while+ ``$HOME/.e2e-break-gateway-boot`` exists. The updater drains the OLD gateway (pre-update code,+ no fault) and its relaunch boots the NEW code, which refuses to start: the restart fails for real,+ no gateway serves the new commit. Removing the toggle and updating again must retry the owed+ restart.+(c) SIGKILL during the post-commit tail: the release's ``web.mjs`` writes+ ``$HOME/.e2e-web-build-started`` and sleeps 120 s while ``$HOME/.e2e-slow-web-build`` exists. The+ update runs in the shared namespace; once the slow build started, every process born after the+ update was spawned is SIGSTOPped then SIGKILLed (that is the whole update tree, including a+ completion child in its own session or reparented to the namespace init).+(d) a sticky profile (``hermes profile use e2epost``) must not move update.log / receipts off the+ root hermes home.++What is asserted is what the user sees: the exit code, ``⚠`` lines, the receipt at+``<root>/logs/update_receipts/latest.json`` (``outcome``, ``followups``), the+``source-completion-pending`` obligation in the install-state dir, the config version, the+owed-restart warning a later command prints, and which gateway (by its control-socket ``identify``)+serves the checkout.+"""++from __future__ import annotations++import contextlib+import json+import os+import re+import shutil+import signal+import tempfile+import time+from pathlib import Path+from typing import Iterator++import pytest++import hermes_yaml as yaml+from tests.e2e.core.upgrade import _helpers as H+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git import _git_world as G+from tests.e2e.core.upgrade.handoff._nshost import NamespaceHost++pytestmark = G.PYTESTMARK++WARN = "⚠"+BREAK_WEB = ".e2e-break-web-build"+SLOW_WEB = ".e2e-slow-web-build"+WEB_STARTED = ".e2e-web-build-started"+BREAK_GATEWAY = ".e2e-break-gateway-boot"+TOGGLES = (BREAK_WEB, SLOW_WEB, WEB_STARTED, BREAK_GATEWAY)+WEB_FAULT_TEXT = "e2e: the web build fails on purpose"+GATEWAY_FAULT_TEXT = "e2e: gateway boot refused on purpose"+OWED_RESTART = "did not restart running gateways" # update_cmd_fleet._warn_pending_fleet_restart+PROFILE = "e2epost"+UPDATE_TIMEOUT = 1500+_WEB_MARK = "// e2e (test_hostile_post): hostile build toggles"+_GATEWAY_MARK = "# e2e (test_hostile_post): hostile gateway boot toggle"++_HOSTILE_WEB = f"""{_WEB_MARK}, keyed on files in $HOME.+import {{ existsSync as e2eExists, writeFileSync as e2eWrite }} from 'node:fs'+import {{ homedir as e2eHomedir }} from 'node:os'+const e2eHomes = [...new Set([process.env.HOME, e2eHomedir()].filter(Boolean))]+const e2eToggle = name => e2eHomes.some(home => e2eExists(`${{home}}/${{name}}`))+if (e2eToggle('{BREAK_WEB}')) {{+ console.error('{WEB_FAULT_TEXT} ({BREAK_WEB})')+ process.exit(1)+}}+if (e2eToggle('{SLOW_WEB}')) {{+ for (const home of e2eHomes) {{ try {{ e2eWrite(`${{home}}/{WEB_STARTED}`, String(process.pid)) }} catch {{}} }}+ console.log('e2e: slow web build started ({SLOW_WEB})')+ await new Promise(resolve => setTimeout(resolve, 120000))+}}+"""++_HOSTILE_GATEWAY = f""" {_GATEWAY_MARK}+ if __import__("os").path.exists(__import__("os").path.join(__import__("os").path.expanduser("~"), "{BREAK_GATEWAY}")):+ print("{GATEWAY_FAULT_TEXT} ({BREAK_GATEWAY})", file=__import__("sys").stderr, flush=True)+ raise SystemExit(1)+"""+++# -- the shared install --------------------------------------------------------------------------++[email protected](scope="module")+def w() -> Iterator[G.World]:+ """A SHORT root (the gateway's AF_UNIX control socket lives under ``$HERMES_HOME``; pytest's deep+ ``tmp_path`` overflows ``sun_path``). Set ``HERMES_E2E_KEEP_ROOT=1`` to keep it for a post-mortem."""+ base = os.environ.get("TMPDIR") or tempfile.gettempdir()+ root = Path(tempfile.mkdtemp(prefix="hp", dir=base))+ try:+ with G.world(root, base=I.head_sha()) as world:+ _edit_config(world, lambda cfg: cfg.update(updates={**(cfg.get("updates") or {}), "check": False}))+ yield world+ finally:+ if not os.environ.get("HERMES_E2E_KEEP_ROOT"):+ shutil.rmtree(root, ignore_errors=True)+++def _config_path(w: G.World) -> Path:+ return w.sb.hermes_home / "config.yaml"+++def _load_config(w: G.World) -> dict:+ p = _config_path(w)+ data = yaml.safe_load(p.read_text(encoding="utf-8-sig")) if p.is_file() else None+ return data if isinstance(data, dict) else {}+++def _edit_config(w: G.World, edit) -> None:+ cfg = _load_config(w)+ edit(cfg)+ _config_path(w).write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+++def _config_version(w: G.World) -> int | None:+ v = _load_config(w).get("_config_version")+ return int(v) if isinstance(v, int) or (isinstance(v, str) and v.isdigit()) else None+++def _toggle(w: G.World, name: str, on: bool) -> None:+ p = w.sb.home / name+ if on:+ p.write_text("on\n", encoding="utf-8")+ else:+ p.unlink(missing_ok=True)+++def _clear_toggles(w: G.World) -> None:+ for name in TOGGLES:+ _toggle(w, name, False)+++def _pending_markers(w: G.World) -> list[str]:+ """The ``source-completion-pending`` obligation(s) in the install-state dir(s)."""+ installs = w.sb.hermes_home / "installs"+ return sorted(str(p) for p in installs.glob("**/source-completion-pending")) if installs.is_dir() else []+++def _followups(rec: dict) -> list[dict]:+ items = rec.get("followups") or []+ return [f for f in items if isinstance(f, dict)]+++def _followup_steps(rec: dict) -> set[str]:+ return {str(f.get("step")) for f in _followups(rec)}+++def _update_log(w: G.World) -> Path:+ return w.sb.hermes_home / "logs" / "update.log"+++def _read(p: Path) -> str:+ return p.read_text(encoding="utf-8-sig", errors="replace") if p.is_file() else ""+++def _read_json(path: Path) -> dict:+ try:+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ return {}+ return data if isinstance(data, dict) else {}+++def _warn_lines(text: str) -> list[str]:+ return [line.strip() for line in text.splitlines() if WARN in line]+++def _obligation(w: G.World) -> str:+ """The host fleet-restart obligation record(s) anywhere in the sandbox (diagnostics only)."""+ found = []+ for base, dirs, files in os.walk(w.sb.root):+ dirs[:] = [d for d in dirs if d not in ("node_modules", ".git", "venv", ".venv", "hermes-agent")]+ if "host-update-restart.json" in files:+ path = Path(base) / "host-update-restart.json"+ found.append(f"{path}: {_read(path)[:600]}")+ return "; ".join(found) or "none"+++def _facts(w: G.World, cp=None, **extra) -> str:+ """A one-glance summary heading every failure message."""+ rec = w.receipt()+ parts = [f"rc={cp.returncode}" if cp is not None else "rc=-",+ f"head={w.head()[:12]}",+ f"receipt.outcome={rec.get('outcome')!r} update_id={str(rec.get('update_id'))[:12]} "+ f"pid={rec.get('pid')} followups={_followups(rec)}",+ f"pending={_pending_markers(w)}",+ f"config_version={_config_version(w)}",+ f"obligation={_obligation(w)}"]+ if cp is not None:+ parts.append(f"⚠ lines={_warn_lines(G.output(cp))[:8]}")+ parts += [f"{k}={v}" for k, v in extra.items()]+ return "\n".join(parts) + "\n"+++# -- hostile releases ----------------------------------------------------------------------------+++def _head_file(w: G.World, rel: str) -> str:+ return w.git("show", f"HEAD:{rel}") + "\n"+++def _hostile_web_mjs(w: G.World) -> str:+ """The checkout's ``scripts/build/web.mjs`` with the toggle block after its imports."""+ text = _head_file(w, "scripts/build/web.mjs")+ if _WEB_MARK in text:+ return text+ lines = text.splitlines(keepends=True)+ last_import = max(i for i, line in enumerate(lines) if line.startswith("import "))+ while " from " not in lines[last_import] and last_import + 1 < len(lines): # a multi-line import+ last_import += 1+ out = "".join(lines[:last_import + 1]) + _HOSTILE_WEB + "".join(lines[last_import + 1:])+ assert out.count(_WEB_MARK) == 1+ return out+++def _publish_web_release(w: G.World, tag: str) -> str:+ """A release whose web build obeys the toggles and whose web inputs changed (web UI stale)."""+ return w.publish(f"release: e2e hostile post web {tag}", {+ "scripts/build/web.mjs": _hostile_web_mjs(w),+ f"web/e2e-hostile-post-{tag}.txt": f"web input changed by release {tag}\n",+ })+++def _publish_gateway_fault_release(w: G.World, tag: str) -> str:+ """A release whose ``hermes gateway run`` refuses to boot while the toggle exists."""+ text = _head_file(w, "hermes_cli/gateway.py")+ if _GATEWAY_MARK not in text:+ m = re.search(r"^def run_gateway\(.*?\):\n \"\"\".*?\"\"\"\n", text, re.S | re.M)+ assert m, "premise: hermes_cli/gateway.py has no run_gateway() with a docstring to inject after"+ text = text[:m.end()] + _HOSTILE_GATEWAY + text[m.end():]+ return w.publish(f"release: e2e hostile post gateway {tag}", {+ "hermes_cli/gateway.py": text,+ f"docs/e2e-hostile-post-{tag}.txt": f"release {tag}\n",+ })+++# -- one shared PID namespace (gateway / killable update) ----------------------------------------+++def _namespace(w: G.World) -> Iterator[NamespaceHost]:+ """Every process of the cell in ONE sandbox, as on a user's machine: the updater's process scans+ see the gateway it restarts. Closing kills the namespace init, which takes everything with it."""+ host = NamespaceHost(w.sb.root, w.sb.env)+ try:+ yield host+ finally:+ leaked = host.close()+ assert not leaked, f"processes outlived the sandbox: {leaked}"+++def _ns_cli(host: NamespaceHost, w: G.World, *args: str, timeout: float = 600):+ cp = host.run([w.sb.hermes, *args], timeout=timeout)+ w.transcripts.append(f"$ hermes {' '.join(args)} -> rc={cp.returncode}\n{(cp.stdout or '')[-6000:]}\n"+ f"{(cp.stderr or '')[-3000:]}")+ return cp+++def _ns_update(host: NamespaceHost, w: G.World, *extra: str):+ return _ns_cli(host, w, "update", "--yes", "--branch", "main", *extra, timeout=UPDATE_TIMEOUT)+++def _identify(w: G.World) -> dict | None:+ from gateway.control_socket import identify_gateway++ with contextlib.suppress(Exception):+ return identify_gateway(w.sb.hermes_home, timeout=5.0)+ return None+++def _serving(w: G.World, sha: str) -> dict | None:+ ident = _identify(w)+ return ident if ident and ident.get("code_sha") == sha else None+++def _kill_born_after(host: NamespaceHost, before: set[int]) -> list[int]:+ """SIGSTOP then SIGKILL every process born after ``before`` was taken (by PID, namespace view):+ the update, its re-exec'd interpreter, build children and any detached completion child (own+ session, or reparented to the namespace init). Repeats until none is left."""+ killed: list[int] = []+ for _ in range(10):+ live = [p["pid"] for p in host.procs() if p["pid"] not in before and p["state"] not in ("Z", "X")]+ if not live:+ break+ for pid in live:+ host.kill(pid, signal.SIGSTOP)+ for pid in live:+ host.kill(pid, signal.SIGKILL) # windows-footgun: ok - linux-only (bwrap) module+ if pid not in killed:+ killed.append(pid)+ time.sleep(0.5)+ return killed+++def _gateway_logs(w: G.World) -> str:+ logs = w.sb.hermes_home / "logs"+ chunks = [_read(p)[-4000:] for p in sorted(logs.glob("*.log"))] if logs.is_dir() else []+ chunks += [_read(p)[-4000:] for p in sorted(w.sb.root.glob("gateway-*.log"))]+ return "\n".join(chunks)+++# -- cells ---------------------------------------------------------------------------------------+++def test_failed_web_build_after_commit_is_a_followup_not_a_failed_update(w):+ w.reset_clean()+ _clear_toggles(w)+ latest = _config_version(w)+ if latest is None:+ from hermes_cli.config_defaults import DEFAULT_CONFIG++ latest = int(DEFAULT_CONFIG["_config_version"])+ owed = latest - 1+ _edit_config(w, lambda cfg: cfg.update(_config_version=owed))+ target = _publish_web_release(w, "a")+ log0 = len(_read(_update_log(w)))++ _toggle(w, BREAK_WEB, True)+ try:+ cp = w.update("--no-gateway-restart")+ finally:+ _toggle(w, BREAK_WEB, False)+ out = G.output(cp)+ log = _read(_update_log(w))[log0:]+ rec = w.receipt()+ facts = _facts(w, cp, config_version_lowered_to=owed, latest_config_version=latest)+ diag = facts + w.diag(cp)++ assert w.head() == target, f"premise: the release never committed, so this is no post-commit cell:\n{diag}"+ assert WEB_FAULT_TEXT in out + log, f"premise: the hostile web build never ran (web UI not seen stale?):\n{diag}"+ assert cp.returncode == 0, f"the code committed, yet a failed web build failed `hermes update`:\n{diag}"+ assert _warn_lines(out), f"the failed web build was not surfaced with a ⚠ line:\n{diag}"+ assert rec.get("outcome") == "success", f"receipt outcome is not success after the commit:\n{diag}"+ assert "build" in _followup_steps(rec), f"receipt followups do not name the failed `build` step:\n{diag}"+ assert _pending_markers(w), f"the failed build disarmed the source-completion obligation:\n{diag}"+ assert (_config_version(w) or 0) >= latest, (+ f"the failed web build skipped the independent config migration (_config_version still "+ f"{_config_version(w)}, latest {latest}):\n{diag}")++ # The fault clears; the next plain update (no new release) pays the owed tail.+ cp = w.update()+ rec = w.receipt()+ diag = _facts(w, cp) + w.diag(cp)+ assert cp.returncode == 0 and w.head() == target, f"the healing update failed:\n{diag}"+ assert not _followups(rec), f"the healing update still reports followups:\n{diag}"+ assert not _pending_markers(w), f"the healing update left the completion obligation armed:\n{diag}"+ assert (w.checkout / "hermes_cli" / "web_dist" / "index.html").is_file(), \+ f"the healing update did not build the web UI:\n{diag}"+++def test_gateway_that_cannot_reboot_is_an_owed_restart_not_a_failed_update(w):+ """Fault: the RELEASE's gateway cannot boot (``run_gateway`` exits 1 while the toggle exists). The+ old gateway drains/stops normally; the relaunch runs the new code and dies at boot, so no gateway+ serves the new commit. A SIGSTOPped old gateway would not do: the survivor sweep SIGKILLs it and+ the relaunch then succeeds."""+ w.reset_clean()+ _clear_toggles(w)+ with _namespace(w) as host:+ try:+ gw = host.spawn([w.sb.hermes, "gateway", "run"], log=w.sb.root / "gateway-b.log") # sandbox-writable+ before_sha = w.head()+ try:+ ident = H.wait_for(lambda: _serving(w, before_sha), timeout=240, interval=1.0,+ what="the cron-only gateway's control-socket identify")+ except AssertionError as exc:+ raise AssertionError(f"premise: the gateway never came up: {exc}\n{_gateway_logs(w)[-4000:]}\n"+ f"{host.ps_text()}") from None+ target = _publish_gateway_fault_release(w, "b")+ _toggle(w, BREAK_GATEWAY, True)+ cp = _ns_update(host, w)+ out = G.output(cp)+ rec = w.receipt()+ obligation_after_update = _obligation(w)+ status = _ns_cli(host, w, "status", timeout=300)+ facts = _facts(w, cp, gateway_before=f"pid {ident.get('pid')} sha {before_sha[:12]} (spawned {gw})",+ identify_after=_identify(w), obligation_after_update=obligation_after_update)+ diag = (facts + w.diag(cp) + "\n--- gateway logs ---\n" + _gateway_logs(w)[-6000:]+ + "\n--- sandbox ---\n" + host.ps_text() + "\n--- hermes status ---\n" + G.output(status)[-3000:])++ assert w.head() == target, f"premise: the release never committed:\n{diag}"+ assert not _serving(w, target), f"premise: a gateway serves the new commit; the restart fault never fired:\n{diag}"+ assert cp.returncode == 0, f"the code committed, yet a failed gateway restart failed `hermes update`:\n{diag}"+ assert _warn_lines(out), f"the failed gateway restart was not surfaced with a ⚠ line:\n{diag}"+ assert rec.get("outcome") == "success", f"receipt outcome is not success after the commit:\n{diag}"+ assert "gateway_restart" in _followup_steps(rec), \+ f"receipt followups do not name the failed `gateway_restart` step:\n{diag}"+ assert OWED_RESTART in G.output(status), \+ f"a later command does not warn that a gateway restart is still owed:\n{diag}"++ # The fault clears; the next plain update retries the owed restart. This gateway is a+ # manual `gateway run` that died at boot: no supervisor and no live process, so the+ # retry has nothing it can relaunch. It must still exit 0 and must NOT silently discharge+ # the obligation (no gateway serves HEAD yet).+ _toggle(w, BREAK_GATEWAY, False)+ cp = _ns_update(host, w)+ status = _ns_cli(host, w, "status", timeout=300)+ diag = (_facts(w, cp, identify_after=_identify(w)) + w.diag(cp) + "\n--- gateway logs ---\n"+ + _gateway_logs(w)[-6000:] + "\n--- sandbox ---\n" + host.ps_text()+ + "\n--- hermes status ---\n" + G.output(status)[-3000:])+ assert cp.returncode == 0, f"the retrying update failed:\n{diag}"+ assert OWED_RESTART in G.output(status), \+ f"the retry discharged the owed restart while no gateway serves HEAD:\n{diag}"++ # The operator restarts it (the remedy the warning names); once a gateway serves HEAD the+ # obligation discharges and the warning goes away.+ host.spawn([w.sb.hermes, "gateway", "run"], log=w.sb.root / "gateway-b2.log")+ served = None+ with contextlib.suppress(AssertionError):+ served = H.wait_for(lambda: _serving(w, target), timeout=240, interval=1.0, what="a gateway on HEAD")+ status = _ns_cli(host, w, "status", timeout=300)+ diag = (_facts(w, cp, identify_after=_identify(w)) + "\n--- gateway logs ---\n"+ + _gateway_logs(w)[-6000:] + "\n--- sandbox ---\n" + host.ps_text()+ + "\n--- hermes status ---\n" + G.output(status)[-3000:])+ assert served, f"premise: the restarted gateway never served {target[:12]}:\n{diag}"+ assert OWED_RESTART not in G.output(status), \+ f"the owed-restart warning survived a gateway serving HEAD:\n{diag}"+ finally:+ _toggle(w, BREAK_GATEWAY, False)+ for p in host.procs():+ if p["pid"] > 2 and "gateway" in p["cmdline"]:+ host.kill(p["pid"], signal.SIGKILL) # windows-footgun: ok - linux-only (bwrap) module+ # The namespace (and its gateways) is gone; its PID file names a PID of a dead namespace.+ (w.sb.hermes_home / "gateway.pid").unlink(missing_ok=True)+++def test_sigkill_during_post_commit_tail_leaves_a_running_receipt(w):+ w.reset_clean()+ _clear_toggles(w)+ prev = w.receipt()+ target = _publish_web_release(w, "c")+ log0 = len(_read(_update_log(w)))+ started = w.sb.home / WEB_STARTED+ _toggle(w, SLOW_WEB, True)+ killed: list[int] = []+ try:+ with _namespace(w) as host:+ before = {p["pid"] for p in host.procs()}+ spawn_log = w.sb.root / "update-c.log" # sandbox-writable+ upd = host.spawn([w.sb.hermes, "update", "--yes", "--branch", "main", "--no-gateway-restart"],+ log=spawn_log)++ def _slow_build_running():+ if started.is_file():+ return True+ if not host.alive(upd):+ raise AssertionError(f"premise: the update exited before the slow web build started:\n"+ f"{_read(spawn_log)[-6000:]}\n{w.diag()}")+ return False++ H.wait_for(_slow_build_running, timeout=1200, interval=1.0, what="the slow web build to start")+ with contextlib.suppress(AssertionError):+ H.wait_for(lambda: re.search(r"web UI|slow web build", _read(_update_log(w))[log0:]),+ timeout=30, interval=0.5, what="update.log to show the web build")+ log_shows_build = bool(re.search(r"web UI|slow web build", _read(_update_log(w))[log0:]))+ killed = _kill_born_after(host, before)+ rec = w.receipt()+ facts = _facts(w, killed=killed, update_spawn_pid=upd, log_shows_web_build=log_shows_build,+ previous_update_id=prev.get("update_id"))+ diag = facts + w.diag() + "\n--- spawned update output ---\n" + _read(spawn_log)[-6000:]+ finally:+ _toggle(w, SLOW_WEB, False)+ started.unlink(missing_ok=True)++ assert killed, f"premise: nothing was killed:\n{diag}"+ assert w.head() == target, f"premise: the kill landed before the release committed:\n{diag}"+ assert rec.get("outcome") == "running" and rec.get("update_id") and \+ rec.get("update_id") != prev.get("update_id"), \+ f"latest.json is not a `running` record of the killed update:\n{json.dumps(rec, default=str)[:3000]}\n{diag}"+ assert rec.get("pid") in killed, f"the running receipt names pid {rec.get('pid')}, not a killed process:\n{diag}"+ killed_id = rec["update_id"]++ cp = w.update("--no-gateway-restart")+ rec = w.receipt()+ diag = _facts(w, cp, killed_update_id=killed_id) + w.diag(cp)+ assert "interrupted" in G.output(cp), f"the next update did not report the interrupted run:\n{diag}"+ assert cp.returncode == 0, f"the update after the interrupted one failed:\n{diag}"+ assert rec.get("outcome") == "success" and rec.get("update_id") != killed_id, \+ f"latest.json is not this run's terminal success:\n{diag}"+++def test_sticky_profile_update_logs_and_receipts_land_in_the_root_home(w):+ w.reset_clean()+ _clear_toggles(w)+ root = w.sb.hermes_home+ prof_receipts = root / "profiles" / PROFILE / "logs" / "update_receipts"+ if not (root / "profiles" / PROFILE).is_dir():+ cp = w.sb.cli("profile", "create", PROFILE, "--no-alias", timeout=300)+ assert cp.returncode == 0, f"premise: profile create failed:\n{H.describe(cp)}"+ cp = w.sb.cli("profile", "use", PROFILE, timeout=300)+ assert cp.returncode == 0, f"premise: profile use failed:\n{H.describe(cp)}"+ try:+ assert (root / "active_profile").read_text(encoding="utf-8-sig").strip() == PROFILE, \+ "premise: the sticky profile was not recorded"+ prof_before = {p.name for p in prof_receipts.iterdir()} if prof_receipts.is_dir() else set()+ log0 = _update_log(w).stat().st_size if _update_log(w).is_file() else 0+ prev = w.receipt()+ target = w.publish("release: e2e hostile post profile d", {"docs/e2e-hostile-post-d.txt": "d\n"})++ cp = w.update("--no-gateway-restart")++ prof_after = {p.name for p in prof_receipts.iterdir()} if prof_receipts.is_dir() else set()+ log1 = _update_log(w).stat().st_size if _update_log(w).is_file() else 0+ rec = w.receipt()+ diag = _facts(w, cp, profile_receipts_new=sorted(prof_after - prof_before), root_update_log_bytes=f"{log0}->{log1}",+ previous_update_id=prev.get("update_id")) + w.diag(cp)+ assert w.head() == target, f"premise: the release never committed:\n{diag}"+ assert cp.returncode == 0, f"the sticky-profile update failed:\n{diag}"+ # Only the UPDATE receipt is this lane's: pm's own sync receipts (pm_*sync*.json, its+ # latest.json with kind "sync") still follow the process home — pm/ is out of scope here.+ update_files = sorted(n for n in prof_after - prof_before if n.startswith("update_"))+ prof_latest = _read_json(prof_receipts / "latest.json")+ assert not update_files, f"the update wrote update receipts into the profile home {prof_receipts}:\n{diag}"+ # pm's sync receipt carries the update's correlation id, so "kind" tells them apart.+ assert prof_latest.get("kind", "sync") == "sync", \+ f"the profile home's latest.json is this update's receipt:\n{diag}"+ assert log1 > log0, f"the root update.log did not grow:\n{diag}"+ assert rec.get("update_id") != prev.get("update_id") and rec.get("outcome") == "success", \+ f"root latest.json is not this run's success:\n{diag}"+ finally:+ w.sb.cli("profile", "use", "default", timeout=300)diff --git a/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py b/tests/hermes_cli/test_fleet_matrix_self_restart_pending.pyindex 1a092911302..a8b9f92800d 100644--- a/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py+++ b/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py@@ -96,9 +96,12 @@ def test_restart_phase_records_accepted_self_restart_and_verify_exits_clean(monkassert "restart pending" in out.getvalue()assert "Update not complete" not in out.getvalue()assert cleared == [True]- with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:- restart.self_restart_pending_pids = set() # same fleet, identity not threaded → STALE, exit 1+ with contextlib.redirect_stdout(io.StringIO()) as out:+ restart.self_restart_pending_pids = set() # same fleet, identity not threaded → STALEfleet_mod._verify_fleet_after_update(restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,)- assert exc.value.code == 1+ # Contract C3: STALE is an owed restart (was SystemExit(1)): flagged, follow-up, marker kept.+ assert restart.incomplete+ assert "follow-up 'gateway_restart'" in out.getvalue()+ assert cleared == [True]diff --git a/tests/hermes_cli/test_manual_serve_deferral.py b/tests/hermes_cli/test_manual_serve_deferral.pyindex 05c14404544..5d01d360d72 100644--- a/tests/hermes_cli/test_manual_serve_deferral.py+++ b/tests/hermes_cli/test_manual_serve_deferral.py@@ -37,11 +37,15 @@ def test_manual_deferral_survives_receipt_rotation(monkeypatch, capsys, kind, corestart.failed_or_stale_units.append("hermes-serve-work.service")restart.incomplete = Trueif condition != "alive":- with pytest.raises(SystemExit) as exc:- fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)- assert exc.value.code == 1+ # Contract C3: a restart that is still owed no longer fails the committed update (was+ # SystemExit(1) + "partial") ...+ fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)+ # ... the obligation stays armed (unchanged) ...assert fleet._fleet_restart_obligation_armed()- assert update_receipt.read_latest_receipt()["outcome"] == "partial"+ receipt = update_receipt.read_latest_receipt()+ # ... and the receipt is a success naming the owed restart.+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt["followups"]] == ["gateway_restart"]returnfleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)receipt = update_receipt.read_latest_receipt()diff --git a/tests/hermes_cli/test_source_build.py b/tests/hermes_cli/test_source_build.pyindex 9c3c9e85d9c..dbdea3e1477 100644--- a/tests/hermes_cli/test_source_build.py+++ b/tests/hermes_cli/test_source_build.py@@ -299,21 +299,26 @@ def test_update_recompiles_only_products_whose_inputs_changed(source_products):@pytest.mark.platforms("linux")@pytest.mark.parametrize("step", ["tui", "web", "desktop"])def test_update_failure_raises_without_retries_or_replacing_live_app(source_products, step):- from hermes_cli.source_build import build_update_products+ from hermes_cli.source_build import ProductBuildError, build_update_productsroot, acquired = source_productsapp = root / "apps/desktop/release/linux-unpacked/hermes"app.parent.mkdir(parents=True)app.write_text("previous app")(root / f"fail-{step}").touch()- with pytest.raises(subprocess.CalledProcessError):+ with pytest.raises(ProductBuildError) as failure:build_update_products(root, desktop=True)- assert app.read_text() == "previous app"- assert not list((root / "apps/desktop").glob(".staging-*"))- order = ["deps", "tui", "web", "desktop"]- assert [event["step"] for event in _events(root)] == order[:order.index(step) + 1]+ # The failure is still raised, naming the one product that failed (no retries) ...+ assert len(failure.value.failures) == 1+ assert isinstance(failure.value.failures[0][1], subprocess.CalledProcessError)+ # ... but it no longer skips the independent products after it (was order[:index + 1]).+ assert [event["step"] for event in _events(root)] == ["deps", "tui", "web", "desktop"]assert acquired == ["npm"]- assert not (Path(os.environ["HERMES_HOME"]) / "desktop-build-stamp.json").exists()+ assert not list((root / "apps/desktop").glob(".staging-*"))+ if step == "desktop":+ # A failed desktop build never replaces the live app nor stamps it.+ assert app.read_text() == "previous app"+ assert not (Path(os.environ["HERMES_HOME"]) / "desktop-build-stamp.json").exists()@pytest.mark.platforms("linux")diff --git a/tests/hermes_cli/test_source_completion_stamp.py b/tests/hermes_cli/test_source_completion_stamp.pyindex c445aafcd37..6ca887dae08 100644--- a/tests/hermes_cli/test_source_completion_stamp.py+++ b/tests/hermes_cli/test_source_completion_stamp.py@@ -52,12 +52,30 @@ def test_successful_source_completion_writes_checkout_identity(tmp_path, monkeypdef test_failed_source_completion_does_not_publish_identity(tmp_path, monkeypatch):root = _repo(tmp_path)- _completion_dependencies(monkeypatch, lambda **_kwargs: False)+ _completion_dependencies(monkeypatch, lambda **_kwargs: True)- assert not complete_source_checkout(root, desktop=False, assume_yes=True)+ def broken_build(root, *, desktop):+ raise RuntimeError("web UI build: npm exited 1")++ monkeypatch.setattr("hermes_cli.source_build.build_update_products", broken_build)+ owed: list = []+ assert not complete_source_checkout(root, desktop=False, assume_yes=True, followups=owed)+ # The tail is owed, so the checkout identity is not published.+ assert [step for step, _ in owed] == ["build"]assert not (root / "install-stamp.json").exists()+def test_unsafe_sqlite_withholds_success_but_not_the_finished_tail(tmp_path, monkeypatch):+ # Was: an unsafe SQLite verdict also withheld the stamp, so the tail stayed owed forever+ # (re-running it cannot fix the interpreter, codemap §8 V1). The install still reports failure.+ root = _repo(tmp_path)+ _completion_dependencies(monkeypatch, lambda **_kwargs: False)+ owed: list = []+ assert not complete_source_checkout(root, desktop=False, assume_yes=True, followups=owed)+ assert owed == []+ assert (root / "install-stamp.json").is_file()++def _sandboxed_marker(tmp_path, monkeypatch):"""Point every update-lock reader at a marker inside this test's sandbox."""marker = tmp_path / ".hermes-update-in-progress"diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.pyindex 91158c51c39..8fef6c7e600 100644--- a/tests/hermes_cli/test_update_completion_process.py+++ b/tests/hermes_cli/test_update_completion_process.py@@ -155,6 +155,15 @@ def transition(tmp_path):"_current = contextvars.ContextVar('receipt', default=None)\n""class UpdateReceipt: pass\n""def record_stage(*args, **kwargs): pass\n"+ "def record_skip(*args, **kwargs): pass\n"+ "TAIL_FOLLOWUPS = frozenset({'launchers', 'build', 'maintenance', 'config_migration', 'completion'})\n"+ "def record_followup(step, reason, **kwargs):\n"+ " print(f' ⚠ Update follow-up {step!r} did not finish: {reason}')\n"+ " r = _current.get()\n"+ " if r is not None: r.data.setdefault('followups', []).append({'step': step, 'reason': reason})\n"+ "def amend_terminal_followup(*args): pass\n"+ "def _receipt_dir():\n"+ " return pathlib.Path(os.environ['HERMES_HOME']) / 'logs/update_receipts'\n""def finalize_pending_update_receipt(code, reason):\n"" r = _current.get()\n"" if r is None: return\n"@@ -370,7 +379,8 @@ def test_killed_selected_python_returns_signal_exit_status(transition):assert result["pm_receipt"]["update_id"] == request["receipt"]["update_id"]-def test_failed_build_preserves_exit_status_without_maintenance(transition):+def test_failed_build_after_commit_is_a_followup_and_later_steps_still_run(transition):+ """Contract C3: the code is committed, so a failed product build cannot fail the update."""from hermes_cli import update_completionroot, git, old, new, request = transition@@ -380,13 +390,24 @@ def test_failed_build_preserves_exit_status_without_maintenance(transition):"def build_update_products(*a, **kw): raise subprocess.CalledProcessError(23, ['builder'])\n")result = update_completion.run_completion(request)- assert result["exit_code"] == 23- assert result["receipt"]["outcome"] == "failed"+ # Was 23 / "failed": a post-commit build failure exits 0 with a success receipt.+ assert result["exit_code"] == 0+ assert result["receipt"]["outcome"] == "success"+ # The failure is not silent: it is a named receipt follow-up.+ assert [f["step"] for f in result["receipt"]["followups"]] == ["build"]+ # The tail obligation stays armed so the next launch / `hermes update` rebuilds.assert (Path(request["home"]) / "completion-pending").read_text() == "owed"events = [json.loads(line)["name"] for line in (root / "events.jsonl").read_text().splitlines()]- assert "maintenance" not in events- assert "restart" not in events- assert "emergency_resume" in events+ # Was "not in": the failed build no longer skips maintenance (config migration) ...+ assert "maintenance" in events+ # ... nor the gateway restart and its verification.+ assert "restart" in events and "verify" in events+ # The tail was not complete, so the install stamp is not written.+ assert "stamp" not in events+ # The gateway watcher hears success: the code it runs is the committed code.+ assert {"name": "exit_marker", "ok": True}.items() <= next(+ json.loads(line) for line in (root / "events.jsonl").read_text().splitlines()+ if json.loads(line)["name"] == "exit_marker").items()def test_prepare_failure_preserves_correlated_pm_receipt(transition, monkeypatch):diff --git a/tests/hermes_cli/test_update_external_profile_reconciliation.py b/tests/hermes_cli/test_update_external_profile_reconciliation.pyindex 4ce7666af1e..2c79bc921bd 100644--- a/tests/hermes_cli/test_update_external_profile_reconciliation.py+++ b/tests/hermes_cli/test_update_external_profile_reconciliation.py@@ -94,20 +94,22 @@ def test_symlinked_external_profile_gateway_does_not_fail_update(external_profildef test_external_profile_does_not_mask_a_missed_own_gateway(external_profile_host):- """The root's own gateway missed by the restart phase still fails the update."""+ """The root's own gateway missed by the restart phase is still an owed restart."""plan = UpdatePlan(runtimes=[_gateway("default", 1111), _gateway("work", 4242)])restart = _restart_outcome()restart.restarted_services.clear()update_receipt.begin_update_receipt()- with pytest.raises(SystemExit) as exc:- fleet._verify_fleet_after_update(- restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True,- )+ # Contract C3: no longer SystemExit(1); the miss is flagged and owed instead.+ fleet._verify_fleet_after_update(+ restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True,+ )- assert exc.value.code == 1- outcomes = {o["profile"]: o["outcome"] for o in update_receipt.read_latest_receipt()["runtime_outcomes"]}+ assert restart.incomplete+ receipt = update_receipt.read_latest_receipt()+ outcomes = {o["profile"]: o["outcome"] for o in receipt["runtime_outcomes"]}assert outcomes == {"default": "unaccounted", "work": "external"}+ assert [f["step"] for f in receipt["followups"]] == ["gateway_restart"]def test_external_requires_verified_pid_evidence():diff --git a/tests/hermes_cli/test_update_fleet_check_fail_closed.py b/tests/hermes_cli/test_update_fleet_check_fail_closed.pyindex 42dd9aae965..f78a39ebf6e 100644--- a/tests/hermes_cli/test_update_fleet_check_fail_closed.py+++ b/tests/hermes_cli/test_update_fleet_check_fail_closed.py@@ -72,19 +72,23 @@ class TestCallSiteWiring:fleet._verify_fleet_after_update(restart, _pre_update_plan=plan,_windows_gateway_resume=None, update_complete=True)+ cleared = []+ monkeypatch.setattr(fleet, "_clear_fleet_restart_pending_marker", lambda: cleared.append(True))+ # Contract C3: the code is committed, so verification never fails the update (was SystemExit(1)).+ verify()if had_gateway:- with pytest.raises(SystemExit) as failure:- verify()- assert failure.value.code == 1assert events[0] == "settle"assert events.count("probe") > 1assert "returned no rows" in capsys.readouterr().outelse:- verify()assert events == ["probe"]+ # Fail-closed survives as an OWED restart: the fleet obligation is kept armed ...assert restart.incomplete is had_gateway+ assert cleared == ([] if had_gateway else [True])receipt = json.loads((update_cmd.get_hermes_home() / "logs/update_receipts/latest.json").read_text())- assert receipt["outcome"] == ("partial" if had_gateway else "success")+ # ... and the receipt is a success that names the owed step (was outcome "partial").+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt.get("followups", [])] == (["gateway_restart"] if had_gateway else [])@@ -105,3 +109,32 @@ def test_unmapped_stops_are_not_expected_rows():out.stopped_unmapped_pids.discard(102)pre, killed = out.fleet_probe_signals()assert _fleet_probe_expected_runtimes(_plan([]), pre, None, out.restarted_services, killed)+++def test_unmapped_stop_keeps_the_restart_owed(monkeypatch, tmp_path):+ # Codemap §6 V7/V12: an unmapped gateway stopped with no successor used to be "accounted for"+ # (update exit 0, obligation cleared) and stayed down silently. It still predicts no row (the+ # test above), but the restart is now OWED: a receipt follow-up and an armed fleet obligation.+ import json+ from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_receipt++ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)+ monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)+ monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda **kw: None)+ monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])+ monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **kw: [])+ cleared = []+ monkeypatch.setattr(fleet, "_clear_fleet_restart_pending_marker", lambda: cleared.append(True))+ out = fleet._GatewayRestartOutcome(+ incomplete=False, phase_errors=[], pre_restart_gateway_pids=[101], restarted_services=[],+ failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[],+ killed_pids={101}, stopped_unmapped_pids={101},+ )+ update_receipt.begin_update_receipt()+ fleet._verify_fleet_after_update(out, _pre_update_plan=_plan([]), _windows_gateway_resume=None,+ update_complete=True)+ receipt = json.loads((update_cmd.get_hermes_home() / "logs/update_receipts/latest.json").read_text())+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt["followups"]] == ["gateway_restart"]+ assert "101" in receipt["followups"][0]["reason"]+ assert cleared == []diff --git a/tests/hermes_cli/test_update_fleet_completion.py b/tests/hermes_cli/test_update_fleet_completion.pyindex 984bfb0b1ff..2a458ff58de 100644--- a/tests/hermes_cli/test_update_fleet_completion.py+++ b/tests/hermes_cli/test_update_fleet_completion.py@@ -1,6 +1,5 @@"""SQLite completion and fleet verification remain independent update outcomes."""-from contextlib import nullcontextimport jsonimport pytest@@ -45,17 +44,18 @@ def test_fleet_completion_preserves_runtime_verdict_and_restart_obligation(healthy = update_complete and state == "current"with update_receipt.update_receipt_scope():update_receipt.begin_update_receipt()- with nullcontext() if healthy else pytest.raises(SystemExit) as exc:- update_cmd_fleet._verify_fleet_after_update(- restart, _pre_update_plan=None, _windows_gateway_resume=None,- update_complete=update_complete,- )- if not healthy:- assert exc.value.code == 1+ # Contract C3: neither verdict fails the committed update any more (was SystemExit(1)).+ update_cmd_fleet._verify_fleet_after_update(+ restart, _pre_update_plan=None, _windows_gateway_resume=None,+ update_complete=update_complete,+ )receipt = json.loads((get_hermes_home() / "logs/update_receipts/latest.json").read_text())- assert receipt["outcome"] == ("success" if healthy else "partial")+ # Was "partial" when not healthy: the run is a success; an owed fleet restart is a follow-up.+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt.get("followups", [])] == ([] if state == "current" else ["gateway_restart"])assert receipt["fleet"] == snapshot+ # The two verdicts stay independent: only the fleet keeps the restart obligation armed.assert restart.incomplete is (state != "current")assert update_cmd_fleet._fleet_restart_obligation_armed() is (state != "current")assert migrated == ([True] if healthy else [])diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.pyindex 357dbd8c79a..d284761ecbd 100644--- a/tests/hermes_cli/test_update_fleet_restart_pending.py+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py@@ -412,8 +412,9 @@ def test_clean_update_escalates_surviving_serve_as_unaccounted(``hermes-gateway.service``) and an unmanaged ``serve`` on the samedefault profile. The serve survives the update as the SAME process, sothe update must (1) warn, (2) reconcile it as ``unaccounted`` instead of- borrowing the gateway's restart, and (3) exit 1 with a ``partial``- receipt — not print a clean success."""+ borrowing the gateway's restart, and (3) under contract C3 (the code is+ committed) end ``success`` with an owed ``gateway_restart`` follow-up and+ the restart obligation still armed — never a silent clean success."""from hermes_cli.update_inventory import (RuntimeRecord, UpdatePlan, _restart_mechanism,)@@ -460,18 +461,24 @@ def test_clean_update_escalates_surviving_serve_as_unaccounted(lambda **_k: [{"pid": 5555, "purpose": "serve", "create_time": 1000.0}],)- with pytest.raises(SystemExit) as excinfo:- hermes_main.cmd_update(args)- assert excinfo.value.code == 1+ # Was SystemExit(1): the committed update no longer fails (contract C3).+ hermes_main.cmd_update(args)out = capsys.readouterr().out+ # (1) still warned, unchanged.assert "pid 5555" in out and "pre-update code" in outassert "Planned runtimes the restart phase never touched" in outassert "serve [default] pid 5555" in out+ assert "follow-up 'gateway_restart'" in outlatest = get_hermes_home() / "logs" / "update_receipts" / "latest.json"receipt = json.loads(latest.read_text(encoding="utf-8"))- assert receipt["outcome"] == "partial"+ # (3) was "partial": a success that names the owed restart.+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt["followups"]] == ["gateway_restart"]+ from hermes_cli import update_cmd_fleet+ assert update_cmd_fleet._fleet_restart_obligation_armed()+ # (2) the reconciliation verdict is unchanged.by_pid = {o["pid"]: o["outcome"] for o in receipt["runtime_outcomes"]}assert by_pid == {4444: "restarted", 5555: "unaccounted"}diff --git a/tests/hermes_cli/test_update_hangup_protection.py b/tests/hermes_cli/test_update_hangup_protection.pyindex a4b6c5a5413..b924353f09c 100644--- a/tests/hermes_cli/test_update_hangup_protection.py+++ b/tests/hermes_cli/test_update_hangup_protection.py@@ -118,7 +118,7 @@ class TestInstallHangupProtection:def test_non_fatal_if_log_setup_fails(self, monkeypatch):- """If get_hermes_home() raises, stdio must be left untouched but SIGHUP still handled."""+ """If the root-home lookup raises, stdio must be left untouched but SIGHUP still handled."""prev_out, prev_err = sys.stdout, sys.stderrdef _boom():@@ -126,7 +126,7 @@ class TestInstallHangupProtection:# Patch the import inside _install_hangup_protection.monkeypatch.setattr(- "hermes_cli.config.get_hermes_home", _boom, raising=True+ "hermes_constants.get_default_hermes_root", _boom, raising=True)original_handler = (diff --git a/tests/hermes_cli/test_update_post_commit_followups.py b/tests/hermes_cli/test_update_post_commit_followups.pynew file mode 100644index 00000000000..f7fe1f61561--- /dev/null+++ b/tests/hermes_cli/test_update_post_commit_followups.py@@ -0,0 +1,178 @@+"""Contract C3: after the commit point nothing fails `hermes update`.++Post-commit step failures are ⚠ + a receipt follow-up + an armed obligation; the receipt+is durable while the run is open; receipts resolve to the root home.+"""++from __future__ import annotations++import json+import os+import subprocess++import pytest++from hermes_cli import update_receipt+++def _latest(home):+ return json.loads((home / "logs/update_receipts/latest.json").read_text())+++def test_open_receipt_is_durably_running_and_finalizes_in_place(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ update_receipt.begin_update_receipt()+ running = _latest(tmp_path)+ assert running["outcome"] == "running" and running["pid"] == os.getpid()+ run_files = list((tmp_path / "logs/update_receipts").glob(f"update_*_{running['update_id']}.json"))+ assert len(run_files) == 1+ update_receipt.record_stage("apply", "success")+ assert [s["name"] for s in _latest(tmp_path)["stages"]] == ["apply"]+ update_receipt.record_followup("build", "web UI build: npm exited 1")+ update_receipt.finalize_update_receipt("success")+ final = _latest(tmp_path)+ assert final["outcome"] == "success"+ assert [(f["step"], f["reason"]) for f in final["followups"]] == [("build", "web UI build: npm exited 1")]+ # The terminal record replaced the running one in the SAME archive file (no duplicate per run).+ assert list((tmp_path / "logs/update_receipts").glob(f"update_*_{final['update_id']}.json")) == run_files+++def test_dead_running_record_is_reported_interrupted_by_the_next_run(tmp_path, monkeypatch, capsys):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ dead = subprocess.Popen(["true"])+ dead.wait()+ update_receipt.begin_update_receipt()+ update_receipt.record_stage("deps", "success")+ killed = update_receipt._current.get().data+ killed_id = killed["update_id"]+ # Simulate the kill: the record on disk names a process that is gone.+ for path in (tmp_path / "logs/update_receipts").glob("*.json"):+ data = json.loads(path.read_text())+ data.update(pid=dead.pid, writer_pid=dead.pid, pid_create_time=None)+ path.write_text(json.dumps(data))+ update_receipt._current.set(None)++ update_receipt.begin_update_receipt()+ out = capsys.readouterr().out+ assert "interrupted" in out and "last stage: deps" in out+ (archived,) = (tmp_path / "logs/update_receipts").glob(f"update_*_{killed_id}.json")+ assert json.loads(archived.read_text())["outcome"] == "interrupted"+ assert _latest(tmp_path)["update_id"] != killed_id+ update_receipt.finalize_update_receipt("success")+++def test_live_running_record_is_not_reclaimed(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ update_receipt.begin_update_receipt()+ own_id = update_receipt._current.get().data["update_id"]+ for path in (tmp_path / "logs/update_receipts").glob("*.json"):+ data = json.loads(path.read_text())+ data.update(pid=os.getppid(), writer_pid=os.getppid(), pid_create_time=None) # alive+ path.write_text(json.dumps(data))+ assert update_receipt.reconcile_interrupted_runs() == []+ (archived,) = (tmp_path / "logs/update_receipts").glob(f"update_*_{own_id}.json")+ assert json.loads(archived.read_text())["outcome"] == "running"+ update_receipt.finalize_update_receipt("success")+++def test_profile_process_writes_receipts_to_the_root_home(tmp_path, monkeypatch):+ root = tmp_path / ".hermes"+ profile = root / "profiles/work"+ profile.mkdir(parents=True)+ monkeypatch.setattr("hermes_constants._get_platform_default_hermes_home", lambda: root)+ monkeypatch.setattr("hermes_constants._default_hermes_root_memo", None)+ monkeypatch.setenv("HERMES_HOME", str(profile))+ assert update_receipt._receipt_dir() == root / "logs/update_receipts"+++def test_failed_web_build_does_not_skip_the_tui(tmp_path, monkeypatch, capsys):+ from hermes_cli import source_build++ built = []+ monkeypatch.setattr("hermes_cli.main_install_repair._install_configured_features_missing_deps", lambda root: None)+ monkeypatch.setattr("hermes_cli.update_stage.publish_stage", lambda text: None)+ monkeypatch.setattr("hermes_cli.memory_provider_migration.migrate_all_homes", lambda: None)+ monkeypatch.setattr(source_build, "source_frontends", lambda root: ("web", "ui-tui"))+ monkeypatch.setattr(source_build, "source_build_env", lambda **kw: {"PATH": ""})+ monkeypatch.setattr(source_build, "prepare_source_dependencies", lambda *a, **kw: None)+ monkeypatch.setattr(source_build, "source_product_current", lambda *a: False)+ monkeypatch.setattr(source_build, "build_source_tui", lambda root, env: built.append("tui"))++ def broken_web(root, env):+ raise subprocess.CalledProcessError(1, ["npm", "run", "build"])++ monkeypatch.setattr(source_build, "build_source_web", broken_web)+ with pytest.raises(source_build.ProductBuildError) as failure:+ source_build.build_update_products(tmp_path, desktop=False)+ assert built == ["tui"]+ assert [name for name, _ in failure.value.failures] == ["web UI build"]+ assert "npm run build exited 1" in str(failure.value)+++def test_failed_config_migration_is_owed_and_later_maintenance_runs(tmp_path, monkeypatch, capsys):+ from hermes_cli import update_cmd, update_cmd_maint as maint++ calls = []+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ for name in ("_verify_and_restore_state_dbs_post_update", "_invalidate_live_plugin_catalog_caches",+ "_print_bundled_skills_sync_report", "_sync_profiles_after_update"):+ monkeypatch.setattr(maint, name, lambda name=name: calls.append(name))+ monkeypatch.setattr("hermes_cli.gitlock.fetch_full_commit_graph", lambda *a, **kw: False)+ monkeypatch.setattr("hermes_cli.model_catalog.seed_cache_from_checkout", lambda root: False)++ def broken_migration(**kwargs):+ raise SystemExit(1) # a migration helper that exits must not fail the committed update++ monkeypatch.setattr(update_cmd, "_check_and_apply_config_migration", broken_migration)+ monkeypatch.setattr(maint, "_print_verified_update_completion", lambda message: calls.append("verdict") or True)+ monkeypatch.setattr(maint, "_print_post_update_notices_and_self_heals", lambda: calls.append("notices"))+ update_receipt.begin_update_receipt()+ owed: list = []+ assert maint._run_post_update_maintenance(+ assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None,+ had_desktop_app_before_update=False, pre_update_version=None, followups=owed) is True+ assert [step for step, _ in owed] == ["config_migration"]+ assert calls[-2:] == ["verdict", "notices"]+ assert "⚠ Update follow-up 'config_migration'" in capsys.readouterr().out+ update_receipt.finalize_update_receipt("success")+ assert [f["step"] for f in _latest(tmp_path)["followups"]] == ["config_migration"]+++def test_owed_restart_names_its_gateways_so_a_dead_fleet_cannot_discharge_it(tmp_path, monkeypatch):+ # A gateway that died at boot leaves no live row. An inventory-less obligation would be settled+ # by the gateway-less discharge, silencing the warning that replaces exit 1 under C3.+ from hermes_cli import update_cmd_fleet as fleet+ from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ fleet._write_fleet_restart_pending_marker(expected_sha="a" * 40)+ plan = UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile="default", pid=4242),+ RuntimeRecord(kind="dashboard", profile="default", pid=4343)])+ fleet._record_owed_gateway_inventory(plan)++ inventory = json.loads(fleet._obligation_fields()["inventory"])+ assert [(r["kind"], r["profile"]) for r in inventory["runtimes"]] == [("gateway", "default")]+ # HEAD still holds the pulled code, so only the fleet evidence can settle it.+ monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: "a" * 40)+ monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda: [])+ assert fleet._marker_only_restart_obsolete() is False+ assert fleet._fleet_restart_obligation_armed()+++def test_owed_restart_rearms_a_settled_obligation_and_a_later_run_keeps_owing_it(tmp_path, monkeypatch):+ # A pre-restart probe can settle an inventory-less record; the owed restart must re-arm it, and+ # a later verify that finds nothing to restart must keep owing the named gateway.+ from hermes_cli import update_cmd_fleet as fleet+ from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: "b" * 40)+ monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda: [])+ assert not fleet._fleet_restart_obligation_armed()+ fleet._record_owed_gateway_inventory(UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile="default")]))+ assert fleet._obligation_fields()["expected_sha"] == "b" * 40+ # A later verify with nothing live to restart still owes the named gateway (and keeps it armed).+ assert fleet._named_gateways_still_owed()+ assert fleet._fleet_restart_obligation_armed()diff --git a/tests/hermes_cli/test_update_stale_gateway_yield.py b/tests/hermes_cli/test_update_stale_gateway_yield.pyindex 9a2fcba478c..11b9937fffe 100644--- a/tests/hermes_cli/test_update_stale_gateway_yield.py+++ b/tests/hermes_cli/test_update_stale_gateway_yield.py@@ -103,7 +103,7 @@ def test_update_signals_proven_stale_gateway_survivor(cron_home, tmp_path):def test_verify_fleet_hands_stale_rows_to_survivor_signalling(monkeypatch):- """The wiring: a stale fleet matrix reaches signal_stale_fleet_survivors before exit 1."""+ """The wiring: a stale fleet matrix reaches signal_stale_fleet_survivors; the restart stays owed."""import hermes_cli.update_cmd_fleet as fleet_modimport hermes_cli.update_cmd_stale_survivors as survimport hermes_cli.update_cmd as update_cmd@@ -121,9 +121,10 @@ def test_verify_fleet_hands_stale_rows_to_survivor_signalling(monkeypatch):incomplete=False, phase_errors=[], pre_restart_gateway_pids=[4242], restarted_services=[],failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),)- with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:+ with contextlib.redirect_stdout(io.StringIO()):fleet_mod._verify_fleet_after_update(restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,)- assert exc.value.code == 1+ # Contract C3: was SystemExit(1); now flagged incomplete (owed restart, marker kept).+ assert restart.incompleteassert seen["fleet"] == stale_fleetdiff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.pyindex a60d76b5960..2eda523fa2e 100644--- a/tests/hermes_cli/test_update_zip_completion.py+++ b/tests/hermes_cli/test_update_zip_completion.py@@ -168,26 +168,24 @@ def test_zip_helper_propagates_completion_status_after_real_verification(zip_upd{"pid": plan.runtimes[0].pid, "profile": "default"}])request = update_cmd._source_completion_request(update_cmd._resolve_update_options(args, True), plan, snapshot, state.token, False, True)- if verdict == "healthy":- assert update_cmd_zip._update_via_zip(args, completion_request=request) is True- else:- with pytest.raises(SystemExit) as error:- update_cmd_zip._update_via_zip(args, completion_request=request)- assert error.value.code == 1- assert state.events == ["prepare", ("marker", verdict != "unsafe-sqlite"),- "restart", "resume", "finalize"]+ # Contract C3: the swapped code is committed, so neither verdict fails the update (was SystemExit(1)).+ assert update_cmd_zip._update_via_zip(args, completion_request=request) is True+ # The gateway watcher hears success for every verdict (was False for unsafe SQLite).+ assert state.events == ["prepare", ("marker", True), "restart", "resume", "finalize"]receipt = json.loads((state.active / "logs/update_receipts/latest.json").read_text())- assert receipt["outcome"] == ("success" if verdict == "healthy" else "partial")+ # Was "partial": a success that names what is still owed.+ assert receipt["outcome"] == "success"+ assert [f["step"] for f in receipt.get("followups", [])] == {+ "healthy": [], "unsafe-sqlite": ["sqlite_runtime"], "stale-fleet": ["gateway_restart"]}[verdict]assert receipt["runtime_outcomes"][0]["outcome"] == ("unaccounted" if verdict == "stale-fleet" else "restarted")assert json.loads(state.jobs.read_text()) == state.original_jobs@pytest.mark.parametrize("route", ["direct", "git-failure"])[email protected]("failure", ["swap", "late-swap", "stage", "preparation"])[email protected]("failure", ["swap", "late-swap", "stage"])def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monkeypatch, route, failure):import os- import pmstate = zip_updatebefore = {profile: (profile / "config.yaml").read_bytes()@@ -225,12 +223,6 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monreturn copytree(src, dst, *args, **kwargs)monkeypatch.setattr(shutil, "copytree", fail_copy)expected = SystemExit- else:- def fail_preparation(*args, **kwargs):- assert (state.root / "payload.txt").read_text() == "new"- raise pm.InstallError("venv", "preparation stopped")- monkeypatch.setattr("hermes_cli.source_build.build_update_products", fail_preparation)- expected = pm.InstallErrorwith pytest.raises(expected) as raised:update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=True)if failure in {"swap", "late-swap"}:@@ -246,10 +238,41 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monassert {profile: (profile / "config.yaml").read_bytes() for profile in before} == beforeassert not (state.sibling / ".env").exists()assert json.loads(state.jobs.read_text()) == state.original_jobs- assert not (state.active / "logs/update_receipts/latest.json").exists()+ # The receipt is durable from the start (was: no latest.json at all). This direct+ # ``_cmd_update_impl`` call has no command-boundary finalizer, so it is still the open+ # record of THIS run, never a success.+ latest = state.active / "logs/update_receipts/latest.json"+ assert not latest.exists() or json.loads(latest.read_text())["outcome"] != "success"assert not list(state.root.glob("*.hermes-update-*"))[email protected]("route", ["direct", "git-failure"])+def test_zip_build_failure_after_swap_is_a_followup(zip_update, monkeypatch, route):+ # Was the "preparation" case above (pm.InstallError propagated): the build runs after the+ # swap committed the new tree, so under contract C3 it is an owed follow-up, not a failure.+ import pm++ state = zip_update+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))+ monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)+ monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True)++ def fail_fetch(*args, **kwargs):+ raise subprocess.CalledProcessError(1, ["git", "fetch"])+ monkeypatch.setattr(update_cmd, "_git_run", fail_fetch)++ def fail_build(*args, **kwargs):+ assert (state.root / "payload.txt").read_text() == "new"+ raise pm.InstallError("venv", "preparation stopped")+ monkeypatch.setattr("hermes_cli.source_build.build_update_products", fail_build)+ update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=True)+ assert (state.root / "payload.txt").read_text() == "new"+ receipt = json.loads((state.active / "logs/update_receipts/latest.json").read_text())+ assert receipt["outcome"] == "success"+ assert "build" in [f["step"] for f in receipt["followups"]]+ assert state.token["resume_needed"] is False++@pytest.mark.parametrize("entry", ["payload.txt", "tools"])def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, monkeypatch, entry):import shutildiff --git a/website/docs/developer-guide/source-update-completion.md b/website/docs/developer-guide/source-update-completion.mdindex 87221130b79..8f43012b139 100644--- a/website/docs/developer-guide/source-update-completion.md+++ b/website/docs/developer-guide/source-update-completion.md@@ -35,13 +35,38 @@ fleet restart, Windows resume, dashboard deduplication and verification.The existing per-kind restart and abort-recovery algorithms remain; transientsupervisor/process failures are real even without mixed-generation imports. Onlythe purge/reload workaround and independent retry/ZIP tail compositions disappear.-Gateway exit status is written before a restart can terminate the updater's cgroup,-and is demoted on later failure. Verification publishes the final receipt.+Gateway exit status is written before a restart can terminate the updater's cgroup.+Verification publishes the final receipt.++## After the commit point nothing fails the update++Once the tree has moved, `hermes update` exits 0 unless the code itself was rolled back.+Every completion step is independent: a failed launcher publish, product build (each of+TUI/web/desktop is attempted even when another failed), profile sync, config migration,+bytecode sweep, gateway restart/verification, Windows resume or retired-channel adoption+prints a `⚠` line and is appended to the receipt's `followups` as `{step, reason}` while the+receipt's `outcome` stays `"success"`. The step's own obligation stays armed:+`source-completion-pending` for the tail (launchers, build, maintenance, config migration),+the host fleet-restart obligation for gateways (the CLI startup warning keeps naming it; an+owed restart records the pre-update gateways on the obligation, so a gateway that died at boot+stays owed until it serves the checkout instead of being settled by the gateway-less discharge),+the unstamped bytecode fingerprint for the sweep. The next launch or `hermes update` —+including the "Already up to date" path, which runs the same completion — retries it. A host+stamped "restarted" for this commit whose fleet is still off the checkout restarts again+instead of dead-ending. Exit 2 (refused / concurrent) and exit 1 (nothing committed, or+rolled back) keep their meaning.++The receipt is durable while the run is open: `begin_update_receipt` writes it as+`outcome: "running"` to the run's own archive file and `latest.json`, and each stage+boundary refreshes it, so a killed update leaves its own record. The next update marks a+`running` record whose processes are gone `interrupted` (naming its last stage) and reports+it. Receipts and the `update.log` tee resolve to the root home+(`hermes_constants.get_default_hermes_root()`), never a sticky profile's.## Parent lifecycle and failuresThe parent waits and propagates the child's exact nonzero result (a signal is-mapped to shell-style 128+signal). A child cannot succeed by merely exiting zero:+mapped to shell-style 128+signal); post-commit step failures never produce one. A child cannot succeed by merely exiting zero:a terminal response with the matching receipt identity is required. The responsereturns the mutated Windows token so the parent's registered emergency resume doesnot repeat completed work. Normal parent completion performs no maintenance.diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex e7b9c2962e0..8923f884e93 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -97,7 +97,7 @@ For an admitted source checkout, `hermes update` runs these phases:3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes rolls the install back so your shell stays bootable: it resets the checkout to the commit it ran before the pull (`git reset --hard <pre-pull-sha>`), or, when the update switched away from a detached checkout or a parked feature branch, returns there with `git checkout --detach <sha>` / `git checkout <branch>` (a branch it cannot check out again is restored detached at the same commit). Re-run `hermes update` once the upstream fix lands.4. **Dependency preparation** — PM provisions required tools and prepares a complete Python environment from the new lock, existing extras, and enabled plugin requirements. It validates that environment before publishing its selection. A plugin never fails the update. A plugin that no longer fits the new core is added to `plugins.disabled` in every profile that enables it (a memory provider has `memory.provider` cleared). That covers a `requires-python` that excludes Hermes's Python, a `manifest_version` newer than this Hermes supports, and dependencies that the resolver proves can't resolve alongside core and earlier plugins in config order, or that fail their own build. A download or network failure gets one retry and is disabled if it fails again. The update prints `⚠ Disabled plugin '<name>' in <home>: <reason>`, records it in the receipt's warnings, and continues. Re-enable it with `hermes plugins enable <name>` once the plugin ships a compatible release, or once the network is back. A `requires_hermes` range the running version misses never disables a plugin, because a source checkout without release tags can read as an older release. That plugin sits out instead (`⚠ Left plugin '<name>' … out of this update`), stays enabled, and rejoins once Hermes reports a version it accepts. A secondary profile whose config cannot be read sits out the same way until the config is fixed. Only a core that cannot build on its own fails this step.5. **Config migration** — detects new config options added since your version and prompts you to set them-6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build (on Windows a real-time scanner briefly holding `release/win-unpacked` is ridden out with a few short retries). A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update fails at that step, and `hermes desktop --build-only --force-build` or the next `hermes update` retries the rebuild. On macOS the rebuilt bundle is then copied (with `ditto`, signature intact) over a stale `/Applications/Hermes.app` or `~/Applications/Hermes.app`, so the copy Finder and the Dock launch matches the backend; an installed copy that is currently running is left alone and the update tells you to quit it and run `hermes update` again. If a copy an earlier update installed has since been removed (including dragged to the Trash), the update rebuilds it if needed, puts it back and says so, so Finder, the Dock and Spotlight find Hermes again; `hermes uninstall` removes the app for good. On Windows, when the update finishes from inside the Desktop app it would rebuild (the app completing an interrupted update at launch), the rebuild is skipped with a notice instead: Windows locks a running app's files, and stopping the app would end the update with it. The rest of the update completes; quit Hermes Desktop and run `hermes desktop` from a terminal, or use **Update now** in **Settings → About**, to rebuild and reopen it.+6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build (on Windows a real-time scanner briefly holding `release/win-unpacked` is ridden out with a few short retries). A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update prints a `⚠` line, still finishes the remaining steps (config migration, gateway restart) and exits 0 with a `build` follow-up in its receipt, and the next launch, `hermes update` or `hermes desktop --build-only --force-build` retries the rebuild. On macOS the rebuilt bundle is then copied (with `ditto`, signature intact) over a stale `/Applications/Hermes.app` or `~/Applications/Hermes.app`, so the copy Finder and the Dock launch matches the backend; an installed copy that is currently running is left alone and the update tells you to quit it and run `hermes update` again. If a copy an earlier update installed has since been removed (including dragged to the Trash), the update rebuilds it if needed, puts it back and says so, so Finder, the Dock and Spotlight find Hermes again; `hermes uninstall` removes the app for good. On Windows, when the update finishes from inside the Desktop app it would rebuild (the app completing an interrupted update at launch), the rebuild is skipped with a notice instead: Windows locks a running app's files, and stopping the app would end the update with it. The rest of the update completes; quit Hermes Desktop and run `hermes desktop` from a terminal, or use **Update now** in **Settings → About**, to rebuild and reopen it.7. **Gateway auto-restart**: running gateways are refreshed after the update completes. Service-managed gateways (systemd on Linux, launchd on macOS) restart through the service manager. Manual gateways are relaunched when Hermes can map their PID to a profile. Manually launched `hermes serve` / `hermes dashboard` backends are different: the updater leaves them running and asks their owner to restart them. See [Manual backend restart reminders](#manual-backend-restart-reminders). Backends owned by a running Desktop app remain the app's responsibility.8. **Multiplex migration (multi-profile installs)** — once the fleet is verified on the new code, an install with two or more profiles that still run **one gateway per profile** is folded into a single multiplexed default gateway when nothing blocks it (same as `hermes gateway migrate --multiplex --yes`); if a blocker exists (a bot token shared by two profiles, a secondary profile binding a port with no `/p/<profile>/` ingress) the update prints the blockers with their fixes and changes nothing. Single-profile installs are never touched. See [Migrating from per-profile gateways](../user-guide/multi-profile-gateways.md#migrating-from-per-profile-gateways).@@ -314,7 +314,7 @@ fleet caused only by the deferral does not make the update `partial`.### Interrupted gateway restarts-If an earlier update pulled code but did not finish restarting the fleet, the next `hermes update` retries even when the checkout is already current. An empty process scan does not prove recovery: failed systemd units and installed launchd jobs may have no live PID. If discovery or restart fails, or a requested service cannot be verified active, the marker stays pending and the update exits nonzero. Recover the affected services with the printed commands and retry.+If an earlier update pulled code but did not finish restarting the fleet, the next `hermes update` retries even when the checkout is already current. An empty process scan does not prove recovery: failed systemd units and installed launchd jobs may have no live PID. If discovery or restart fails, or a requested service cannot be verified active, the marker stays pending: the update still exits 0 (the new code is in place), prints a `⚠` line and a `gateway_restart` follow-up in its receipt, every CLI start warns about the owed restart, and the next `hermes update` retries it. Recover the affected services with the printed commands, or rerun `hermes update`.A failed historical receipt alone does not prove that gateways are still stale. Startup and gateway-status warnings, as well as update catch-up, check for a live successor on the current checkout for every gateway profile recorded in that receipt. A manual gateway restart can settle receipt-only advice without rewriting the historical outcome. Manual backend obligations must first transfer to their separate reminders.diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex e9c28573fbc..4cb19a23740 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -2017,8 +2017,8 @@ external update owner. See [Updating & Uninstalling](../getting-started/updatingAdditional behavior:- **Gateway restart.** After a successful update, Hermes attempts to restart all running gateway profiles of the home being updated (its root and every `profiles/<name>` under it) automatically so they pick up the new code. Gateways and `hermes-gateway*` services that belong to a different `HERMES_HOME` on the same machine — another install, or a scratch home running `hermes update` — are named in the output and left alone. Use `hermes gateway restart` when you want to restart a gateway without applying an update.-- **Restart-phase recovery.** If the in-process restart phase aborts while importing the freshly pulled tree, supervised gateway profiles are retried through a clean Python process. Only restarts independently confirmed by systemd (`systemctl --user is-active`) are reported as verified; a relaunch that merely exited 0 is recorded as `relaunch_attempted` and still fails the update conservatively. Manual gateways and serve/dashboard runtimes are never killed without a relaunch authority; they are recorded as skipped with a reason and remain in the incomplete-update report with the exact restart command.-- **Update receipts + fleet version check.** Every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/` (pre-update fleet plan, steps, skips with reasons, restart outcome; `latest.json` points at the newest). After the restart phase the updater verifies each live gateway's running code against the updated checkout and prints a per-profile version matrix; a gateway still on pre-update code fails the update (exit 1) with the exact restart command.+- **Restart-phase recovery.** If the in-process restart phase aborts while importing the freshly pulled tree, supervised gateway profiles are retried through a clean Python process. Only restarts independently confirmed by systemd (`systemctl --user is-active`) are reported as verified; a relaunch that merely exited 0 is recorded as `relaunch_attempted` and the restart stays owed (a `gateway_restart` follow-up; the update itself still exits 0 because the code is in place). Manual gateways and serve/dashboard runtimes are never killed without a relaunch authority; they are recorded as skipped with a reason and remain in the incomplete-update report with the exact restart command.+- **Update receipts + fleet version check.** Every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/` in the root Hermes home, even from a sticky profile (pre-update fleet plan, steps, skips with reasons, restart outcome, follow-ups; `latest.json` points at the newest and reads `running` while an update is in progress). After the restart phase the updater verifies each live gateway's running code against the updated checkout and prints a per-profile version matrix. A gateway still on pre-update code does not fail the update once the new code is in place: the update prints a `⚠` line with the exact restart command, exits 0, records a `gateway_restart` follow-up, and keeps the restart owed — every CLI start warns about it and the next `hermes update` retries it.- **Local source changes.** For git installs, dirty tracked files and untracked files are auto-stashed before branch checkout or pull (`git stash push --include-untracked`). Interactive terminal updates ask before restoring the stash. Non-interactive updates restore it by default; set `updates.non_interactive_local_changes: discard` only on managed installs where local source edits should be thrown away after a successful pull. If stash restore conflicts or the pull fails, the stash is left in place for manual recovery.- **npm lockfile churn.** Before stashing or switching branches, Hermes makes a best-effort cleanup of tracked `package-lock.json` diffs produced by npm install/build steps. Commit or manually stash intentional lockfile edits before running `hermes update`.- **Pairing data snapshot.** Even when `--backup` is off, `hermes update` takes a lightweight snapshot of `~/.hermes/pairing/` and the Feishu comment rules before `git pull`. You can roll it back with `hermes backup restore --state pre-update` if a pull rewrites a file you were editing.