The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(update): remove the unused update-phase runner
ethernet48cae98cc15b
diff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.pyindex 6fc92eb3da8..cef870251fb 100644--- a/hermes_cli/post_update.py+++ b/hermes_cli/post_update.py@@ -13,18 +13,12 @@ Steps declare a scope:The scopes must match the record that gates them in ``boot_bootstrap``(home record vs machine record).--Ported from the restack branch's post_update module, rewritten onto this-branch's vocabulary: install identity via ``hermes_cli.steward`` (stamp +-.git), managed tools via ``pm`` (facts.json ledger) instead of the retired-``installation`` package."""from __future__ import annotationsimport loggingimport osimport shutil-import subprocessimport sysfrom datetime import datetime, timezonefrom pathlib import Path@@ -304,8 +298,8 @@ def step_report_runtime_drift() -> dict:ledger — no network, no installs. Drift is reported loudly (the sameverdict the CLI startup block prints) so the user knows to run``hermes pm install``; boot itself never installs anything. The- installing pass is MACHINE_STEPS below, owned by the explicit update- flow — automatic boot must not run network installers.+ installing pass is MACHINE_STEPS below, selected by the scope CLI.+ Automatic boot must not run network installers."""import pm@@ -509,23 +503,14 @@ HOME_STEPS: tuple = (("expose_cli", step_expose_cli),)-# What AUTOMATIC boot runs for the home scope: HOME_STEPS minus the-# bundled-skills sync — startup skill syncing already has exactly one-# owner per entrypoint (main.py's _sync_bundled_skills_for_startup for-# the CLI, gateway/run.py's configure-logging sync for the gateway), and-# `hermes update`'s explicit pass keeps the full HOME_STEPS. Adding the-# sync here made boot a third writer racing those two.+# Startup skill syncing belongs to each entry point. Boot bootstrap must+# not repeat it. The explicit scope CLI includes the skills step.BOOT_HOME_STEPS: tuple = tuple(step for step in HOME_STEPS if step[0] != "sync_skills")-# Machine steps may be slow (network installers); they run ONLY in the-# explicit update phase (``python -m hermes_cli.post_update --update-phase``,-# i.e. `hermes update`'s fresh-interpreter step pass) — never on automatic-# boot.-#-# There is no separate cua-driver refresh step: pinned managed tools ride-# provision_runtimes' pm sweep — one authority on every tool's version.+# Only the explicit scope CLI selects installing machine steps. Automatic+# boot uses the check-only registry below.MACHINE_STEPS: tuple = (("provision_runtimes", step_provision_runtimes),)@@ -556,122 +541,16 @@ def run_steps(steps: Iterable) -> dict:return results-def resync_and_reexec(args) -> int | None:- """Sync dependencies before a fresh-process handoff.-- ``venv_sync`` uses PM's recorded inputs and selected environment for- this checkout. The resumed flag prevents a second sync after handoff.- Return None to continue in this process, or an exit code to propagate.- POSIX replaces the process. Windows waits for a child and returns its code.- """- if args.resumed_after_sync:- return None-- from hermes_cli import venv_sync-- result = venv_sync.sync()- state = result.get("state")- if state == "failed":- print(f" ✗ venv sync failed: {result.get('detail')}")- return 1- if state in ("sealed", "current"):- # Nothing changed under us — this interpreter is as good as a- # fresh one, and an exec would only cost startup time.- return None-- print(" ✓ venv synced — handing off to a fresh interpreter")- argv = [sys.executable, "-m", "hermes_cli.post_update", "--update-phase",- "--resumed-after-sync"]- if args.gateway_mode:- argv.append("--gateway-mode")- if args.assume_yes:- argv.append("--assume-yes")- if args.pre_update_snapshot_id:- argv.extend(["--pre-update-snapshot-id", str(args.pre_update_snapshot_id)])-- if os.name == "posix":- sys.stdout.flush()- sys.stderr.flush()- os.execv(sys.executable, argv)- # unreachable: execv only returns by raising-- completed = subprocess.run(argv)- return completed.returncode---def _run_update_phase(args) -> int:- """Phase 2: the full post-update step list in a fresh interpreter,- then record the new identity so the next boot's bootstrap skips.-- ``hermes update`` and boot bootstrap share ONE registry: this runner- executes exactly HOME_STEPS + MACHINE_STEPS (machine steps inline —- an update invocation is interactive, deferring would hide failures),- and writes both boot records via ``boot_bootstrap.write_record``.-- TODO(update-collapse): route hermes_cli.update_cmd's inline- post-update phase through ``python -m hermes_cli.post_update- --update-phase`` (spawn with inherited stdio) so the updater stops- reloading modules by hand. The restack branch delegated to- ``update_cmd._run_update_phase_inline`` here; that helper does not- exist on this branch yet, so the shared-registry runner IS the- update phase for now.- """- from hermes_cli import boot_bootstrap-- steps = (*HOME_STEPS, *MACHINE_STEPS)- results = run_steps(steps)- failed = [name for name, res in results.items() if not res.get("ok")]- for name, res in results.items():- state = "ok" if res.get("ok") else f"FAILED ({res.get('error')})"- skipped = res.get("skipped")- print(f" post-update {name}: {f'skipped ({skipped})' if skipped else state}")-- root = boot_bootstrap.default_project_root()- identity = boot_bootstrap.current_install_identity(root)- if identity:- try:- boot_bootstrap.write_record(root, "home", identity, results)- boot_bootstrap.write_record(root, "machine", identity, results)- except OSError as exc:- logger.warning("could not record post-update identity: %s", exc)- return 1 if failed else 0--def main(argv: list | None = None) -> int:- """``python -m hermes_cli.post_update`` — run in a FRESH interpreter- so every step imports post-pull code (no reload lists).-- Two modes:-- * default / ``--scope``: the boot-bootstrap step registries.- * ``--update-phase``: phase 1 (``resync_and_reexec``) syncs the venv- and re-execs, so phase 2 (the full step list + boot-record write)- always runs on the synced world.- """+ """Run the selected maintenance registry and report its failures."""import argparseparser = argparse.ArgumentParser(prog="hermes_cli.post_update")parser.add_argument("--scope", choices=("home", "machine", "all"), default="all")- parser.add_argument("--update-phase", action="store_true")- parser.add_argument("--gateway-mode", action="store_true")- parser.add_argument("--assume-yes", action="store_true")- parser.add_argument("--pre-update-snapshot-id", default=None)- parser.add_argument("--pre-update-version", default=None)- parser.add_argument(- "--resumed-after-sync",- action="store_true",- help="internal: this process IS the post-sync interpreter; never sync again",- )args = parser.parse_args(argv)logging.basicConfig(level=logging.INFO, format="%(message)s")- if args.update_phase:- handoff = resync_and_reexec(args)- if handoff is not None:- return handoff- return _run_update_phase(args)-selected: list = []if args.scope in ("home", "all"):selected.extend(HOME_STEPS)diff --git a/tests/compat/old_updater_surface.json b/tests/compat/old_updater_surface.jsonindex 6d784c180cf..44540ff72c6 100644--- a/tests/compat/old_updater_surface.json+++ b/tests/compat/old_updater_surface.json@@ -185,11 +185,9 @@"hermes_cli.update_receipt::read_latest_receipt","hermes_cli.update_receipt::record_gateway_restart","hermes_cli.update_receipt::record_step",- "hermes_cli::boot_bootstrap","hermes_cli::gateway_windows","hermes_cli::main","hermes_cli::runtime_paths",- "hermes_cli::venv_sync","hermes_constants::","hermes_constants::FIRST_PARTY_MODULE_ROOTS","hermes_constants::display_hermes_home",diff --git a/tests/hermes_cli/test_post_update.py b/tests/hermes_cli/test_post_update.pyindex b49f33c6d92..ff8e6b49ad7 100644--- a/tests/hermes_cli/test_post_update.py+++ b/tests/hermes_cli/test_post_update.py@@ -5,7 +5,6 @@ match what boot_bootstrap gates them with, a failing step must not stop therest, and step_migrate_config must restore its backups when a migrationfails or does not advance the version."""-import jsonfrom pathlib import Pathimport pytest@@ -238,175 +237,19 @@ def test_main_scope_selects_registries(monkeypatch):assert ran == ["h", "m"]-# ── --update-phase runner mode ───────────────────────────────────────---def test_update_phase_runs_shared_registry_and_writes_boot_records(- tmp_path, monkeypatch-):- """`hermes update` and boot bootstrap share ONE registry: the update- phase runs HOME_STEPS + MACHINE_STEPS and records the new identity so- the next boot's bootstrap skips."""- from hermes_cli import boot_bootstrap-- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))-- root = tmp_path / "payload"- root.mkdir()- (root / "install-stamp.json").write_text(- json.dumps({"commit": "cafe1234", "payload": "full", "updateMechanism": "electron-updater"})- )- monkeypatch.setattr(boot_bootstrap, "default_project_root", lambda: root)-+def test_scope_cli_rejects_unrelated_flags_without_running_steps(monkeypatch):ran = []- monkeypatch.setattr(- post_update, "HOME_STEPS", (("h", lambda: ran.append("h") or {"ok": True}),)- )- monkeypatch.setattr(- post_update, "MACHINE_STEPS", (("m", lambda: ran.append("m") or {"ok": True}),)- )-- rc = post_update.main(["--update-phase", "--resumed-after-sync"])-- assert rc == 0- assert ran == ["h", "m"] # machine steps inline in an update, not deferred- for scope in ("home", "machine"):- record = boot_bootstrap.read_last_known(- boot_bootstrap.record_path(root, scope)- )- assert record.get("identity") == "cafe1234"- assert boot_bootstrap.needs_bootstrap(root, scope) is None---def test_update_phase_propagates_step_failure(tmp_path, monkeypatch):- from hermes_cli import boot_bootstrap-- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- root = tmp_path / "payload"- root.mkdir()- (root / "install-stamp.json").write_text(- json.dumps({"commit": "cafe1234", "payload": "full", "updateMechanism": "electron-updater"})- )- monkeypatch.setattr(boot_bootstrap, "default_project_root", lambda: root)- monkeypatch.setattr(- post_update, "HOME_STEPS",- (("bad", lambda: (_ for _ in ()).throw(RuntimeError("x"))),),- )- monkeypatch.setattr(post_update, "MACHINE_STEPS", ())-- assert post_update.main(["--update-phase", "--resumed-after-sync"]) == 1- # The record is still written: a broken step must not retrigger the- # slow path every boot (the steps re-gate themselves).- assert boot_bootstrap.needs_bootstrap(root, "home") is None---# ── the re-exec-after-sync handoff ───────────────────────────────────---class _Args:- """The argparse surface resync_and_reexec consumes."""-- def __init__(self, resumed=False, gateway=False, yes=False, snap=None):- self.resumed_after_sync = resumed- self.gateway_mode = gateway- self.assume_yes = yes- self.pre_update_snapshot_id = snap---class TestResyncAndReexec:- def test_the_resumed_flag_is_absolute(self, monkeypatch):- """Loop-proofing: the post-sync process must never sync again,- even when the stamp looks stale (another writer could move it- between exec and check — argv cannot race)."""-- def no_sync(*a, **k):- raise AssertionError("--resumed-after-sync must not sync")-- from hermes_cli import venv_sync-- monkeypatch.setattr(venv_sync, "sync", no_sync)-- assert post_update.resync_and_reexec(_Args(resumed=True)) is None-- def test_current_and_sealed_run_phase2_in_place(self, monkeypatch):- """No world change, no exec: the running interpreter is as good- as a fresh one and the exec would only cost startup."""- from hermes_cli import venv_sync-- for state in ("current", "sealed"):- monkeypatch.setattr(- venv_sync, "sync", lambda *a, s=state, **k: {"state": s, "ok": True}- )- monkeypatch.setattr(- post_update.os, "execv",- lambda *a: (_ for _ in ()).throw(AssertionError("must not exec")),- raising=False,- )- assert post_update.resync_and_reexec(_Args()) is None-- def test_a_failed_sync_stops_the_phase(self, monkeypatch):- from hermes_cli import venv_sync-- monkeypatch.setattr(- venv_sync,- "sync",- lambda *a, **k: {"state": "failed", "ok": False, "detail": "uv exited 3"},- )-- assert post_update.resync_and_reexec(_Args()) == 1-- def test_a_synced_world_reexecs_with_carried_args(self, monkeypatch):- """POSIX: os.execv, same pid, update-lock owner stays correct.- Every serialized arg must survive the handoff, plus the resumed- marker."""- from hermes_cli import venv_sync-- monkeypatch.setattr(- venv_sync, "sync", lambda *a, **k: {"state": "synced", "ok": True}- )- seen = {}-- def fake_execv(exe, argv):- seen["exe"] = exe- seen["argv"] = argv- raise SystemExit(0) # execv never returns; simulate the replacement-- monkeypatch.setattr(post_update.os, "execv", fake_execv, raising=False)- monkeypatch.setattr(post_update.os, "name", "posix")-- with pytest.raises(SystemExit):- post_update.resync_and_reexec(- _Args(gateway=True, yes=True, snap="snap-7")- )-- argv = seen["argv"]- assert seen["exe"] == post_update.sys.executable- assert argv[1:4] == ["-m", "hermes_cli.post_update", "--update-phase"]- assert "--resumed-after-sync" in argv- assert "--gateway-mode" in argv and "--assume-yes" in argv- assert argv[argv.index("--pre-update-snapshot-id") + 1] == "snap-7"-- def test_windows_spawns_and_propagates(self, monkeypatch):- """No exec on Windows: spawn + wait + propagate the child's code;- the child passes any update lock by ancestry."""- from hermes_cli import venv_sync-- monkeypatch.setattr(- venv_sync, "sync", lambda *a, **k: {"state": "synced", "ok": True}- )- monkeypatch.setattr(post_update.os, "name", "nt")- seen = {}-- class _Done:- returncode = 7-- def fake_run(argv, **kwargs):- seen["argv"] = argv- return _Done()-- monkeypatch.setattr(post_update.subprocess, "run", fake_run)-- assert post_update.resync_and_reexec(_Args()) == 7- assert "--resumed-after-sync" in seen["argv"]+ monkeypatch.setattr(post_update, "HOME_STEPS", (("home", lambda: ran.append("home") or {"ok": True}),))+ monkeypatch.setattr(post_update, "MACHINE_STEPS", (("machine", lambda: ran.append("machine") or {"ok": True}),))+ for flags in (+ ["--gateway-mode"],+ ["--assume-yes"],+ ["--pre-update-snapshot-id", "fixture"],+ ["--pre-update-version", "fixture"],+ ["--resumed-after-sync"],+ ["--update-phase", "--resumed-after-sync"],+ ):+ with pytest.raises(SystemExit) as exc:+ post_update.main(flags)+ assert exc.value.code == 2+ assert ran == []