feat(update): hermes update --plan — read-only fleet inventory + plan phase in every update

Phase 2 core slice of #91277: the updater now knows WHAT it is operating
on before it mutates anything.

- hermes_cli/update_inventory.py (new): side-effect-free runtime
  inventory — install kind via detect_install_method (git / docker / nix
  / apt, updatable-in-place or not, with the correct external update
  command for image/package-managed installs), all profiles, every live
  gateway with its supervisor (systemd / launchd / manual via the
  fleet-wide _get_service_pids), running code_sha/code_version from the
  #91283 gateway_state.json stamps, and the restart mechanism each
  runtime will get.
- hermes update --plan: prints the plan and exits; runs BEFORE the
  docker/nix refusal gates so image-managed installs get a useful
  'not updatable in place + right command' report instead of a bare
  refusal. Read-only, safe on a live fleet.
- Every real update run now records the pre-update plan in its receipt
  ('plan' key) and prints a one-line fleet summary, so post-mortems can
  compare what the update SAW against what it did.
- Docs: updating.md (--plan section + receipts/fleet-check section),
  cli-commands.md (flag row + receipts behavior bullet).
- 11 tests: two-profile fleet classification, docker not-in-place,
  dead-PID exclusion, PID-file fallback dedupe, all-probes-fail
  never-raises, JSON round-trip for the receipt, print output shapes,
  receipt integration.
