Skip to content

The agent that grows with you

merge origin/main (7 commits) into ethie/pm-clean

ethernet793605bc7829
diff --cc apps/desktop/electron/main.ts
index d3c3bbef68e,0ba2a1f9567..c95b0ed7192
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -282,10 -269,14 +282,15 @@@ import type { InstallStamp } from './in
import { createIntroRevealWindowController } from './intro-reveal-window'
import { isAuthWall, resolveLinkTitle } from './link-title-wall'
import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'
- import { linuxCrashDiagnostics } from './linux-crash-diagnostics'
+ import {
+ CHROMIUM_LOG_FILENAME,
+ enableLinuxCrashDiagnostics,
+ linuxCrashDiagnostics
+ } from './linux-crash-diagnostics'
import { notifyLauncherWindowRevealed } from './linux-launcher-ready'
import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'
+import { registerMachineProfile } from './machine-profile'
+ import { ACTIVE_LOG_POLL_MS, planLogRotation, reclaimActiveLogIfOversized } from './log-rotation'
import { ensureMainWindow } from './main-window-lifecycle'
import {
assertManagedUpdatePreflightClear,
diff --cc hermes_cli/update_cmd_fleet.py
index 3336e77d234,0e50ac890bd..8d51e194987
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@@ -80,6 -132,42 +132,42 @@@ def _clear_fleet_restart_pending_marker
_m()._clear_marker_file(_fleet_restart_pending_marker_path(), label="fleet-restart-pending")
+ def _fleet_restart_obligation_armed() -> bool:
+ """True when this HOST owes a fleet restart — from any profile's CLI."""
+ from hermes_cli.update_host_obligation import host_obligation_present
+ if host_obligation_present():
+ return True
+ with suppress(OSError):
+ return _fleet_restart_pending_marker_path().is_file()
+ return False
+
+
+ def _obligation_fields() -> dict[str, str] | None:
+ """Armed obligation as ``key=value`` fields: HOST record first, then the legacy marker.
+
+ ``None`` means nothing armed OR a malformed record; both must leave the obligation standing.
+ """
+ from hermes_cli.update_host_obligation import host_obligation_present, obligation_fields
+ fields = obligation_fields()
+ if fields is not None:
+ return fields
+ if host_obligation_present():
+ # The record exists but its terms are unknown (corrupt, or a NEWER CLI's version). An
+ # unrelated legacy marker's inventory cannot discharge terms nobody can read: fail closed.
+ return None
+ try:
- text = _fleet_restart_pending_marker_path().read_text(encoding="utf-8")
++ text = _fleet_restart_pending_marker_path().read_text(encoding="utf-8-sig")
+ except (OSError, UnicodeError):
+ return None
+ legacy: dict[str, str] = {}
+ for line in text.splitlines():
+ key, sep, value = line.partition("=")
+ if not sep or key in legacy:
+ return None
+ legacy[key] = value
+ return legacy
+
+
def _current_checkout_sha() -> str | None:
"""Current on-disk checkout HEAD, or None if it cannot be resolved."""
from hermes_cli.update_cmd import _capture_head_sha, _m
@@@ -439,9 -522,77 +522,8 @@@ def _needs_sudo(scope: str) -> bool
)
-def _unit_main_pid(scope_cmd: list, svc_name: str) -> int:
- """Live ``MainPID`` of a unit; ``0`` when inactive, unprivileged or unreadable.
-
- Property reads need no manage-units privileges, and an unreadable PID is never collapsed:
- identity that cannot be proved keeps its own restart.
- """
- try:
- result = _systemctl(list(scope_cmd) + ["show", svc_name, "--property=MainPID", "--value"], timeout=10)
- except (OSError, subprocess.TimeoutExpired):
- return 0
- if getattr(result, "returncode", 1) != 0:
- return 0
- try:
- return int((getattr(result, "stdout", "") or "").strip() or 0)
- except ValueError:
- return 0
-
-
-def _restart_systemd_gateway_units_best_effort(failed: list, listings) -> None:
- """Restart every hermes-gateway/serve unit ONCE PER LIVE HOST PROCESS.
-
- One host runs one multiplexing gateway, so leftover per-profile units
- (``hermes-gateway-<profile>.service``) all point at the SAME live ``MainPID``; restarting
- each in turn restarts the host gateway N times — a self-inflicted N-fold outage triggered
- by one update. Units that share a live main PID are collapsed to one representative and the
- others are named as LEGACY units to migrate, never silently dropped.
- """
- from hermes_cli.update_host_obligation import collapse_units_to_host_processes
-
- answered = set()
- targets: dict[str, tuple[str, list, str]] = {} # "<scope>/<unit>" -> (scope, scope_cmd, unit)
- for scope, scope_cmd, result in listings:
- answered.add(scope)
- if result.returncode != 0:
- failed.append(f"systemd-{scope} (listing failed)")
- continue
- _for_each_systemd_gateway_unit(
- result.stdout,
- process_unit=lambda svc_name, _scope=scope, _cmd=scope_cmd: targets.setdefault(
- f"{_scope}/{svc_name}", (_scope, _cmd, svc_name)),
- on_unit_timeout=lambda svc_name, exc: failed.append(svc_name),
- )
-
- keys = list(targets)
- covered: dict[str, str] = {}
- if len(keys) > 1:
- # Only worth a `systemctl show` round when several units could be one process.
- keys, covered = collapse_units_to_host_processes(
- keys, lambda key: _unit_main_pid(targets[key][1], targets[key][2]))
- for unit_key, owner_key in covered.items():
- print(
- f" • {unit_key} is a legacy per-profile unit sharing one host gateway process with "
- f"{owner_key}; restarting it again would restart that process twice. Fold the units "
- "together with: hermes gateway migrate"
- )
-
- for key in keys:
- scope, scope_cmd, svc_name = targets[key]
- manage_cmd = list(scope_cmd) + ["--no-ask-password"]
- if _needs_sudo(scope):
- manage_cmd = ["sudo", "-n"] + manage_cmd
- try:
- result = _systemctl_reset_and_restart(manage_cmd, svc_name, scope_cmd=scope_cmd)
- if result.returncode != 0 or not _wait_for_service_active(scope_cmd, svc_name):
- failed.append(svc_name)
- except subprocess.TimeoutExpired:
- failed.append(svc_name)
- # A timeout or missing executable is not an empty scope.
- failed.extend(f"systemd-{scope} (listing unavailable)" for scope, _ in _SYSTEMD_SCOPES if scope not in answered)
-
def _live_fleet_current_rows() -> list[dict] | None:
"""The fleet matrix when the probe finds at least one gateway and every row is ``current``
at the checkout SHA (identity known); ``None`` on any unknown/stale/down row or a failed
@@@ -462,10 -613,203 +544,33 @@@
return None
+ def _restart_identity_sha() -> str:
+ """The SHA a completed host restart is stamped with; ``""`` when nothing names the code.
+
+ ``_current_checkout_sha()`` is ``None`` on every non-git install (zip, pip, Docker), and an
+ empty stamp can never match, so the per-host restart-once guard would be inert exactly on the
+ installs it exists for: each profile's ``hermes update`` would re-kill the one shared
+ multiplexer. The obligation's own ``expected_sha`` — else the receipt's post-update identity —
+ names the same pulled code.
+ """
+ sha = _current_checkout_sha()
+ if sha:
+ return str(sha)
+ sha = ((_obligation_fields() or {}).get("expected_sha") or "").strip()
+ if sha:
+ return sha
+ with suppress(Exception):
+ from hermes_cli.update_receipt import read_latest_receipt
+ post_update = (read_latest_receipt() or {}).get("post_update")
+ if isinstance(post_update, dict):
+ return str(post_update.get("sha") or "")
+ return ""
+
+
def _run_pending_fleet_restart() -> bool:
- """Catch-up restart for gateways left on pre-update code. Never raises.
-
- True when all discovered targets recovered (or none exist); False if incomplete.
-
- Idempotent per HOST: one process multiplexes every profile, so the second profile's
- ``hermes update`` must attach to the first one's restart instead of killing the shared
- gateway again (the obligation record carries the proof).
-
- See #95294.
- """
- from hermes_cli.update_cmd import _m
- from hermes_cli.update_host_obligation import host_restart_already_completed, mark_host_restart_completed
- checkout_sha = _restart_identity_sha()
- if host_restart_already_completed(checkout_sha):
- print(" ✓ This host's gateway was already restarted for this update — not restarting it again.")
- return True
- print("→ Restarting gateways left on pre-update code...")
- # Warn if legacy Hermes gateway unit files are still installed. When both hermes.service (from a
- # pre-rename install) and the current hermes-gateway.service are enabled, they SIGTERM-fight for the
- # same bot token (see PR #11909). Flagging here means every `hermes update` surfaces the issue until the
- # user migrates.
- try:
- from hermes_cli.gateway import (
- find_gateway_pids, is_macos, is_windows, kill_gateway_processes, supports_systemd_services,
- _wait_for_gateway_exit,
- )
- except Exception as exc:
- _warn_gateway_restart_phase_aborted(exc, None)
- return False
-
- try:
- pids = list(find_gateway_pids(all_profiles=True))
- except Exception as exc:
- logger.debug("Pending fleet restart: gateway probe failed: %s", exc)
- pids = None
-
- # A gateway this very update cold-started (or a manual `hermes gateway restart` seconds
- # ago) already serves the checkout code; stopping it here re-kills the fleet, and on
- # Windows the stop/start pair then reports "No gateway was running" plus a second spawn
- # (#117051). Skip when EVERY live gateway is current on the checkout SHA.
- if pids and _live_fleet_current_rows() is not None:
- print(" ✓ Every running gateway already serves the checkout code — nothing to restart.")
- return True
-
- failed: list = []
- try:
- # Snapshot before stopping: Restart=no units can disappear from list-units on a clean exit.
- systemd_listings = list(_systemd_gateway_unit_listings()) if supports_systemd_services() else None
- # Stop old processes before supervisor recovery, never its freshly verified workers.
- if pids != []:
- try:
- leftover = list(find_gateway_pids(all_profiles=True))
- except Exception:
- leftover = list(pids or [])
- if leftover:
- with _best_effort('Pending fleet restart: PID stop failed: %s'):
- kill_gateway_processes(all_profiles=True)
- _wait_for_gateway_exit(timeout=5.0, force_after=None)
- # --- Systemd services (Linux) --- Discover all hermes-gateway* units (default + profiles) plus
- # hermes-serve* units (the Desktop app's backend, #83438).
- if systemd_listings is not None:
- _restart_systemd_gateway_units_best_effort(failed, systemd_listings)
- # --- Launchd services (macOS) --- Restart EVERY ai.hermes.gateway* LaunchAgent, not only the
- # invoking profile's — parity with the systemd branch above (#41403). Per-label TimeoutExpired
- # isolation happens inside.
- if is_macos():
- try:
- _restart_macos_launchd_gateways([], failed, 45.0, require_supervision=True)
- except Exception as exc:
- logger.debug("Pending fleet restart: launchd failed: %s", exc)
- failed.append("launchd")
- if is_windows():
- try:
- from hermes_cli import gateway_windows
- if gateway_windows.is_installed():
- gateway_windows.restart()
- except Exception as exc:
- logger.debug("Pending fleet restart: Windows failed: %s", exc)
- failed.append("windows-gateway")
- if failed:
- _warn_incomplete_gateway_fleet_restart(failed)
- return False
- # Stamp the HOST obligation so every other profile's CLI knows this update's restart
- # already happened; without it each profile re-kills the one shared multiplexer.
- mark_host_restart_completed(checkout_sha or "")
- print(" ✓ Pending fleet restart completed.")
- return True
- except Exception as exc:
- try:
- surviving = list(find_gateway_pids(all_profiles=True))
- except Exception:
- surviving = pids
- _warn_gateway_restart_phase_aborted(exc, surviving)
- return False
-
-
-def _defer_fleet_restart_after_update(*, update_complete: bool, resume_incomplete: bool = False) -> None:
- """Record a deliberately deferred fleet restart and return/exit on outcome.
-
- ``hermes update --no-gateway-restart`` (cron running inside the gateway's
- own cgroup) updated code and dependencies but must not restart the fleet:
- the SIGUSR1 drain + systemd restart would kill the updater itself. The
- ``fleet_restart_pending`` marker written before the pull is KEPT so the
- next normal update (or ``hermes gateway restart``) catches up.
-
- Outcome contract (same success/partial meaning as the normal path):
- a STALE fleet caused only by this deliberate deferral is expected and
- does NOT make the update partial — exit 0, receipt "success". The receipt
- is "partial" (and the process exits 1, marker kept) when the update
- itself did not complete (``update_complete`` False) or the Windows
- pause/resume reconciliation reported incomplete.
-
- The live interpreter still serves pre-update code here, so callers must
- also skip stale-module purge/reload work: mutating this process's
- sys.modules graph mid-flight risks breaking the serving gateway.
- """
- print()
- print("→ Gateway restart skipped (--no-gateway-restart).")
- print(" Code and dependencies are updated; gateways still serve pre-update code.")
- print(" Restart them separately: `hermes gateway restart` or a daily-restart cron.")
- print(" (fleet restart deferred — marker kept for catch-up)")
- with suppress(Exception):
- from hermes_cli.update_receipt import record_skip
- record_skip("gateway_restart", "--no-gateway-restart: deferred, marker kept")
- partial = (not update_complete) or resume_incomplete
- with suppress(Exception):
- from hermes_cli.update_receipt import finalize_update_receipt
- finalize_update_receipt("partial" if partial else "success")
- if partial:
- sys.exit(1)
-
-
-def _apply_pending_fleet_restart_catchup(*, defer: bool = False) -> None:
- """On an already-up-to-date ``hermes update``, finish a skipped restart.
-
- No-op when nothing is pending; exits 1 on incomplete catch-up so automation
- does not treat the fleet as healthy. ``defer`` (``--no-gateway-restart``) keeps
- the marker and warns instead: running the restart from inside the gateway's own
- cgroup would kill the caller.
- """
- from hermes_cli.update_cmd import _run_pending_fleet_restart
- if not _pending_fleet_restart_needed():
- return
- if defer:
- print()
- _warn_pending_fleet_restart()
- print(" (fleet restart deferred — --no-gateway-restart; marker kept)")
- print(" Restart separately: `hermes gateway restart` or next non-cron update.")
- return
- print()
- _warn_pending_fleet_restart()
- print("→ Running the pending fleet restart...")
- if not _run_pending_fleet_restart():
- print(" ⚠ Fleet restart incomplete. Recover with: hermes gateway restart")
- sys.exit(1)
- if not _pending_fleet_restart_needed():
- return
- # The restart itself succeeded, but the receipt still owes gateways it cannot match to a
- # live row (unknown identity, pre-pull plan SHAs). When every live gateway serves the
- # checkout code, that matrix is the recovery evidence: settle the receipt with it instead of
- # failing this run — an exit 1 here writes another failed receipt and the warning never
- # clears, even after a successful manual `hermes gateway restart` (#117051).
- fleet = _live_fleet_current_rows()
- if fleet is not None:
- from hermes_cli.update_receipt import settle_latest_receipt_fleet
- settled = settle_latest_receipt_fleet(
- fleet, discharges=lambda receipt: not _pending_fleet_restart_needed(receipt=receipt)
- )
- if settled:
- print(f" ✓ Update receipt settled: {len(fleet)} gateway(s) serve the checkout code.")
- return
- print(" ⚠ Fleet restart ran, but gateways are still off the checkout code. Recover with: hermes gateway restart")
- sys.exit(1)
+ """Historical retry hook; new retries use the ordinary completion owner."""
+ from hermes_cli._old_updater import stop_for_relaunch
+ stop_for_relaunch(incomplete=True)
def _systemctl(cmd: list, *, timeout: float):
@@@ -1078,28 -1422,28 +1183,70 @@@ def _restart_systemd_gateway_units(rest
f"continuing with remaining gateways"
)
++ # Enumerate every scope first: leftover per-profile units (``hermes-gateway-<profile>``)
++ # all point at the SAME live MainPID on a multiplexed host, and restarting each in turn
++ # is an N-fold outage from one update. Units sharing a live PID collapse to one restart;
++ # the others are named as legacy units to migrate, never silently dropped.
++ from hermes_cli.update_host_obligation import collapse_units_to_host_processes
++ targets: dict[str, tuple[str, list, str]] = {} # "<scope>/<unit>" -> (scope, scope_cmd, unit)
for scope, scope_cmd, result in _systemd_gateway_unit_listings(_on_list_timeout):
-- # Scope-qualify this scope's additions before the next scope can add a
-- # same-named unit; ``finally`` so a mid-scope abort keeps settled units.
++ _for_each_systemd_gateway_unit(
++ result.stdout,
++ process_unit=lambda svc_name, _scope=scope, _cmd=scope_cmd: targets.setdefault(
++ f"{_scope}/{svc_name}", (_scope, _cmd, svc_name)),
++ on_unit_timeout=_on_unit_timeout,
++ )
++ keys = list(targets)
++ covered: dict[str, str] = {}
++ if len(keys) > 1:
++ # Only worth a `systemctl show` round when several units could be one process.
++ keys, covered = collapse_units_to_host_processes(
++ keys, lambda key: _unit_main_pid(targets[key][1], targets[key][2]))
++ for unit_key, owner_key in covered.items():
++ print(
++ f" • {unit_key} is a legacy per-profile unit sharing one host gateway process with "
++ f"{owner_key}; restarting it again would restart that process twice. Fold the units "
++ "together with: hermes gateway migrate"
++ )
++
++ for key in keys:
++ scope, scope_cmd, svc_name = targets[key]
++ # Scope-qualify before the next unit; ``finally`` so a mid-pass abort keeps settled units.
_scope_mark = len(restarted_services)
try:
-- _for_each_systemd_gateway_unit(
-- result.stdout,
-- process_unit=lambda svc_name: _restart_one_systemd_gateway_unit(
-- svc_name,
-- scope=scope,
-- scope_cmd=scope_cmd,
-- drain_budget=drain_budget,
-- _manage_cmd_cache=_manage_cmd_cache,
-- restarted_services=restarted_services,
-- failed_or_stale_units=failed_or_stale_units,
-- ),
-- on_unit_timeout=_on_unit_timeout,
++ _restart_one_systemd_gateway_unit(
++ svc_name,
++ scope=scope,
++ scope_cmd=scope_cmd,
++ drain_budget=drain_budget,
++ _manage_cmd_cache=_manage_cmd_cache,
++ restarted_services=restarted_services,
++ failed_or_stale_units=failed_or_stale_units,
)
++ except subprocess.TimeoutExpired as exc:
++ _on_unit_timeout(svc_name, exc)
finally:
restarted_scoped_units.update(f"{scope}/{name}" for name in restarted_services[_scope_mark:])
++def _unit_main_pid(scope_cmd: list, svc_name: str) -> int:
++ """Live ``MainPID`` of a unit; ``0`` when inactive, unprivileged or unreadable.
++
++ Property reads need no manage-units privileges, and an unreadable PID is never collapsed:
++ identity that cannot be proved keeps its own restart.
++ """
++ try:
++ result = _systemctl(list(scope_cmd) + ["show", svc_name, "--property=MainPID", "--value"], timeout=10)
++ except (OSError, subprocess.TimeoutExpired):
++ return 0
++ if getattr(result, "returncode", 1) != 0:
++ return 0
++ try:
++ return int((getattr(result, "stdout", "") or "").strip() or 0)
++ except ValueError:
++ return 0
++
++
@dataclass
class _GatewayRestartOutcome:
"""Restart-phase bookkeeping. ``restarted_services`` keeps bare unit names (fleet
diff --cc hermes_cli/update_host_obligation.py
index 00000000000,849269f3a98..23a6ae62c3d
mode 000000,100644..100644
--- a/hermes_cli/update_host_obligation.py
+++ b/hermes_cli/update_host_obligation.py
@@@ -1,0 -1,221 +1,221 @@@
+ """Host-scoped update→restart obligation for ``hermes update``.
+
+ Multiplex-only (Teknium ruling): exactly ONE ``hermes gateway run`` per host serves every
+ profile, so "this pull still owes the fleet a restart" is a property of the HOST, not of one
+ profile's ``HERMES_HOME``. The legacy ``$HERMES_HOME/fleet_restart_pending`` marker was
+ per-home: ``hermes -p coder update`` armed and cleared coder's copy while restarting the
+ SHARED process, and every other profile's CLI could neither see nor discharge that obligation
+ — it simply armed its own and re-killed the same host process.
+
+ The record therefore lives beside the host rendezvous record, in
+ :func:`gateway.host_rendezvous.host_state_dir` (``$HERMES_GATEWAY_LOCK_DIR`` else
+ ``$XDG_STATE_HOME/hermes/gateway-locks``) — the one cross-profile, per-OS-user state root the
+ tree already has. It is written once per host, read by every profile's CLI, and cleared once.
+
+ The same "one host process, not one per profile" identity is what
+ :func:`collapse_units_to_host_processes` applies to enumerated systemd units: leftover
+ per-profile ``hermes-gateway-<p>.service`` units on a multiplexed host all point at the same
+ live ``MainPID``, so restarting each one restarts the host process N times.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import os
+ import time
+ from pathlib import Path
+ from typing import Any, Callable, Iterable, Optional
+
+ logger = logging.getLogger("hermes_cli.update_cmd")
+
+ #: One file per OS user, beside ``host-gateway.json`` / ``host-serve.json``.
+ HOST_OBLIGATION_NAME = "host-update-restart.json"
+
+ _RECORD_VERSION = 1
+
+
+ def host_obligation_path() -> Optional[Path]:
+ """Path of the host obligation record, or ``None`` when the host state dir is unresolvable."""
+ try:
+ from gateway.host_rendezvous import host_state_dir
+
+ return host_state_dir() / HOST_OBLIGATION_NAME
+ except Exception: # pragma: no cover - import/env failure must never break the updater
+ logger.debug("Host obligation path unavailable", exc_info=True)
+ return None
+
+
+ def read_host_obligation() -> Optional[dict]:
+ """The published obligation record, or ``None`` when absent/corrupt/foreign-versioned."""
+ path = host_obligation_path()
+ if path is None:
+ return None
+ try:
- payload = json.loads(path.read_text(encoding="utf-8"))
++ payload = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, UnicodeDecodeError, ValueError):
+ return None
+ if not isinstance(payload, dict) or payload.get("version") != _RECORD_VERSION:
+ return None
+ return payload
+
+
+ def host_obligation_present() -> bool:
+ """True when the record FILE exists, parseable or not.
+
+ Fail-closed: a corrupt record is an obligation whose terms are unknown, never a discharged
+ one — the restart is still owed and the reader falls back to "no recorded inventory".
+ """
+ path = host_obligation_path()
+ if path is None:
+ return False
+ try:
+ return path.is_file()
+ except OSError:
+ return False
+
+
+ def amend_host_obligation(**fields: Any) -> None:
+ """Merge ``fields`` into the armed record (test/diagnostic surface). Never raises."""
+ record = read_host_obligation()
+ path = host_obligation_path()
+ if record is None or path is None:
+ return
+ record.update(fields)
+ try:
+ from utils import atomic_json_write
+
+ atomic_json_write(path, record, mode=0o600)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("Could not amend host update-restart obligation: %s", exc)
+
+
+ def write_host_obligation(
+ *, expected_sha: str = "", runtimes: Optional[list] = None, profile: str = ""
+ ) -> bool:
+ """Arm the host obligation. True when it was written. Never raises.
+
+ Re-arming from a second profile for the SAME pulled SHA keeps the existing record (and its
+ ``restarted`` proof) instead of resetting it: the host owes one restart, not one per profile.
+ """
+ path = host_obligation_path()
+ if path is None:
+ return False
+ existing = read_host_obligation()
+ if existing is not None and expected_sha and existing.get("expected_sha") == expected_sha:
+ # Same pull, second profile: the host owes ONE restart, so keep the standing record (and
+ # any proof that the restart already happened) rather than resetting it. A later arm that
+ # carries the owed inventory still upgrades it — an inventory-less record owes no set.
+ if runtimes is None:
+ return True
+ inventory = {"version": 1, "runtimes": runtimes}
+ if existing.get("inventory") != inventory:
+ amend_host_obligation(inventory=inventory)
+ return True
+ payload: dict[str, Any] = {
+ "version": _RECORD_VERSION,
+ "started": time.time(),
+ "pid": os.getpid(),
+ "armed_by_profile": profile or "",
+ "expected_sha": expected_sha or "",
+ }
+ if runtimes is not None:
+ payload["inventory"] = {"version": 1, "runtimes": runtimes}
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ from utils import atomic_json_write
+
+ atomic_json_write(path, payload, mode=0o600)
+ except Exception as exc:
+ logger.debug("Could not write host update-restart obligation: %s", exc)
+ return False
+ return True
+
+
+ def clear_host_obligation() -> None:
+ """Discharge the obligation for the whole host. Never raises."""
+ path = host_obligation_path()
+ if path is None:
+ return
+ try:
+ path.unlink(missing_ok=True)
+ except OSError as exc:
+ logger.debug("Could not clear host update-restart obligation: %s", exc)
+
+
+ def obligation_fields() -> Optional[dict[str, str]]:
+ """The obligation in the legacy ``key=value`` field shape, or ``None`` when unarmed.
+
+ Keeps one parser for both sources: the fields a reader needs (``expected_sha``, the
+ serialized ``inventory``) are identical whether they came from the host record or from an
+ in-flight legacy per-home marker.
+ """
+ record = read_host_obligation()
+ if record is None:
+ return None
+ fields = {"expected_sha": str(record.get("expected_sha") or "")}
+ inventory = record.get("inventory")
+ if inventory is not None:
+ fields["inventory"] = json.dumps(inventory)
+ return fields
+
+
+ def mark_host_restart_completed(sha: str) -> None:
+ """Record that the host process was restarted onto ``sha``. Never raises."""
+ record = read_host_obligation()
+ path = host_obligation_path()
+ if record is None or path is None:
+ return
+ record["restarted"] = {"sha": sha or "", "pid": os.getpid(), "at": time.time()}
+ try:
+ from utils import atomic_json_write
+
+ atomic_json_write(path, record, mode=0o600)
+ except Exception as exc:
+ logger.debug("Could not stamp host restart completion: %s", exc)
+
+
+ def host_restart_already_completed(sha: Optional[str]) -> bool:
+ """True when THIS host obligation was already restarted onto ``sha``.
+
+ The guard that makes the catch-up restart idempotent per host: a second profile running
+ ``hermes update`` must attach to the first restart's outcome, never kill the shared
+ multiplexer again.
+ """
+ record = read_host_obligation()
+ if record is None or not sha:
+ return False
+ restarted = record.get("restarted")
+ return isinstance(restarted, dict) and str(restarted.get("sha") or "") == sha
+
+
+ def collapse_units_to_host_processes(
+ units: Iterable[str], main_pid: Callable[[str], int]
+ ) -> tuple[list[str], dict[str, str]]:
+ """Split enumerated units into ``(restart, {legacy_unit: covering_unit})``.
+
+ Units resolving to the same live ``MainPID`` are ONE host process; restarting each of them
+ restarts that process N times, which on a multiplexed host is an N-fold outage triggered by
+ leftover per-profile units. A unit with no readable main PID (inactive, unprivileged scope)
+ keeps its own restart: identity that cannot be proved is never collapsed away.
+ """
+ restart: list[str] = []
+ covered: dict[str, str] = {}
+ owner_by_pid: dict[int, str] = {}
+ for unit in units:
+ try:
+ pid = int(main_pid(unit) or 0)
+ except Exception:
+ # Identity that cannot be proved keeps its own restart; a probe failure of any kind
+ # must never abort the whole pass.
+ pid = 0
+ if pid <= 0:
+ restart.append(unit)
+ continue
+ owner = owner_by_pid.get(pid)
+ if owner is None:
+ owner_by_pid[pid] = unit
+ restart.append(unit)
+ else:
+ covered[unit] = owner
+ return restart, covered
diff --cc hermes_cli/update_restart_recovery.py
index f49b41cf36d,bf7b1f4570c..5b4ec296654
--- a/hermes_cli/update_restart_recovery.py
+++ b/hermes_cli/update_restart_recovery.py
@@@ -149,11 -149,77 +149,77 @@@ def _systemd_verified_active(profile: s
)
+ def _host_state_dir() -> str:
+ """The path ``gateway.host_rendezvous.host_state_dir()`` resolves, computed locally.
+
+ This module imports no Hermes code at runtime — importing the freshly pulled tree is exactly
+ what aborted the phase that calls us — so the rule is duplicated here rather than shared.
+ """
+ override = os.environ.get("HERMES_GATEWAY_LOCK_DIR")
+ if override:
+ return override
+ state_home = os.environ.get("XDG_STATE_HOME") or ""
+ if not os.path.isabs(state_home):
+ state_home = os.path.join(os.path.expanduser("~"), ".local", "state")
+ return os.path.join(state_home, "hermes", "gateway-locks")
+
+
+ def _pid_is_live(pid: int) -> bool:
+ """Liveness of ``pid``: ``psutil`` when importable, else the POSIX signal-0 probe.
+
+ The signal probe is POSIX-only by construction — on Windows ``os.kill(pid, 0)`` sends a real
+ control event and can kill the target — so an unimportable psutil there means "cannot prove".
+ """
+ try:
+ import psutil
+
+ return bool(psutil.pid_exists(pid))
+ except Exception:
+ pass
+ if os.name == "nt":
+ return False
+ try:
+ os.kill(pid, 0) # windows-footgun: ok — POSIX-only branch, guarded by os.name above
+ except PermissionError:
+ return True
+ except OSError:
+ return False
+ return True
+
+
+ def _host_served_profiles() -> set[str]:
+ """Profiles the ONE live host gateway multiplexes, from its rendezvous record.
+
+ Restarting any one of them restarts the same process, so they are a single restart target.
+ Empty (no collapsing, today's per-profile behaviour) when the record is absent, unreadable,
+ dead, or when liveness cannot be probed — a missed collapse costs an extra restart, a wrong
+ one would skip a profile that really has its own process.
+ """
+ try:
- with open(os.path.join(_host_state_dir(), "host-gateway.json"), encoding="utf-8") as handle:
++ with open(os.path.join(_host_state_dir(), "host-gateway.json"), encoding="utf-8-sig") as handle:
+ record = json.load(handle)
+ except (OSError, UnicodeDecodeError, ValueError):
+ return set()
+ if not isinstance(record, dict) or record.get("role") != "gateway":
+ return set()
+ pid = record.get("pid")
+ profiles = record.get("profiles")
+ if not isinstance(pid, int) or pid <= 0 or not isinstance(profiles, list) or not _pid_is_live(pid):
+ return set()
+ return {name for name in profiles if isinstance(name, str) and name}
+
+
def restart_profiles(
profiles: Iterable[str], *, supervisors: Mapping[str, str] | None = None, run: Callable[..., Any] = subprocess.run
- ) -> dict[str, list[str]]:
+ ) -> dict[str, Any]:
"""Restart the supplied profiles (only ones whose inventory identified a service supervisor).
+ Profiles served by the SAME host gateway process are one restart target: a host multiplexes
+ every profile, so N payload profiles meant N sequential ``gateway restart`` calls, each
+ killing the successor the previous pass had just verified. The group is restarted exactly
+ once through one representative and the rest are reported under ``covered`` with that
+ restart's outcome.
+
A profile only lands in ``verified`` when its supervisor is systemd and ``systemctl --user is-
active`` independently confirms the unit after the relaunch command succeeded.
"""
diff --cc tests/hermes_cli/conftest.py
index 9958b10a534,01a4ac845e9..e45fcc0aae4
--- a/tests/hermes_cli/conftest.py
+++ b/tests/hermes_cli/conftest.py
@@@ -57,41 -57,107 +57,67 @@@ def _suppress_concurrent_hermes_gate(re
@pytest.fixture(autouse=True)
-def _inline_post_swap_handoff(request, monkeypatch):
- """Run the post-swap tail in-process instead of re-executing ``hermes update --post-swap``.
-
- ``_apply_pulled_update`` / ``_update_via_zip`` hand the rest of the run to a child
- interpreter on the pulled tree. A mocked updater flow must not spawn that child (it would
- run a real dependency sync against the worktree), so the tail runs here through the same
- payload round-trip — every step stays patchable and the payload shape is still exercised.
- Tests of the hand-off itself opt out with ``@pytest.mark.real_post_swap_handoff``.
+def _source_channels_resolve_locally(request, monkeypatch):
+ """Every unflagged ``hermes update`` resolves its channel through R2; tests must
+ not reach the network for that. Default every channel to a ``source-branch``
+ record delivering ``origin/<name>`` through the documented seam. Channel tests
+ that model records themselves re-patch ``_resolve_channel`` after this runs;
+ the marker opts out entirely for tests of the reader's own network path.
"""
- if request.node.get_closest_marker("real_post_swap_handoff"):
- return
- try:
- from hermes_cli import update_cmd, update_receipt
- except Exception:
+ if request.node.get_closest_marker("real_release_channels"):
return
+ from hermes_cli import source_releases
+ from hermes_cli.release_channels import ChannelResolution
- def _inline(args, **payload_kwargs):
- payload = update_cmd._post_swap_payload(**payload_kwargs)
- if payload["receipt"]:
- update_receipt.resume_update_receipt(payload["receipt"])
- update_cmd._execute_post_swap(payload, args, payload_kwargs["gateway_mode"])
+ def resolve(name, repository):
+ record = {"schema": 1, "name": name, "repository": repository, "policy": "source-branch",
+ "state": "active", "identity": None, "nextSequence": 1, "head": None,
+ "delivery": {"kind": "source-branch", "branch": name}}
+ return ChannelResolution(record, record, None)
- monkeypatch.setattr(update_cmd, "_hand_off_post_swap", _inline, raising=False)
+ monkeypatch.setattr(source_releases, "_resolve_channel", resolve)
+ @pytest.fixture(autouse=True)
+ def _discharge_host_update_obligation():
+ """Start and end every ``hermes_cli`` test with NO host update-restart obligation.
+
+ The record is host-scoped on purpose (one multiplexer per host), so it lives in the
+ per-OS-USER host state dir — not in the per-test ``HERMES_HOME``. The root conftest pins
+ that dir per test only when the caller supplied no ``HERMES_GATEWAY_LOCK_DIR`` (#118097
+ keeps the documented override working), so with one set every test in a file shares it and
+ a test that arms the obligation makes the next one read a restart it never owed. Clearing
+ the record — rather than re-pinning the dir — leaves that override rule untouched.
+ """
+
+ def _clear() -> None:
+ try:
+ from hermes_cli.update_host_obligation import clear_host_obligation
+
+ clear_host_obligation()
+ except Exception:
+ # Import/env failure here must never error an unrelated test.
+ pass
+
+ _clear()
+ yield
+ _clear()
+
+
@pytest.fixture
-def isolated_update_runtime(monkeypatch, tmp_path, request):
- """Keep mocked updater flows off the host checkout and runtime fleet."""
- from hermes_cli import gateway, main, update_cmd, update_cmd_fleet
- from hermes_cli import update_inventory, update_receipt
-
- checkout = tmp_path / "isolated-update-checkout"
- (checkout / ".git").mkdir(parents=True)
- (checkout / "apps" / "desktop").mkdir(parents=True)
- monkeypatch.setattr(main, "PROJECT_ROOT", checkout)
- if hasattr(request.module, "PROJECT_ROOT"):
- monkeypatch.setattr(request.module, "PROJECT_ROOT", checkout)
-
- monkeypatch.setattr(gateway, "find_gateway_pids", lambda *a, **k: [])
- monkeypatch.setattr(gateway, "find_profile_gateway_processes", lambda *a, **k: [])
- monkeypatch.setattr(gateway, "_get_service_pids", lambda *a, **k: set())
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(main, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(main, "_resume_windows_gateways_after_update", lambda *a, **k: None)
- monkeypatch.setattr(main, "_detect_venv_python_processes", lambda: [])
- monkeypatch.setattr(main, "_restore_active_tool_dependencies", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd, "_clear_windows_venv_holders_or_exit", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd, "_finish_dashboard_update_cleanup", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd, "_apply_pending_fleet_restart_catchup", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd_fleet, "_restart_macos_launchd_gateways", lambda *a, **k: None)
- monkeypatch.setattr(update_inventory, "collect_runtime_inventory", lambda: None)
- monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda *a, **k: [])
-
-
-# ---- prompt_toolkit / capsys isolation ----
-# ``cli._cprint`` renders through ``prompt_toolkit.print_formatted_text``,
-# which — when called with no explicit ``output=`` — lazily creates an
-# ``Output`` from ``sys.stdout`` **and caches it on the process-global default
-# ``AppSession``** (``prompt_toolkit.application.current._current_app_session``,
-# a ``ContextVar`` with a module-level default). The cache is keyed to nothing
-# and never re-reads ``sys.stdout``.
-#
-# Under pytest, ``capsys`` swaps ``sys.stdout`` for a fresh buffer per test.
-# So the first CLI test that emits through ``_cprint`` (e.g. one exercising
-# ``/queue``, which prints a "Queued: …" line) locks prompt_toolkit's cached
-# output onto *its* captured stdout. Every later ``capsys`` test that asserts
-# on ``_cprint`` output then reads an empty buffer, because the render went to
-# the first test's now-dead capture target. That is the mechanism behind the
-# order-dependent ``test_resume_quiet_stderr`` failure: it passes in isolation
-# and in its own file, but fails in a full ``tests/cli`` run.
-#
-# Reset the cached output before every CLI test so each one re-creates a fresh
-# prompt_toolkit ``Output`` bound to its own ``sys.stdout`` on first use. This
-# is a no-op when prompt_toolkit isn't importable and cheap otherwise (the
-# property re-creates lazily).
+def isolated_source_completion(monkeypatch):
+ """Unit-test the completion tail in-process; real transport is tested separately."""
+ from hermes_cli import update_cmd, update_completion
+
+ monkeypatch.setattr("hermes_cli.source_build.build_update_products", lambda *a, **kw: None)
+ monkeypatch.setattr("hermes_cli.venv_sync.publish_launchers", lambda *a: None)
+
+ def complete(request):
+ update_completion._complete_selected(request)
+ return {"exit_code": 0, "receipt": update_completion._read_terminal_receipt(request),
+ "windows_resume": request["windows_resume"]}
+
+ monkeypatch.setattr(update_cmd, "run_completion", complete)
@pytest.fixture(autouse=True)
diff --cc tests/hermes_cli/test_manual_serve_deferral.py
index 3462bac41b1,b9d813caf00..7e54177a02d
--- a/tests/hermes_cli/test_manual_serve_deferral.py
+++ b/tests/hermes_cli/test_manual_serve_deferral.py
@@@ -38,15 -38,15 +38,15 @@@ def test_manual_deferral_survives_recei
restart.incomplete = True
if condition != "alive":
with pytest.raises(SystemExit) as exc:
- fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, node_failures=[], update_complete=True)
+ fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)
assert exc.value.code == 1
- assert fleet._fleet_restart_pending_marker_path().exists()
+ assert fleet._fleet_restart_obligation_armed()
assert update_receipt.read_latest_receipt()["outcome"] == "partial"
return
- fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, node_failures=[], update_complete=True)
+ fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)
receipt = update_receipt.read_latest_receipt()
assert receipt["runtime_outcomes"][0]["outcome"] == "deferred"
- assert not fleet._fleet_restart_pending_marker_path().exists()
+ assert not fleet._fleet_restart_obligation_armed()
assert "hermes-serve.service" not in capsys.readouterr().out
update_receipt.begin_update_receipt()
update_receipt.finalize_update_receipt("success", fleet=[])
diff --cc tests/hermes_cli/test_update_fleet_restart_pending.py
index fec311653aa,53c086408d4..41b7aa3a62c
--- a/tests/hermes_cli/test_update_fleet_restart_pending.py
+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py
@@@ -26,14 -26,16 +26,16 @@@ import hermes_cli.main_web_build as mai
import hermes_cli.main_install_repair as main_install_repair
from hermes_cli import update_cmd
import hermes_cli.update_cmd_fleet as update_cmd_fleet
-import hermes_cli.update_cmd_deps as update_cmd_deps
from hermes_cli.update_receipt import COMMAND_BOUNDARY_STOP_REASON
from hermes_constants import get_hermes_home
+ import hermes_cli.update_host_obligation as host_obligation
+ from gateway import host_rendezvous
+pytestmark = pytest.mark.usefixtures("isolated_source_completion")
-def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
- """Simulate git commands where HEAD advances from pre_sha to post_sha."""
- calls = {"n": 0}
+
+def _make_up_to_date_side_effect(sha="abc123"):
+ """Simulate git commands where origin is already at HEAD."""
def side_effect(cmd, **kwargs):
joined = " ".join(str(c) for c in cmd)
@@@ -550,11 -585,120 +552,11 @@@ def test_interrupt_between_pull_and_res
with pytest.raises(KeyboardInterrupt):
hermes_main.cmd_update(args)
- marker = update_cmd._fleet_restart_pending_marker_path()
- assert marker.is_file()
- assert "expected_sha=def456" in marker.read_text(encoding="utf-8")
+ assert update_cmd_fleet._fleet_restart_obligation_armed()
+ record = json.loads(host_obligation.host_obligation_path().read_text(encoding="utf-8"))
+ assert record["expected_sha"] == "def456"
-def test_already_up_to_date_runs_pending_restart_when_marker_present(
- monkeypatch, tmp_path, capsys
-):
- args = _update_args()
- _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())
- monkeypatch.setattr(update_cmd_fleet, "_current_checkout_sha", lambda: "abc123")
- update_cmd._write_fleet_restart_pending_marker(expected_sha="abc123", runtimes=[{"kind": "gateway", "profile": "default"}])
-
- seen = {"ran": False}
- monkeypatch.setattr(
- "hermes_cli.update_receipt.collect_fleet_versions",
- lambda **k: [{"profile": "default", "state": "current", "code_sha": "abc123"}] if seen["ran"] else [],
- )
-
- def _restart():
- seen["ran"] = True
- return True
-
- monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", _restart)
- monkeypatch.setattr(update_cmd_fleet, "_run_pending_fleet_restart", _restart)
-
- hermes_main.cmd_update(args)
-
- assert seen["ran"] is True
- assert not update_cmd_fleet._fleet_restart_obligation_armed()
- out = capsys.readouterr().out
- assert "did not restart running gateways" in out
-
-
-def test_already_up_to_date_runs_pending_restart_when_receipt_skewed(
- monkeypatch, tmp_path, capsys
-):
- args = _update_args()
- _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())
-
- disk_sha = "e" * 40
- monkeypatch.setattr(update_cmd, "_current_checkout_sha", lambda: disk_sha)
- monkeypatch.setattr(update_cmd_fleet, "_current_checkout_sha", lambda: disk_sha)
- receipt_dir = get_hermes_home() / "logs" / "update_receipts"
- receipt_dir.mkdir(parents=True)
- (receipt_dir / "latest.json").write_text(
- json.dumps(
- {
- "exit_code": 1,
- "stop_reason": "KeyboardInterrupt: ",
- "outcome": "failed",
- "plan": {
- "expected_sha": disk_sha,
- "runtimes": [
- {
- "kind": "gateway",
- "profile": "default",
- "pid": 42,
- "code_sha": "7" * 40,
- }
- ],
- },
- }
- ),
- encoding="utf-8",
- )
-
- seen = {"ran": False}
- monkeypatch.setattr(
- "hermes_cli.update_receipt.collect_fleet_versions",
- lambda **k: [{"profile": "default", "state": "current", "code_sha": disk_sha}] if seen["ran"] else [],
- )
- monkeypatch.setattr(
- update_cmd,
- "_run_pending_fleet_restart",
- lambda: seen.__setitem__("ran", True) or True,
- )
- monkeypatch.setattr(
- update_cmd_fleet,
- "_run_pending_fleet_restart",
- lambda: seen.__setitem__("ran", True) or True,
- )
-
- hermes_main.cmd_update(args)
-
- assert seen["ran"] is True
- out = capsys.readouterr().out
- assert "did not restart running gateways" in out
-
-
-def test_already_up_to_date_skips_restart_when_nothing_pending(
- monkeypatch, tmp_path, capsys
-):
- args = _update_args()
- _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())
-
- seen = {"ran": False}
- monkeypatch.setattr(
- update_cmd,
- "_run_pending_fleet_restart",
- lambda: seen.__setitem__("ran", True) or True,
- )
- monkeypatch.setattr(
- update_cmd_fleet,
- "_run_pending_fleet_restart",
- lambda: seen.__setitem__("ran", True) or True,
- )
-
- hermes_main.cmd_update(args)
-
- assert seen["ran"] is False
- assert "did not restart running gateways" not in capsys.readouterr().out
-
-
def test_startup_warn_prints_when_marker_present(capsys):
update_cmd._write_fleet_restart_pending_marker()
update_cmd._warn_pending_fleet_restart_on_startup()
diff --cc tests/hermes_cli/test_update_host_obligation.py
index 00000000000,421455996f0..fd3d9f5776b
mode 000000,100644..100644
--- a/tests/hermes_cli/test_update_host_obligation.py
+++ b/tests/hermes_cli/test_update_host_obligation.py
@@@ -1,0 -1,304 +1,261 @@@
+ """The update→restart obligation is HOST-scoped, and one update restarts the host gateway once.
+
+ Multiplex-only (Teknium ruling): exactly one ``hermes gateway run`` per host serves every
+ profile. The obligation used to live in ONE profile's ``HERMES_HOME``, so ``hermes -p coder
+ update`` armed and cleared coder's copy while restarting the SHARED process; no other profile
+ could see that obligation, and every profile that ran the catch-up killed the same gateway
+ again. These tests pin the host-scoped contract:
+
+ - an obligation armed from one profile is owed (and dischargeable) from every other profile;
-- the host gateway is restarted AT MOST ONCE per obligation, however many profiles run it;
+ - enumerated systemd units that resolve to one live main PID restart that process once;
+ - the fresh-process recovery restarts one host process for every profile it serves.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import os
+ from types import SimpleNamespace
+
+ import pytest
+
+ import hermes_cli.update_cmd_fleet as fleet
+ import hermes_cli.update_host_obligation as host_obligation
+ import hermes_cli.update_restart_recovery as recovery
+ from hermes_cli import update_cmd
+
+ SHA = "a" * 40
+
+
+ @pytest.fixture
+ def two_profiles(tmp_path, monkeypatch):
+ """Two profile HERMES_HOMEs behind ONE host state dir — the real multiplex topology."""
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "gateway-locks"))
+ homes = {}
+ for name in ("coder", "writer"):
+ home = tmp_path / "profiles" / name
+ home.mkdir(parents=True)
+ homes[name] = home
+ return homes
+
+
+ def _enter(monkeypatch, home) -> None:
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+
+ def _arm(profile_runtime: str) -> None:
+ fleet._write_fleet_restart_pending_marker(
+ expected_sha=SHA, runtimes=[{"kind": "gateway", "profile": profile_runtime}])
+
+
+ @pytest.fixture
+ def no_live_fleet(monkeypatch):
+ """No fleet matrix rows: the obligation can never be discharged by evidence in these tests."""
+ monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: SHA)
+ monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda: [])
+
+
+ def test_obligation_armed_by_one_profile_is_owed_by_every_other(two_profiles, no_live_fleet, monkeypatch):
+ """One host, one obligation: the profile that did not pull still owes — and can discharge — it."""
+ _enter(monkeypatch, two_profiles["coder"])
+ _arm("coder")
+
+ _enter(monkeypatch, two_profiles["writer"])
+ assert fleet._pending_fleet_restart_needed() is True
+
+ fleet._clear_fleet_restart_pending_marker()
+ _enter(monkeypatch, two_profiles["coder"])
+ assert fleet._pending_fleet_restart_needed() is False
+
+
-def test_host_gateway_restarts_once_when_two_profiles_run_the_catch_up(
- two_profiles, no_live_fleet, monkeypatch, capsys
-):
- """``hermes -p coder update`` then ``hermes -p writer update`` stops the host gateway ONCE."""
- monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda **k: [4242])
- monkeypatch.setattr("hermes_cli.gateway.supports_systemd_services", lambda: False)
- monkeypatch.setattr("hermes_cli.gateway.is_macos", lambda: False)
- monkeypatch.setattr("hermes_cli.gateway.is_windows", lambda: False)
- monkeypatch.setattr("hermes_cli.gateway._wait_for_gateway_exit", lambda **k: True)
- monkeypatch.setattr(fleet, "_restart_macos_launchd_gateways", lambda *a, **k: None)
- kills: list = []
- monkeypatch.setattr("hermes_cli.gateway.kill_gateway_processes", lambda **k: kills.append(k))
-
- _enter(monkeypatch, two_profiles["coder"])
- _arm("coder")
- assert update_cmd._run_pending_fleet_restart() is True
-
- _enter(monkeypatch, two_profiles["writer"])
- _arm("writer")
- assert update_cmd._run_pending_fleet_restart() is True
-
- assert len(kills) == 1, "the one host gateway must be stopped once per update, not once per profile"
- assert "already restarted for this update" in capsys.readouterr().out
-
-
+ def test_legacy_per_home_marker_is_still_read_and_cleared(two_profiles, no_live_fleet, monkeypatch):
+ """An obligation armed by the pre-host-scope code must still be discharged after the upgrade."""
+ _enter(monkeypatch, two_profiles["coder"])
+ legacy = fleet._fleet_restart_pending_marker_path()
+ legacy.write_text(
+ f"started=1.0\npid=1\nexpected_sha={SHA}\n"
+ + "inventory=" + json.dumps({"version": 1, "runtimes": [{"kind": "gateway", "profile": "coder"}]}) + "\n",
+ encoding="utf-8",
+ )
+
+ assert fleet._pending_fleet_restart_needed() is True
+ fleet._clear_fleet_restart_pending_marker()
+ assert not legacy.exists()
+ assert fleet._pending_fleet_restart_needed() is False
+
+
+ def _listing(units: list[str]):
+ result = SimpleNamespace(returncode=0, stdout="\n".join(f"{u} loaded active running x" for u in units))
+ return [("user", ["systemctl", "--user"], result)]
+
+
-def test_leftover_per_profile_units_restart_their_one_host_process_once(monkeypatch, capsys):
- """Three units, one live main PID = one host gateway: restart it once and name the legacy units."""
- # raising=False keeps this usable as the red-on-base A/B (the helper is the fix).
- monkeypatch.setattr(fleet, "_unit_main_pid", lambda scope_cmd, svc: 4242, raising=False)
- restarted: list[str] = []
++def _patch_live_unit_restart(monkeypatch, restarted: list[str], main_pid) -> None:
++ """The live post-update systemd pass with every systemctl seam stubbed: every unit is
++ active, restarts succeed instantly, and ``MainPID`` comes from ``main_pid``."""
++ monkeypatch.setattr("hermes_cli.gateway.supports_systemd_services", lambda: True)
++ monkeypatch.setattr("hermes_cli.gateway._ensure_user_systemd_env", lambda: None)
++ monkeypatch.setattr(fleet, "_unit_main_pid", main_pid)
++ monkeypatch.setattr(fleet, "_systemd_gateway_unit_listings", lambda on_list_timeout=None: _listing([
++ "hermes-gateway.service", "hermes-gateway-coder.service", "hermes-gateway-writer.service"]))
++ monkeypatch.setattr(fleet, "_service_unit_supports_graceful_sigusr1_restart", lambda svc: False)
++ monkeypatch.setattr(fleet, "_resolve_manage_cmd", lambda cache, scope, scope_cmd, svc: list(scope_cmd))
++ monkeypatch.setattr(fleet, "_systemctl", lambda cmd, timeout: SimpleNamespace(returncode=0, stdout="active"))
+ monkeypatch.setattr(
+ fleet, "_systemctl_reset_and_restart",
+ lambda manage_cmd, svc, scope_cmd=None: restarted.append(svc) or SimpleNamespace(returncode=0))
- monkeypatch.setattr(fleet, "_wait_for_service_active", lambda scope_cmd, svc: True)
++ monkeypatch.setattr(fleet, "_wait_for_service_active", lambda scope_cmd, svc, timeout=10.0: True)
++ monkeypatch.setattr(fleet, "_systemd_restart_timeout", lambda *a, **k: 1.0)
+ monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", ["systemctl", "--user"]),))
+
++
++def test_leftover_per_profile_units_restart_their_one_host_process_once(monkeypatch, capsys):
++ """Three units, one live main PID = one host gateway: restart it once and name the legacy units."""
++ restarted: list[str] = []
++ _patch_live_unit_restart(monkeypatch, restarted, lambda scope_cmd, svc: 4242)
++
++ settled: list = []
+ failed: list = []
- fleet._restart_systemd_gateway_units_best_effort(
- failed, _listing(["hermes-gateway.service", "hermes-gateway-coder.service", "hermes-gateway-writer.service"]))
++ scoped: set = set()
++ fleet._restart_systemd_gateway_units(settled, failed, scoped, 1.0)
+
+ assert restarted == ["hermes-gateway"]
++ assert settled == ["hermes-gateway"] and scoped == {"user/hermes-gateway"}
+ assert failed == []
+ out = capsys.readouterr().out
+ assert "hermes-gateway-coder" in out and "legacy per-profile unit" in out
+
+
+ def test_units_with_distinct_live_pids_are_each_restarted(monkeypatch):
+ """Control: genuinely separate processes are still separate restart targets."""
- pids = {"hermes-gateway": 1, "hermes-gateway-coder": 2}
- monkeypatch.setattr(fleet, "_unit_main_pid", lambda scope_cmd, svc: pids[svc], raising=False)
++ pids = {"hermes-gateway": 1, "hermes-gateway-coder": 2, "hermes-gateway-writer": 3}
+ restarted: list[str] = []
- monkeypatch.setattr(
- fleet, "_systemctl_reset_and_restart",
- lambda manage_cmd, svc, scope_cmd=None: restarted.append(svc) or SimpleNamespace(returncode=0))
- monkeypatch.setattr(fleet, "_wait_for_service_active", lambda scope_cmd, svc: True)
- monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", ["systemctl", "--user"]),))
++ _patch_live_unit_restart(monkeypatch, restarted, lambda scope_cmd, svc: pids[svc])
+
- fleet._restart_systemd_gateway_units_best_effort(
- [], _listing(["hermes-gateway.service", "hermes-gateway-coder.service"]))
++ fleet._restart_systemd_gateway_units([], [], set(), 1.0)
+
- assert sorted(restarted) == ["hermes-gateway", "hermes-gateway-coder"]
++ assert sorted(restarted) == sorted(pids)
+
+
+ def _host_record(tmp_path, monkeypatch, profiles: list[str]) -> None:
+ lock_dir = tmp_path / "gateway-locks"
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(lock_dir))
+ (lock_dir / "host-gateway.json").write_text(
+ json.dumps({"role": "gateway", "pid": os.getpid(), "profiles": profiles}), encoding="utf-8")
+
+
+ def test_recovery_restarts_one_host_process_for_all_the_profiles_it_serves(tmp_path, monkeypatch):
+ """N payload profiles served by ONE host gateway = one relaunch, not N that kill each other."""
+ _host_record(tmp_path, monkeypatch, ["coder", "writer", "default"])
+ argvs: list[list[str]] = []
+
+ def fake_run(argv, **kwargs):
+ argvs.append(list(argv))
+ return SimpleNamespace(returncode=0, stdout="")
+
+ result = recovery.restart_profiles(["coder", "writer", "default"], run=fake_run)
+
+ relaunches = [argv for argv in argvs if argv[-2:] == ["gateway", "restart"]]
+ assert len(relaunches) == 1, "one host process must be relaunched once for every profile it serves"
+ reported = [*result["verified"], *result["relaunch_attempted"], *result["failed"]]
+ assert sorted(reported) == ["coder", "default", "writer"], "every requested profile keeps an outcome"
+ assert result["covered"] == {"coder": ["default", "writer"]}
+
+
+ def test_recovery_keeps_separate_processes_separate(tmp_path, monkeypatch):
+ """Control: with no host record, each profile is its own restart target."""
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "empty-locks"))
+ argvs: list[list[str]] = []
+
+ def fake_run(argv, **kwargs):
+ argvs.append(list(argv))
+ return SimpleNamespace(returncode=0, stdout="")
+
+ recovery.restart_profiles(["coder", "writer"], run=fake_run)
+
+ assert len([argv for argv in argvs if argv[-2:] == ["gateway", "restart"]]) == 2
+
+
+ def test_host_obligation_lives_beside_the_host_rendezvous_record(two_profiles, monkeypatch, tmp_path):
+ """The record is written ONCE PER HOST, in the cross-profile rendezvous dir."""
+ _enter(monkeypatch, two_profiles["coder"])
+ _arm("coder")
+
+ path = host_obligation.host_obligation_path()
+ assert path == tmp_path / "gateway-locks" / "host-update-restart.json"
+ assert path.is_file()
+ assert not (two_profiles["coder"] / "fleet_restart_pending").exists()
+
+
+ @pytest.mark.skipif(getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores directory permissions")
+ def test_unwritable_host_state_dir_still_arms_the_obligation(two_profiles, no_live_fleet, monkeypatch, tmp_path):
+ """An unwritable host state dir must never silently disarm the update→restart obligation.
+
+ The host record moved out of ``$HERMES_HOME`` (writable by construction) into the host state
+ dir, which a read-only mount or a container UID mismatch can make unwritable. Losing the
+ obligation there is the #117275 outage shape: an interrupted update leaves stale code running
+ with no warning and no catch-up restart.
+ """
+ _enter(monkeypatch, two_profiles["coder"])
+ lock_dir = tmp_path / "gateway-locks"
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ lock_dir.chmod(0o500)
+ try:
+ _arm("coder")
+ assert not host_obligation.host_obligation_present(), "precondition: the record could not be written"
+ assert fleet._fleet_restart_obligation_armed() is True
+ assert fleet._pending_fleet_restart_needed() is True
+ finally:
+ lock_dir.chmod(0o700)
+
+
+ def test_unreadable_host_record_is_never_discharged_by_the_legacy_marker(two_profiles, no_live_fleet, monkeypatch, tmp_path):
+ """A record whose terms are UNKNOWN cannot be settled by another record's terms.
+
+ A foreign version (a NEWER CLI wrote it) or a corrupt record is fail-closed by contract; the
+ legacy per-home marker describes a different obligation and must not discharge it.
+ """
+ _enter(monkeypatch, two_profiles["coder"])
+ lock_dir = tmp_path / "gateway-locks"
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ (lock_dir / host_obligation.HOST_OBLIGATION_NAME).write_text(
+ json.dumps({"version": 99, "expected_sha": SHA}), encoding="utf-8")
+ fleet._fleet_restart_pending_marker_path().write_text(
+ f"started=1.0\npid=1\nexpected_sha={SHA}\n"
+ + "inventory=" + json.dumps({"version": 1, "runtimes": []}) + "\n",
+ encoding="utf-8",
+ )
+
+ assert fleet._obligation_fields() is None
+ assert fleet._pending_fleet_restart_needed() is True
+
+
-def test_restart_runs_once_per_host_on_a_non_git_install(two_profiles, monkeypatch, capsys):
- """zip/pip/Docker installs resolve no checkout SHA; the restart-once guard must still hold.
-
- ``mark_host_restart_completed("")`` can never match, so every profile's ``hermes update``
- re-killed the one shared multiplexer on exactly the installs this record exists for.
- """
- monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: None)
- monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda: [])
- monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda **k: [4242])
- monkeypatch.setattr("hermes_cli.gateway.supports_systemd_services", lambda: False)
- monkeypatch.setattr("hermes_cli.gateway.is_macos", lambda: False)
- monkeypatch.setattr("hermes_cli.gateway.is_windows", lambda: False)
- monkeypatch.setattr("hermes_cli.gateway._wait_for_gateway_exit", lambda **k: True)
- kills: list = []
- monkeypatch.setattr("hermes_cli.gateway.kill_gateway_processes", lambda **k: kills.append(k))
-
- _enter(monkeypatch, two_profiles["coder"])
- _arm("coder")
- assert update_cmd._run_pending_fleet_restart() is True
-
- _enter(monkeypatch, two_profiles["writer"])
- assert update_cmd._run_pending_fleet_restart() is True
-
- assert len(kills) == 1, "the host gateway must be stopped once per update, not once per profile"
- assert "already restarted for this update" in capsys.readouterr().out
-
-
+ def test_a_failing_main_pid_probe_keeps_its_own_restart():
+ """Any probe error is unproven identity (its own restart), never an aborted restart pass."""
+ def boom(unit):
+ raise RuntimeError("systemctl exploded")
+
+ restart, covered = host_obligation.collapse_units_to_host_processes(["a.service", "b.service"], boom)
+
+ assert restart == ["a.service", "b.service"]
+ assert covered == {}
+
+
+ @pytest.mark.parametrize("env", [
+ {"HERMES_GATEWAY_LOCK_DIR": "/srv/override/locks"},
+ {"XDG_STATE_HOME": "/srv/xdg-state"},
+ {"XDG_STATE_HOME": "relative/state"},
+ {},
+ ])
+ def test_recovery_host_state_dir_matches_the_gateway_resolver(monkeypatch, env):
+ """``update_restart_recovery`` re-implements the lock-dir rule (it may import no Hermes code
+ at runtime); the duplicate must not drift from ``gateway.status._get_lock_dir``."""
+ from gateway.status import _get_lock_dir
+
+ for name in ("HERMES_GATEWAY_LOCK_DIR", "XDG_STATE_HOME"):
+ monkeypatch.delenv(name, raising=False)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+
+ assert recovery._host_state_dir() == str(_get_lock_dir())
++
diff --cc tests/hermes_cli/test_update_scoped_reconciliation.py
index 6aee6f62c08,e6696dea268..32764bcb208
--- a/tests/hermes_cli/test_update_scoped_reconciliation.py
+++ b/tests/hermes_cli/test_update_scoped_reconciliation.py
@@@ -52,10 -53,11 +53,10 @@@ def test_scoped_reconciliation_matrix(m
assert fleet._pending_fleet_restart_needed() is pending
fleet._warn_pending_fleet_restart_on_startup()
assert ("hermes gateway restart" in capsys.readouterr().err) is pending
- # These unfinished receipts require the same evidence for startup and deferred catch-up.
- fleet._apply_pending_fleet_restart_catchup(defer=True)
- assert ("fleet restart deferred" in capsys.readouterr().out) is pending
+ # Deferred catch-up rides the ordinary completion owner under PM; the marker
+ # lifecycle is what the startup warning reflects here.
assert target.read_bytes() == before
- assert fleet._fleet_restart_pending_marker_path().exists() is (marker is not None and pending)
+ assert host_obligation.host_obligation_path().exists() is (marker is not None and pending)
if name == "missing-sibling":
live.append(dict(CURRENT, profile="beta"))
assert not fleet._pending_fleet_restart_needed()
@@@ -63,28 -65,89 +64,30 @@@
assert target.read_bytes() == before
- @pytest.mark.parametrize("suffix", ["inventory=not-json", "expected_sha=", "inventory={}", 'inventory=null\ninventory={"version":1,"runtimes":[]}', "broken-line"])
- def test_malformed_marker_stays_pending(monkeypatch, suffix):
[email protected]("alive", [True, False, None], ids=["alive", "dead", "unknown"])
[email protected]("sha", ["old", "new", None], ids=["different-sha", "same-sha", "no-sha"])
-def test_empty_marker_never_inherits_receipt_ownership(monkeypatch, capsys, alive, sha):
- old = {"outcome": "success", "plan": {"runtimes": [MANUAL]}, "post_update": {"sha": sha}}
- target = seed(monkeypatch, old, "new", [], alive)
- before = target.read_bytes()
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" in warning
- assert ("serve [work] pid 900" in warning) is (alive is not False)
- assert host_obligation.host_obligation_path().exists()
- assert target.read_bytes() == before
-
-
[email protected]("consumer", ["predicate", "startup"])
-def test_reconciliation_uses_one_receipt_snapshot(monkeypatch, capsys, consumer):
- old = {"outcome": "partial", "plan": {"runtimes": [MANUAL]}, "fleet": []}
- seed(monkeypatch, old, None, [])
- reads = []
-
- def read_rotating_receipt():
- reads.append(True)
- return old if len(reads) == 1 else {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
-
- monkeypatch.setattr(update_receipt, "read_latest_receipt", read_rotating_receipt)
- if consumer == "predicate":
- assert not fleet._pending_fleet_restart_needed()
- else:
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" not in warning
- assert "serve [work] pid 900" in warning
- assert len(reads) == 1
- assert list((get_hermes_home() / "serve_restart_pending").glob("*.json"))
-
-
[email protected]("marker", [None, "new"])
[email protected]("blocked_storage", [False, True])
-def test_probe_exception_does_not_hide_manual_warning(monkeypatch, capsys, marker, blocked_storage):
- old = {"outcome": "partial", "plan": {"runtimes": [GATEWAY, MANUAL]}}
- target = seed(monkeypatch, old, marker, [])
- if marker is not None:
- fleet._write_fleet_restart_pending_marker(expected_sha=marker, runtimes=[GATEWAY])
- before = target.read_bytes()
- if blocked_storage:
- (get_hermes_home() / "serve_restart_pending").write_text("not a directory")
[email protected]("suffix", ["{", '{"version": 1, "inventory": ', "broken-line"])
++def test_malformed_obligation_stays_pending(monkeypatch, suffix):
++ """An unparseable record is an obligation whose terms are unknown — never a discharged one."""
+ seed(monkeypatch, {}, "new", [CURRENT])
- marker = fleet._fleet_restart_pending_marker_path()
- with marker.open("a") as stream:
- stream.write(suffix + "\n")
++ marker = host_obligation.host_obligation_path()
++ marker.write_text(marker.read_text(encoding="utf-8") + suffix, encoding="utf-8")
+ assert fleet._pending_fleet_restart_needed()
+ assert marker.exists()
- def unavailable(**kwargs):
- raise OSError("gateway probe unavailable")
- monkeypatch.setattr(update_receipt, "collect_fleet_versions", unavailable)
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" in warning
- assert "serve [work] pid 900" in warning
- assert ("could not be saved" in warning) is blocked_storage
- assert target.read_bytes() == before
+def test_marker_reconciliation_collects_one_live_snapshot(monkeypatch):
+ seed(monkeypatch, {}, "new", [CURRENT])
+ fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY])
+ probes = []
+ def collect(**kwargs):
+ probes.append(True)
+ return [CURRENT] if len(probes) == 1 else []
[email protected]("completed_restart", [False, True])
-def test_new_marker_cannot_borrow_old_alpha_receipt(monkeypatch, capsys, completed_restart):
- """N owns alpha; N+1 owns alpha and beta but dies before writing its receipt."""
- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
- if completed_restart:
- old.update(post_update={"sha": "new"}, gateway_restart={"incomplete": False})
- live = [CURRENT]
- target = seed(monkeypatch, old, "new", live)
- marker = host_obligation.host_obligation_path()
- host_obligation.amend_host_obligation(inventory={"version": 1, "runtimes": [GATEWAY, dict(GATEWAY, profile="beta")]})
- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()
- fleet._warn_pending_fleet_restart_on_startup()
- assert "hermes gateway restart" in capsys.readouterr().err
- assert fleet._pending_fleet_restart_needed()
- fleet._apply_pending_fleet_restart_catchup(defer=True)
- assert "fleet restart deferred" in capsys.readouterr().out
- assert marker.read_bytes() == marker_before
- assert target.read_bytes() == receipt_before
- live.append(dict(CURRENT, profile="beta"))
+ monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)
assert not fleet._pending_fleet_restart_needed()
- assert not marker.exists()
- assert target.read_bytes() == receipt_before
+ assert len(probes) == 1
+
+
@pytest.mark.parametrize("completed_restart", [False, True])
def test_legacy_marker_discharges_on_live_fleet_evidence_without_receipt(monkeypatch, capsys, completed_restart):
"""An inventory-less N+1 marker settles on live-fleet evidence alone (#115638).