This commit is contained in:
Teknium
2026-08-21 04:06:16 -07:00
parent d47252547b
commit 0aecadc17c
7 changed files with 506 additions and 1 deletions
+16
View File
@@ -10079,6 +10079,22 @@ def cmd_update(args):
managed_error("update Hermes Agent")
return
# --plan is read-only and deployment-kind aware, so it runs BEFORE the
# docker/nix/apt refusal gates: on an image-managed or package-managed
# install the plan itself reports "not updatable in place" plus the
# right mechanism — strictly more useful than the bare refusal text.
if getattr(args, "plan", False):
# Read-only plan phase (#91277 Phase 2): inventory every running
# Hermes runtime across profiles, its supervisor, and its running
# code version — without mutating anything. Safe on a live fleet.
from hermes_cli.update_inventory import (
collect_runtime_inventory,
print_update_plan,
)
print_update_plan(collect_runtime_inventory())
return
# Docker users can't ``git pull`` — the image excludes ``.git`` from
# the build context. Bail with a friendly explanation pointing at
# ``docker pull`` BEFORE any of the apply-path / check-path branches
+11
View File
@@ -31,6 +31,17 @@ def build_update_parser(subparsers, *, cmd_update: Callable) -> None:
default=False,
help="Check whether an update is available without installing anything",
)
update_parser.add_argument(
"--plan",
action="store_true",
default=False,
help=(
"Show the update plan and exit without changing anything: install "
"kind (git/docker/nix), every running Hermes service across all "
"profiles with its supervisor and running code version, and how "
"each will be restarted. Read-only; safe on a live fleet."
),
)
update_parser.add_argument(
"--no-backup",
action="store_true",
+21
View File
@@ -5133,6 +5133,27 @@ def _cmd_update_impl(args, gateway_mode: bool):
except Exception as _receipt_exc:
logger.debug("Update receipt unavailable: %s", _receipt_exc)
# Plan phase (#91277 Phase 2): snapshot the pre-update fleet — every
# running Hermes runtime, its supervisor, and its running code version —
# into the receipt, so a post-mortem can compare what the update SAW
# against what it did. Read-only; a probe failure records nothing.
try:
from hermes_cli.update_inventory import (
collect_runtime_inventory,
record_plan_in_receipt,
)
_pre_update_plan = collect_runtime_inventory()
record_plan_in_receipt(_pre_update_plan)
if _pre_update_plan.runtimes:
_n = len(_pre_update_plan.runtimes)
_profiles = ", ".join(
sorted({r.profile for r in _pre_update_plan.runtimes})
)
print(f"→ Fleet: {_n} running service(s) across profiles: {_profiles}")
except Exception as _plan_exc:
logger.debug("Update plan phase failed: %s", _plan_exc)
# On Windows, abort early if another hermes.exe is holding the venv shim
# open. Continuing would result in a string of WinError 32 warnings and
# then either a deferred-rename leftover or a failed git-pull fast path
+274
View File
@@ -0,0 +1,274 @@
"""Runtime inventory + update plan for the fleet-update pipeline (#91277 Phase 2).
One read-only pass that answers, BEFORE any mutation: what Hermes runtimes
are running on this machine, how is each one deployed, which of them will
this update touch, and how will each be restarted?
This is the "plan" phase of the transactional deployment model (#88683):
plan → snapshot → apply → restart-per-kind → verify → report
The module is deliberately side-effect free — every collector is a probe
over primitives that already exist (`find_profile_gateway_processes`,
`_get_service_pids`, `gateway_state.json` code stamps from #91283,
`detect_install_method`) — so `hermes update --plan` can run on a live
fleet with zero risk, and the update receipt can embed the inventory
without changing update behavior.
Deployment kinds (the concept most fleet-update bugs were missing):
git — source checkout; updatable in place via `hermes update`
docker — published image; NOT updatable in place (pull + recreate)
nix/apt — package-manager owned; updatable via the manager only
unknown — no marker; treated as in-place updatable (legacy default)
Supervisors (how a runtime is restarted after code changes):
systemd / launchd — restart via the service manager (fleet-wide)
desktop — Desktop app supervises `hermes serve`; it respawns
manual — plain process; SIGTERM + watcher/manual relaunch
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Any, Optional
logger = logging.getLogger(__name__)
@dataclass
class RuntimeRecord:
"""One running (or expected) Hermes runtime on this machine."""
kind: str # gateway | dashboard | serve
profile: str # profile name ("default", ...)
pid: Optional[int] = None # live PID when known
supervisor: str = "manual" # systemd | launchd | desktop | manual
code_sha: Optional[str] = None # stamped running-code sha (#91283)
code_version: Optional[str] = None
restart_via: str = "" # human-readable restart mechanism
detail: dict = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass
class UpdatePlan:
"""The full pre-update picture: install shape + runtimes + actions."""
install_method: str = "unknown" # git | docker | nix | apt | ...
updatable_in_place: bool = True
update_mechanism: str = "hermes update"
expected_sha: Optional[str] = None # current checkout HEAD (pre-pull)
expected_version: Optional[str] = None
profiles: list = field(default_factory=list)
runtimes: list = field(default_factory=list) # list[RuntimeRecord]
def to_dict(self) -> dict[str, Any]:
payload = asdict(self)
payload["runtimes"] = [
r.to_dict() if isinstance(r, RuntimeRecord) else r
for r in self.runtimes
]
return payload
def _detect_supervisor_for_pid(pid: int, service_pids: set) -> str:
"""Classify how a live gateway PID is supervised."""
if pid in service_pids:
try:
from hermes_cli.gateway import is_macos, supports_systemd_services
if supports_systemd_services():
return "systemd"
if is_macos():
return "launchd"
except Exception:
pass
return "service"
return "manual"
def _restart_mechanism(supervisor: str, profile: str) -> str:
if supervisor == "systemd":
return "systemctl restart (drain-first SIGUSR1 when supported)"
if supervisor == "launchd":
return "launchctl kickstart -k (drain-first, per-label domain)"
if supervisor == "desktop":
return "Desktop app respawns its serve backend"
if profile != "default":
return f"hermes -p {profile} gateway restart"
return "hermes gateway restart"
def collect_runtime_inventory() -> UpdatePlan:
"""Build the pre-update plan. Read-only; never raises.
Every collector degrades independently — a probe failure yields fewer
rows, not an exception. The result is embeddable in the update receipt
and printable via :func:`print_update_plan`.
"""
plan = UpdatePlan()
# --- install shape / deployment kind ---------------------------------
try:
from hermes_cli.config import (
detect_install_method,
get_managed_system,
recommended_update_command_for_method,
)
method = detect_install_method()
plan.install_method = method
managed = get_managed_system()
if managed:
plan.install_method = managed
plan.updatable_in_place = method in ("git", "unknown") and not managed
plan.update_mechanism = recommended_update_command_for_method(method)
except Exception as exc:
logger.debug("Install-method probe failed: %s", exc)
# --- expected code identity (pre-pull) --------------------------------
try:
from hermes_cli.build_info import get_code_identity
identity = get_code_identity(refresh=True)
plan.expected_sha = identity.get("sha")
plan.expected_version = identity.get("version")
except Exception as exc:
logger.debug("Code-identity probe failed: %s", exc)
# --- profiles ----------------------------------------------------------
profile_homes: list[tuple[str, Path]] = []
try:
from hermes_cli.profiles import (
_get_default_hermes_home,
_get_profiles_root,
_PROFILE_ID_RE,
)
default_home = _get_default_hermes_home()
if default_home.is_dir():
profile_homes.append(("default", default_home))
root = _get_profiles_root()
if root.is_dir():
for entry in sorted(root.iterdir()):
if (
entry.is_dir()
and entry.name != "default"
and _PROFILE_ID_RE.match(entry.name)
):
profile_homes.append((entry.name, entry))
plan.profiles = [name for name, _ in profile_homes]
except Exception as exc:
logger.debug("Profile enumeration failed: %s", exc)
# --- service-managed PIDs (fleet-wide) ---------------------------------
service_pids: set = set()
try:
from hermes_cli.gateway import _get_service_pids
service_pids = _get_service_pids(all_profiles=True) or set()
except Exception as exc:
logger.debug("Service-PID probe failed: %s", exc)
# --- per-profile gateways (PID files + runtime status stamps) ----------
seen_pids: set[int] = set()
try:
from gateway.status import _pid_exists, read_runtime_status
for profile, home in profile_homes:
record = read_runtime_status(home / "gateway_state.json")
pid: Optional[int] = None
code_sha = code_version = None
if record:
try:
pid = int(record.get("pid"))
except (TypeError, ValueError):
pid = None
code_sha = record.get("code_sha")
code_version = record.get("code_version")
if pid is None or not _pid_exists(pid):
continue
seen_pids.add(pid)
supervisor = _detect_supervisor_for_pid(pid, service_pids)
plan.runtimes.append(
RuntimeRecord(
kind="gateway",
profile=profile,
pid=pid,
supervisor=supervisor,
code_sha=str(code_sha) if code_sha else None,
code_version=code_version,
restart_via=_restart_mechanism(supervisor, profile),
)
)
except Exception as exc:
logger.debug("Gateway-state inventory failed: %s", exc)
# PID-file mapped gateways not covered by a runtime-status record
try:
from hermes_cli.gateway import find_profile_gateway_processes
for proc in find_profile_gateway_processes():
if proc.pid in seen_pids:
continue
seen_pids.add(proc.pid)
supervisor = _detect_supervisor_for_pid(proc.pid, service_pids)
plan.runtimes.append(
RuntimeRecord(
kind="gateway",
profile=proc.profile,
pid=proc.pid,
supervisor=supervisor,
restart_via=_restart_mechanism(supervisor, proc.profile),
)
)
except Exception as exc:
logger.debug("PID-file gateway inventory failed: %s", exc)
return plan
def print_update_plan(plan: UpdatePlan) -> None:
"""Human-readable plan — what the update will touch and how."""
print("Update plan:")
print(f" Install: {plan.install_method}", end="")
if plan.expected_version:
print(f" (v{plan.expected_version}", end="")
if plan.expected_sha:
print(f" @ {plan.expected_sha[:8]}", end="")
print(")", end="")
print()
if not plan.updatable_in_place:
print(" ⚠ This install is NOT updatable in place.")
print(f" Update via: {plan.update_mechanism}")
profiles = ", ".join(plan.profiles) if plan.profiles else "(none found)"
print(f" Profiles: {profiles}")
if not plan.runtimes:
print(" Running Hermes services: none detected — code swap only.")
return
print(f" Running services to restart ({len(plan.runtimes)}):")
for runtime in plan.runtimes:
sha = f" @ {runtime.code_sha[:8]}" if runtime.code_sha else ""
print(
f" • {runtime.kind} [{runtime.profile}] pid {runtime.pid}"
f" — {runtime.supervisor}{sha}"
)
print(f" restart: {runtime.restart_via}")
def record_plan_in_receipt(plan: UpdatePlan) -> None:
"""Attach the inventory to the active update receipt. Never raises."""
try:
import hermes_cli.update_receipt as ur
if ur._current is not None:
ur._current.data["plan"] = plan.to_dict()
except Exception as exc:
logger.debug("Could not record plan in receipt: %s", exc)
+171
View File
@@ -0,0 +1,171 @@
"""Tests for hermes_cli.update_inventory — the plan phase (#91277 Phase 2)."""
import json
from pathlib import Path
import pytest
import hermes_cli.update_inventory as ui
def _write_state(home: Path, pid: int, sha: str | None = None, version: str | None = None):
record = {"pid": pid}
if sha:
record["code_sha"] = sha
if version:
record["code_version"] = version
(home / "gateway_state.json").write_text(json.dumps(record), encoding="utf-8")
@pytest.fixture()
def fleet(monkeypatch, tmp_path):
"""Two profiles with live gateways: default (systemd) + work (manual)."""
default_home = tmp_path / "home"
work_home = tmp_path / "home" / "profiles" / "work"
work_home.mkdir(parents=True)
_write_state(default_home, 100, sha="a" * 40, version="1.0")
_write_state(work_home, 200) # pre-stamp gateway: no code identity
import re
monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: default_home)
monkeypatch.setattr("hermes_cli.profiles._get_profiles_root", lambda: default_home / "profiles")
monkeypatch.setattr("hermes_cli.profiles._PROFILE_ID_RE", re.compile(r"^[a-z0-9][a-z0-9_-]*$"), raising=False)
monkeypatch.setattr("gateway.status._pid_exists", lambda pid: pid in (100, 200))
monkeypatch.setattr("hermes_cli.gateway._get_service_pids", lambda all_profiles=False: {100})
monkeypatch.setattr("hermes_cli.gateway.supports_systemd_services", lambda: True)
monkeypatch.setattr("hermes_cli.gateway.find_profile_gateway_processes", lambda exclude_pids=None: [])
monkeypatch.setattr(
"hermes_cli.build_info.get_code_identity",
lambda refresh=False: {"sha": "a" * 40, "short_sha": "a" * 8, "version": "1.0", "source": "git"},
)
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda *a, **k: "git")
monkeypatch.setattr("hermes_cli.config.get_managed_system", lambda: None)
return tmp_path
class TestCollectInventory:
def test_two_profile_fleet(self, fleet):
plan = ui.collect_runtime_inventory()
assert plan.install_method == "git"
assert plan.updatable_in_place is True
assert plan.expected_sha == "a" * 40
assert plan.profiles == ["default", "work"]
assert len(plan.runtimes) == 2
by_profile = {r.profile: r for r in plan.runtimes}
assert by_profile["default"].pid == 100
assert by_profile["default"].supervisor == "systemd"
assert by_profile["default"].code_sha == "a" * 40
assert by_profile["work"].pid == 200
assert by_profile["work"].supervisor == "manual"
assert by_profile["work"].code_sha is None # pre-stamp gateway
assert "hermes -p work gateway restart" in by_profile["work"].restart_via
def test_docker_install_not_updatable_in_place(self, fleet, monkeypatch):
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda *a, **k: "docker")
monkeypatch.setattr(
"hermes_cli.config.recommended_update_command_for_method",
lambda m: "docker pull nousresearch/hermes-agent:latest",
)
plan = ui.collect_runtime_inventory()
assert plan.install_method == "docker"
assert plan.updatable_in_place is False
assert "docker pull" in plan.update_mechanism
def test_dead_pids_excluded(self, fleet, monkeypatch):
monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
plan = ui.collect_runtime_inventory()
assert plan.runtimes == []
def test_pid_file_fallback_covers_unstamped_profiles(self, fleet, monkeypatch):
"""Gateways with a PID file but no runtime-status record still appear."""
from hermes_cli.gateway import ProfileGatewayProcess
monkeypatch.setattr(
"hermes_cli.gateway.find_profile_gateway_processes",
lambda exclude_pids=None: [
ProfileGatewayProcess(profile="legacy", path=Path("/x"), pid=300),
# duplicate of an already-seen pid — must be deduped
ProfileGatewayProcess(profile="default", path=Path("/y"), pid=100),
],
)
monkeypatch.setattr("gateway.status._pid_exists", lambda pid: pid in (100, 200))
plan = ui.collect_runtime_inventory()
profiles = [r.profile for r in plan.runtimes]
assert profiles.count("default") == 1 # deduped by pid
assert "legacy" in profiles
def test_never_raises_when_everything_fails(self, monkeypatch):
def _boom(*a, **k):
raise RuntimeError("probe down")
for target in (
"hermes_cli.config.detect_install_method",
"hermes_cli.build_info.get_code_identity",
"hermes_cli.profiles._get_default_hermes_home",
"hermes_cli.gateway._get_service_pids",
"hermes_cli.gateway.find_profile_gateway_processes",
):
monkeypatch.setattr(target, _boom)
plan = ui.collect_runtime_inventory()
assert plan.runtimes == []
assert plan.install_method == "unknown"
def test_plan_serializes_for_receipt(self, fleet):
plan = ui.collect_runtime_inventory()
payload = plan.to_dict()
# must be JSON-clean for the receipt
text = json.dumps(payload)
restored = json.loads(text)
assert restored["install_method"] == "git"
assert len(restored["runtimes"]) == 2
assert restored["runtimes"][0]["kind"] == "gateway"
class TestPrintPlan:
def test_git_fleet_output(self, fleet, capsys):
ui.print_update_plan(ui.collect_runtime_inventory())
out = capsys.readouterr().out
assert "Update plan:" in out
assert "Install: git" in out
assert "default, work" in out
assert "pid 100" in out and "systemd" in out
assert "pid 200" in out and "manual" in out
def test_docker_warns_not_in_place(self, fleet, monkeypatch, capsys):
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda *a, **k: "docker")
monkeypatch.setattr(
"hermes_cli.config.recommended_update_command_for_method",
lambda m: "docker pull nousresearch/hermes-agent:latest",
)
ui.print_update_plan(ui.collect_runtime_inventory())
out = capsys.readouterr().out
assert "NOT updatable in place" in out
assert "docker pull" in out
def test_empty_fleet_message(self, fleet, monkeypatch, capsys):
monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
ui.print_update_plan(ui.collect_runtime_inventory())
assert "none detected" in capsys.readouterr().out
class TestReceiptIntegration:
def test_plan_recorded_into_active_receipt(self, fleet, monkeypatch, tmp_path):
import hermes_cli.update_receipt as ur
home = tmp_path / "receipt_home"
home.mkdir()
monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: home, raising=False)
ur._current = None
ur.begin_update_receipt()
plan = ui.collect_runtime_inventory()
ui.record_plan_in_receipt(plan)
path = ur.finalize_update_receipt("success")
payload = json.loads(path.read_text(encoding="utf-8"))
assert payload["plan"]["install_method"] == "git"
assert len(payload["plan"]["runtimes"]) == 2
def test_noop_without_active_receipt(self, fleet):
import hermes_cli.update_receipt as ur
ur._current = None
ui.record_plan_in_receipt(ui.collect_runtime_inventory()) # must not raise
+10
View File
@@ -80,6 +80,16 @@ You can pass `--keep-stash` to a terminal `hermes update` too if you want the sa
Want to know if an update is available before pulling? Run `hermes update --check` — it fetches and compares commits against `origin/main`. No files are modified, no gateway is restarted. Useful in scripts and cron jobs that gate on "is there an update".
### Fleet preview: `hermes update --plan`
Before updating a machine that runs several profiles or services, `hermes update --plan` prints the full update plan without changing anything: the install kind (git checkout, Docker image, Nix/apt managed), every running Hermes service across all profiles with its supervisor (systemd, launchd, manual) and the code version it is actually serving, and the restart mechanism each one will get. On image- or package-managed installs the plan reports that the install is not updatable in place and names the right update command instead. Read-only and safe on a live fleet.
The same inventory is embedded in every real update's receipt (`~/.hermes/logs/update_receipts/`), so after an update you can compare what the updater saw against what it did.
### Update receipts and the fleet version check
Every `hermes update` run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/` (last 20 kept, `latest.json` always points at the most recent): the pre-update fleet plan, each step taken, anything skipped and why, the gateway restart outcome, and the final fleet version matrix. After the restart phase the updater compares each live gateway's running code against the freshly updated checkout and prints a per-profile matrix — a gateway still serving pre-update code is reported loudly with the exact restart command, and the update exits non-zero so automation never treats a mixed-version fleet as healthy.
### Full pre-update backup: `--backup`
For high-value profiles (production gateways, shared team installs) you can opt into a full pre-pull backup of `HERMES_HOME` (config, auth, sessions, skills, pairing):
+3 -1
View File
@@ -1730,7 +1730,7 @@ hermes completion fish > ~/.config/fish/completions/hermes.fish
## `hermes update`
```bash
hermes update [--gateway] [--check] [--no-backup] [--backup] [--yes]
hermes update [--gateway] [--check] [--plan] [--no-backup] [--backup] [--yes]
```
Pulls the latest `hermes-agent` code and reinstalls dependencies in the managed venv, then re-runs the post-install hooks (MCP servers, skills sync, completion install). Safe to run on a live install. Use `--check` to see whether your checkout is behind `origin/main` without installing.
@@ -1741,6 +1741,7 @@ Pulls the latest `hermes-agent` code and reinstalls dependencies in the managed
|--------|-------------|
| `--gateway` | Internal mode used by the messaging `/update` command. Uses file-based IPC for prompts and progress streaming instead of reading from terminal stdin. Not a gateway restart flag. |
| `--check` | Check whether an update is available without pulling, installing dependencies, or restarting anything. |
| `--plan` | Print the update plan and exit without changing anything: install kind (git/Docker/Nix/apt), every running Hermes service across all profiles with its supervisor and running code version, and how each will be restarted. On image- or package-managed installs, reports the correct external update command instead. Read-only. |
| `--no-backup` | Skip all pre-update backups for this run (both the quick state snapshot and the full zip), regardless of `updates.pre_update_backup`. |
| `--backup` | Force a **full** pre-update backup for this run: the quick state snapshot plus a complete zip of `HERMES_HOME` (config, auth, sessions, skills, pairing data). The default mode is `quick` — a lightweight state snapshot only. Set the permanent mode via `updates.pre_update_backup: quick | full | off` in `config.yaml`. |
| `--yes`, `-y` | Assume yes for interactive prompts such as config migration and stash restore. API-key entry is skipped; run `hermes config migrate` separately for those. |
@@ -1748,6 +1749,7 @@ Pulls the latest `hermes-agent` code and reinstalls dependencies in the managed
Additional behavior:
- **Gateway restart.** After a successful update, Hermes attempts to restart all running gateway profiles automatically so they pick up the new code. Use `hermes gateway restart` when you want to restart a gateway without applying an update.
- **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.
- **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.