Skip to content

The agent that grows with you

Verify update selection through the fresh-completion handoff

ethernet977037bc15e2
diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.py
index 2fd9623e1ec..d6d9091a721 100644
--- a/tests/hermes_cli/test_update_head_moved_gate.py
+++ b/tests/hermes_cli/test_update_head_moved_gate.py
@@ -11,14 +11,13 @@ and fails loudly when the update was a no-op.
from types import SimpleNamespace
-import os
+from copy import deepcopy
import pytest
from hermes_cli import main as hermes_main
-import hermes_cli.main_web_build as main_web_build
-import hermes_cli.main_install_repair as main_install_repair
from hermes_cli import update_cmd
+from hermes_cli.update_inventory import UpdatePlan
@pytest.fixture(autouse=True)
@@ -81,164 +80,68 @@ def _make_head_pinned_side_effect(sha="abc123"):
def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
- """Patch the hermes_cli.main helpers ``_cmd_update_impl`` touches.
-
- ``_m()`` in update_cmd.py lazily returns hermes_cli.main, so patching
- attributes on that module is the canonical test surface (matches
- tests/hermes_cli/test_cmd_update.py).
- """
+ """Exercise the Git gate, capturing the request before the child runs."""
monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect)
monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)
- (tmp_path / ".git").mkdir() # pass the "is a git repo" gate
- monkeypatch.setattr(
- hermes_main, "_resolve_update_branch", lambda args: "main"
- )
- monkeypatch.setattr(hermes_main, "_is_windows", lambda: False)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: False)
+ (tmp_path / ".git").mkdir()
+ monkeypatch.setattr(hermes_main, "_resolve_update_branch", lambda args: "main")
monkeypatch.setattr(
hermes_main, "_get_origin_url",
lambda *a, **k: "https://github.com/NousResearch/hermes-agent.git",
)
monkeypatch.setattr(update_cmd, "_is_fork", lambda *a, **k: False)
+ monkeypatch.setattr(hermes_main, "_stash_local_changes_if_needed", lambda *a, **k: None)
+ monkeypatch.setattr(hermes_main, "_run_pre_update_backup", lambda *a: "snapshot-before-pull")
+ monkeypatch.setattr(hermes_main, "_pause_windows_gateways_for_update", lambda: None)
+ monkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a: None)
+ monkeypatch.setattr(hermes_main, "_install_hangup_protection", lambda **k: {"installed": False})
+ monkeypatch.setattr(hermes_main, "_finalize_update_output", lambda *a: None)
+ # Keep incidental version/inventory probes out of the mock's pre/post HEAD count.
monkeypatch.setattr(
- hermes_main, "_stash_local_changes_if_needed", lambda *a, **k: None
- )
- monkeypatch.setattr(hermes_main, "_clear_bytecode_cache", lambda *a, **k: 0)
- monkeypatch.setattr(
- hermes_main, "_record_bytecode_fingerprint", lambda *a, **k: None
- )
- monkeypatch.setattr(
- main_web_build, "_record_bytecode_fingerprint", lambda *a, **k: None
- )
- monkeypatch.setattr(
- hermes_main, "_run_pre_update_backup", lambda *a, **k: None
- )
- monkeypatch.setattr(
- hermes_main, "_pause_windows_gateways_for_update", lambda: None
- )
- monkeypatch.setattr(
- hermes_main, "_resume_windows_gateways_after_update", lambda *a, **k: None
- )
- # Short-circuit the long tail: dependency install + desktop build.
- monkeypatch.setattr(hermes_main, "_write_update_incomplete_marker", lambda: None)
- monkeypatch.setattr(hermes_main, "_clear_update_incomplete_marker", lambda: None)
- monkeypatch.setattr(
- hermes_main,
- "_install_hangup_protection",
- lambda gateway_mode=False: {
- "prev_stdout": None, "prev_stderr": None,
- "log_file": None, "installed": False,
- },
- )
- monkeypatch.setattr(hermes_main, "_finalize_update_output", lambda *a, **k: None)
- # _check_and_apply_config_migration → _run_migrate_config_fresh →
- # _reload_config_modules() force-reloads hermes_cli.config via
- # importlib, replacing the module object pytest's capsys + the config
- # tests' patches target. No-op the reload so the config module stays
- # stable for later tests in the same process.
- monkeypatch.setattr(
- "hermes_cli.update_cmd._reload_config_modules",
- lambda *a, **k: None,
+ "hermes_cli.version_info.get_version_info", lambda *a, **k: SimpleNamespace(),
)
- # The startup version-info probe runs git rev-parse HEAD (and the
- # result is cached per-process, so whether it runs depends on test
- # order). Mock it so the head-moved mock's call counting only sees the
- # update flow's own pre/post captures.
- monkeypatch.setattr(
- "hermes_cli.version_info.get_version_info",
- lambda *a, **k: SimpleNamespace(),
- )
- # Upstream refactor moved _clear_update_incomplete_marker into
- # main_install_repair; no-op it there too so the marker machinery
- # stays inert on both import paths.
- monkeypatch.setattr(main_install_repair, "_clear_update_incomplete_marker", lambda: None)
- # Gateway restart path (called after a successful update).
- monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda **k: None)
- # Keep the (now surfaced — #78574) gateway auto-restart phase away from
- # this machine's real gateways: discovery returns nothing, systemd is
- # unsupported, so the phase is a clean no-op for both snapshots.
- import hermes_cli.gateway as hermes_gateway
+ plan = UpdatePlan(install_method="git", expected_sha="abc123", profiles=["default"])
+ monkeypatch.setattr("hermes_cli.update_inventory.collect_runtime_inventory", lambda: plan)
+ monkeypatch.setattr("hermes_cli.update_receipt._code_identity", lambda **k: {"commit": "abc123"})
+ requests = []
- monkeypatch.setattr(
- hermes_gateway,
- "find_gateway_pids",
- lambda *a, **k: [],
- )
- # The gateway restart phase also probes per-profile processes; return
- # nothing so no real pid reaches the drain/kill loop (the conftest
- # live-system guard would block the os.kill).
- monkeypatch.setattr(
- hermes_gateway, "find_profile_gateway_processes", lambda *a, **k: []
- )
- # pm-era update flow: the venv re-sync after a pull runs
- # `pm.ensure.sync_venv`, which needs a real uv/venv. The test env has
- # neither, so short-circuit it — the head-moved gate is what's under
- # test, not dependency sync. (pm.ensure the package attribute is the
- # `ensure` function; the module is reached via importlib.)
- import importlib
-
- _pm_ensure_mod = importlib.import_module("pm.ensure")
-
- monkeypatch.setattr(_pm_ensure_mod, "sync_venv", lambda *a, **k: None)
- # Fleet-restart verification (#93406): no gateways are expected (the
- # pid probe above returns nothing), so the post-restart version matrix
- # must not demand rows or fail the update.
- monkeypatch.setattr(
- hermes_main,
- "_fleet_probe_expected_runtimes",
- lambda *a, **k: False,
- )
- # The gateway restart phase imports discovery functions fresh AFTER
- # _purge_stale_hermes_modules drops every cached module (the update
- # reloads code in-place), so monkeypatching hermes_cli.gateway
- # attributes is lost. The phase may still attempt os.kill on real
- # pids; stub os.kill so the conftest live-system guard never fires —
- # this test asserts the head-moved gate, not process teardown.
- import os as _os_mod
-
- monkeypatch.setattr(_os_mod, "kill", lambda *a, **k: None)
- monkeypatch.setattr(
- hermes_gateway, "kill_gateway_processes", lambda *a, **k: []
- )
- monkeypatch.setattr(
- hermes_gateway, "supports_systemd_services", lambda: False
- )
- monkeypatch.setattr(
- hermes_gateway, "find_profile_gateway_processes", lambda *a, **k: []
- )
- # _restart_gateways_after_update purges and re-imports hermes_cli.gateway,
- # which undoes the discovery mocks above (the fresh import finds the live
- # gateways on this dev machine). Neutralize the kill itself so the phase
- # is a no-op regardless of what the re-imported discovery returns.
- monkeypatch.setattr(os, "kill", lambda *a, **k: None)
- # ...and stop the purge from evicting the mocked module in the first place,
- # so find_gateway_pids stays [] and the fleet-restart phase is a clean no-op.
- monkeypatch.setattr(hermes_main, "_purge_stale_hermes_modules", lambda: None)
-
-
-def test_update_success_when_head_moves(monkeypatch, tmp_path, capsys):
- """When the pull advances HEAD, the update proceeds normally."""
+ def capture(request):
+ requests.append(deepcopy(request))
+ return {"exit_code": 0, "receipt": None}
+
+ monkeypatch.setattr(update_cmd, "run_completion", capture)
+ return requests, plan
+
+
+def test_update_hands_off_verified_head_when_it_moves(monkeypatch, tmp_path, capsys):
+ """Only the verified new tree and its pre-update state reach completion."""
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())
+ requests, plan = _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())
hermes_main.cmd_update(args) # completes normally (no SystemExit)
out = capsys.readouterr().out
- assert "✓ Code updated!" in out
assert "Code did not move" not in out
+ request, = requests
+ assert request["source"] == str(tmp_path.resolve())
+ assert request["branch"] == "main"
+ assert request["expected_sha"] == "def456"
+ assert request["plan"] == plan.to_dict()
+ assert request["receipt"]["plan"] == plan.to_dict()
+ assert request["snapshot_id"] == "snapshot-before-pull"
def test_update_fails_loudly_when_head_pinned(monkeypatch, tmp_path, capsys):
"""A detached/pinned HEAD that never moves must fail loudly, not print
'✓ Code updated!' against the stale tree."""
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- _patch_update_deps(monkeypatch, tmp_path, _make_head_pinned_side_effect())
+ requests, _ = _patch_update_deps(monkeypatch, tmp_path, _make_head_pinned_side_effect())
with pytest.raises(SystemExit) as exc_info:
hermes_main.cmd_update(args)
assert exc_info.value.code == 1
+ assert requests == []
out = capsys.readouterr().out
assert "Code did not move" in out
assert "✓ Code updated!" not in out
diff --git a/tests/hermes_cli/test_update_interrupted_recovery.py b/tests/hermes_cli/test_update_interrupted_recovery.py
index dc937a9d342..4f6355e16e0 100644
--- a/tests/hermes_cli/test_update_interrupted_recovery.py
+++ b/tests/hermes_cli/test_update_interrupted_recovery.py
@@ -1,27 +1,28 @@
-"""Tests for interrupted-install self-heal (the ``.update-incomplete`` marker).
+"""An interrupted old updater must retry with a complete source handoff.
-Covers the breadcrumb lifecycle. The launch-time recovery itself is now owned
-by PM: ``hermes_cli/_early_recovery.recover_if_needed`` asks ``pm.recovery``
-to restore dependencies and clears markers only on success — see
-tests/hermes_cli/test_early_recovery.py and tests/pm/test_recovery.py.
+The historical .update-incomplete writer is a relaunch shim, not a state
+protocol. PM recovery tests own dependency repair; this boundary must refuse
+completion when an old in-flight caller cannot provide the new request.
"""
-from __future__ import annotations
+import pytest
-import hermes_cli.main as m
+from hermes_cli import main as cli_main, update_cmd
-def test_marker_round_trip(tmp_path, monkeypatch):
- monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
- marker = m._update_marker_path()
- assert marker == tmp_path / ".update-incomplete"
- assert not marker.exists()
+def test_incomplete_handoff_requires_explicit_update_retry(tmp_path, monkeypatch, capsys):
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path)
+ monkeypatch.setattr(
+ update_cmd, "run_completion",
+ lambda request: pytest.fail("cannot launch completion without captured update state"),
+ )
- m._write_update_incomplete_marker()
- assert marker.exists()
- body = marker.read_text()
- assert "started=" in body
- assert "pid=" in body
+ with pytest.raises(SystemExit) as error:
+ update_cmd._complete_source_update(None)
- m._clear_update_incomplete_marker()
- assert not marker.exists()
+ assert error.value.code == 1
+ output = capsys.readouterr()
+ assert "run `hermes update` again" in output.err
+ assert "Update complete" not in output.out
+ assert not (tmp_path / ".update-incomplete").exists()
+ assert not (tmp_path / ".lazy-refresh-incomplete").exists()
diff --git a/tests/hermes_cli/test_update_parked_branch_guard.py b/tests/hermes_cli/test_update_parked_branch_guard.py
index b90234e31de..6b369576ee9 100644
--- a/tests/hermes_cli/test_update_parked_branch_guard.py
+++ b/tests/hermes_cli/test_update_parked_branch_guard.py
@@ -11,24 +11,25 @@ stale branch with none of main's new code. Two sessions burned time on
The guard (``_assess_parked_branch_switch``):
- clean tree + branch fully merged into origin/<target> → safe to
auto-switch back to the target (and STAY there — no switch-back).
-- dirty tree, unmerged commits, git failure, or the
- ``updates.auto_switch_parked_branch: false`` opt-out → do NOT touch the
- branch; warn loudly and mark the code update SKIPPED.
+- clean tree + unmerged commits → switch while preserving the old branch,
+ or merge in place when configured.
+- dirty tree, git failure, or the ``updates.auto_switch_parked_branch: false``
+ opt-out → do NOT touch the branch; warn and mark the code update SKIPPED.
These tests run the guard against REAL git repositories (init, commit,
branch, clone) — not mocked subprocess.run — so they exercise the actual
``git status`` / ``git cherry`` semantics the guard depends on.
"""
+from copy import deepcopy
import subprocess
from types import SimpleNamespace
import pytest
from hermes_cli import main as hermes_main
-import hermes_cli.main_web_build as main_web_build
-import hermes_cli.main_install_repair as main_install_repair
from hermes_cli import update_cmd
+from hermes_cli.update_inventory import UpdatePlan
GIT = ["git"]
@@ -240,37 +241,52 @@ def test_print_update_completion_carries_branch_and_sha(
# ---------------------------------------------------------------------------
-# Full update flow: parked branch dirty/unmerged → SKIPPED, no false success
+# Full update flow: branch safety and verified checkout completion handoff
# ---------------------------------------------------------------------------
-def _patch_update_flow(monkeypatch, repo, run_real_git=True):
- """Point _cmd_update_impl at the real repo and neuter the long tail.
-
- Matches the monkeypatch surface of test_update_head_moved_gate.py, but
- keeps REAL subprocess.run so the git plumbing runs against the fixture
- repo (the whole point of these regressions).
- """
+def _patch_update_flow(monkeypatch, repo):
+ """Keep real Git, but capture completion instead of building the tiny clone."""
monkeypatch.setattr(hermes_main, "PROJECT_ROOT", repo)
monkeypatch.setattr(hermes_main, "_resolve_update_branch", lambda args: "main")
- monkeypatch.setattr(hermes_main, "_is_windows", lambda: False)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: False)
monkeypatch.setattr(
hermes_main, "_get_origin_url",
lambda *a, **k: "https://github.com/NousResearch/hermes-agent.git",
)
monkeypatch.setattr(update_cmd, "_is_fork", lambda *a, **k: False)
monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *a, **k: None)
monkeypatch.setattr(update_cmd, "_normalize_managed_eol", lambda *a, **k: None)
- monkeypatch.setattr(hermes_main, "_clear_bytecode_cache", lambda *a, **k: 0)
- monkeypatch.setattr(hermes_main, "_record_bytecode_fingerprint", lambda *a, **k: None)
- monkeypatch.setattr(main_web_build, "_record_bytecode_fingerprint", lambda *a, **k: None)
- monkeypatch.setattr(hermes_main, "_run_pre_update_backup", lambda *a, **k: None)
+ monkeypatch.setattr(hermes_main, "_run_pre_update_backup", lambda *a: "pre-switch-snapshot")
monkeypatch.setattr(hermes_main, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(
- hermes_main, "_resume_windows_gateways_after_update", lambda *a, **k: None
- )
-
+ monkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a: None)
+ monkeypatch.setattr(hermes_main, "_install_hangup_protection", lambda **k: {"installed": False})
+ monkeypatch.setattr(hermes_main, "_finalize_update_output", lambda *a: None)
+ plan = UpdatePlan(
+ install_method="git", expected_sha=_git(repo, "rev-parse", "HEAD").stdout.strip(),
+ profiles=["default"],
+ )
+ monkeypatch.setattr("hermes_cli.update_inventory.collect_runtime_inventory", lambda: plan)
+ requests = []
+
+ def capture(request):
+ requests.append(deepcopy(request))
+ return {"exit_code": 0, "receipt": None}
+
+ monkeypatch.setattr(update_cmd, "run_completion", capture)
+ return requests, plan
+
+
+def _assert_completion(requests, plan, repo, *, current=False):
+ request, = requests
+ assert request["source"] == str(repo.resolve())
+ assert request["branch"] == "main"
+ assert request["plan"] == plan.to_dict()
+ assert request["receipt"]["plan"] == plan.to_dict()
+ assert request["snapshot_id"] == "pre-switch-snapshot"
+ if current:
+ assert request["completion_message"] == "✓ Already up to date!"
+ assert request["plan"]["expected_sha"] == _git(repo, "rev-parse", "HEAD").stdout.strip()
+ else:
+ assert request["expected_sha"] == _git(repo, "rev-parse", "HEAD").stdout.strip()
def test_update_skips_and_warns_on_dirty_parked_branch(
@@ -280,13 +296,15 @@ def test_update_skips_and_warns_on_dirty_parked_branch(
NOT print '✓ Code updated!', must warn loudly, and must exit non-zero
with the branch named in the summary."""
(repo_pair / "a.txt").write_text("local edit\n")
- _patch_update_flow(monkeypatch, repo_pair)
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
with pytest.raises(SystemExit) as exc_info:
hermes_main.cmd_update(args)
assert exc_info.value.code == 1
+ assert requests == []
+ assert (repo_pair / "a.txt").read_text() == "local edit\n"
out = capsys.readouterr().out
assert "CODE UPDATE SKIPPED" in out
assert "old-feature" in out
@@ -313,21 +331,12 @@ def test_update_switches_unmerged_parked_branch_with_kept_notice(
_git(repo_pair, "add", "feature.txt")
_git(repo_pair, "commit", "-qm", "feature work")
feature_sha = _git(repo_pair, "rev-parse", "old-feature").stdout.strip()
- _patch_update_flow(monkeypatch, repo_pair)
-
- class _StopFlow(Exception):
- pass
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
- # Stop at product preparation, after the real Git update but before any build.
- monkeypatch.setattr(
- update_cmd,
- "_prepare_updated_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, repo_pair)
out = capsys.readouterr().out
assert "1 commit(s) not merged into origin/main" in out
@@ -367,22 +376,12 @@ def test_update_updates_unmerged_branch_in_place_when_configured(
(repo_pair / "feature.txt").write_text("unmerged work\n")
_git(repo_pair, "add", "feature.txt")
_git(repo_pair, "commit", "-qm", "feature work")
- _patch_update_flow(monkeypatch, repo_pair)
-
- # Stop right after the pull/branch logic, before dependency install.
- class _StopFlow(Exception):
- pass
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
- # Stop at product preparation, after the real Git update but before any build.
- monkeypatch.setattr(
- update_cmd,
- "_prepare_updated_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, repo_pair)
out = capsys.readouterr().out
assert "updating it in place" in out
@@ -424,24 +423,15 @@ def test_switch_branch_flag_overrides_in_place_strategy(
branch_tip_before = _git(
repo_pair, "rev-parse", "old-feature"
).stdout.strip()
- _patch_update_flow(monkeypatch, repo_pair)
-
- class _StopFlow(Exception):
- pass
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
- # Stop at product preparation, after the real Git update but before any build.
- monkeypatch.setattr(
- update_cmd,
- "_prepare_updated_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
args = SimpleNamespace(
branch=None, yes=False, force=False, force_venv=False,
switch_branch=True,
)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, repo_pair)
out = capsys.readouterr().out
assert "1 commit(s) not merged into origin/main" in out
@@ -475,24 +465,15 @@ def test_unmerged_branch_still_updates_in_place_without_the_flag(
(repo_pair / "feature.txt").write_text("unmerged work\n")
_git(repo_pair, "add", "feature.txt")
_git(repo_pair, "commit", "-qm", "feature work")
- _patch_update_flow(monkeypatch, repo_pair)
-
- class _StopFlow(Exception):
- pass
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
- # Stop at product preparation, after the real Git update but before any build.
- monkeypatch.setattr(
- update_cmd,
- "_prepare_updated_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
args = SimpleNamespace(
branch=None, yes=False, force=False, force_venv=False,
switch_branch=False,
)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, repo_pair)
out = capsys.readouterr().out
assert "updating it in place" in out
@@ -509,21 +490,11 @@ def test_update_auto_switches_clean_merged_parked_branch(
"""Clean + fully merged parked branch → auto-switch back to main, pull,
say so, and STAY on main afterwards (sabotage-proven: reverting the
guard re-parks the checkout and this test fails on the branch assert)."""
- _patch_update_flow(monkeypatch, repo_pair)
- # Stop right after the pull/branch logic, before product preparation.
- class _StopFlow(Exception):
- pass
-
- # Stop at product preparation, after the real Git update but before any build.
- monkeypatch.setattr(
- update_cmd,
- "_prepare_updated_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, repo_pair)
out = capsys.readouterr().out
assert "parked on 'old-feature'" in out
@@ -564,20 +535,12 @@ def test_update_up_to_date_path_does_not_repark_merged_branch(
_git(clone, "checkout", "-qb", "old-feature")
# No new upstream commits: local main == origin/main == old-feature tip.
- _patch_update_flow(monkeypatch, clone)
+ requests, plan = _patch_update_flow(monkeypatch, clone)
- class _StopFlow(Exception):
- pass
-
- monkeypatch.setattr(
- update_cmd,
- "_repair_current_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, clone, current=True)
out = capsys.readouterr().out
assert "switched back to main" in out
@@ -591,21 +554,12 @@ def test_update_on_main_fast_path_unchanged(repo_pair, monkeypatch, capsys):
"""On the target branch already: no guard prints, normal pull flow."""
_git(repo_pair, "checkout", "-q", "main")
- _patch_update_flow(monkeypatch, repo_pair)
+ requests, plan = _patch_update_flow(monkeypatch, repo_pair)
- class _StopFlow(Exception):
- pass
-
- # Stop at product preparation, after the real Git update but before any build.
- monkeypatch.setattr(
- update_cmd,
- "_prepare_updated_checkout",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
+ hermes_main.cmd_update(args)
+ _assert_completion(requests, plan, repo_pair)
out = capsys.readouterr().out
assert "parked on" not in out
diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.py
index 793aa9508f6..d3ced430a39 100644
--- a/tests/hermes_cli/test_update_target_identity.py
+++ b/tests/hermes_cli/test_update_target_identity.py
@@ -1,4 +1,5 @@
"""Stable updates consume one remote commit across Git and archive transports."""
+from copy import deepcopy
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import os
@@ -11,11 +12,8 @@ import urllib.request
import pytest
-from hermes_cli import main as cli_main, update_cmd, update_cmd_maint, update_receipt
-
-
-class DependencyBoundary(Exception):
- pass
+from hermes_cli import main as cli_main, update_cmd, update_receipt
+from hermes_cli.update_inventory import UpdatePlan
def git(root, *args):
@@ -57,28 +55,35 @@ def update_tree(tmp_path, monkeypatch):
monkeypatch.setattr(cli_main, 'PROJECT_ROOT', clone)
monkeypatch.setattr(update_receipt, '_code_identity', lambda **_: {'commit': base})
- monkeypatch.setattr(cli_main, '_run_pre_update_backup', lambda *_: None)
+ monkeypatch.setattr(cli_main, '_run_pre_update_backup', lambda *_: 'release-snapshot')
monkeypatch.setattr(cli_main, '_pause_windows_gateways_for_update', lambda: None)
resumed = []
monkeypatch.setattr(cli_main, '_resume_windows_gateways_after_update', lambda state: resumed.append(state))
monkeypatch.setattr(cli_main, '_install_hangup_protection', lambda **_: {'installed': False})
monkeypatch.setattr(cli_main, '_finalize_update_output', lambda *_: None)
- monkeypatch.setattr(update_cmd, '_begin_update_receipt_and_plan', lambda *_: None)
+ plans = []
+
+ def inventory():
+ sha = git(clone, 'rev-parse', 'HEAD') if (clone / '.git').exists() else base
+ plan = UpdatePlan(install_method='git', expected_sha=sha, profiles=['default'])
+ plans.append(plan)
+ return plan
+
+ monkeypatch.setattr('hermes_cli.update_inventory.collect_runtime_inventory', inventory)
monkeypatch.setattr(cli_main, '_sync_with_upstream_if_needed',
lambda *_a, **_k: pytest.fail('stable update reached upstream branch sync'))
- def stop_at_dependencies(*_args, **_kwargs):
- raise DependencyBoundary()
+ requests = []
+
+ def capture(request):
+ requests.append(deepcopy(request))
+ return {'exit_code': 0, 'receipt': None}
- monkeypatch.setattr(update_cmd, '_prepare_updated_checkout', stop_at_dependencies)
- monkeypatch.setattr(update_cmd_maint, '_prepare_updated_checkout', stop_at_dependencies)
- repaired = []
- monkeypatch.setattr(update_cmd, '_repair_current_checkout', lambda **_: repaired.append(True) or True)
- monkeypatch.setattr(update_cmd, '_apply_pending_fleet_restart_catchup', lambda: None)
+ monkeypatch.setattr(update_cmd, 'run_completion', capture)
args = SimpleNamespace(branch=None, channel='stable', yes=True, force=True, force_venv=True,
check=False, plan=False, gateway=False, install_id=False, set_channel=None)
return SimpleNamespace(origin=origin, clone=clone, base=base, wanted=wanted, newer=newer,
- args=args, resumed=resumed, repaired=repaired)
+ args=args, resumed=resumed, requests=requests, plans=plans)
@pytest.mark.parametrize('server', ['sha', 'tag-fallback', 'moved-sha', 'moved-fallback',
@@ -137,17 +142,26 @@ def test_stable_git_uses_remote_identity_without_moving_local_tags(update_tree,
assert error.value.code == 1
assert git(t.clone, 'rev-parse', 'HEAD') == t.base
assert t.resumed
- elif server == 'at-release':
- cli_main.cmd_update(t.args)
- assert t.repaired == [True]
- assert git(t.clone, 'rev-parse', 'HEAD') == expected
+ assert t.requests == []
else:
- with pytest.raises(DependencyBoundary):
- cli_main.cmd_update(t.args)
+ cli_main.cmd_update(t.args)
+ request, = t.requests
+ plan, = t.plans
+ assert request['source'] == str(t.clone.resolve())
+ assert request['branch'] == (t.args.branch or 'main')
+ assert request['plan'] == plan.to_dict()
+ assert request['receipt']['plan'] == plan.to_dict()
+ assert request['snapshot_id'] == 'release-snapshot'
+ if server == 'at-release':
+ assert request['completion_message'] == '✓ Already up to date!'
+ assert request['plan']['expected_sha'] == expected
+ else:
+ assert request['expected_sha'] == expected
assert git(t.clone, 'rev-parse', 'HEAD') == expected
content = 'unreleased-main\n' if server == 'explicit-branch' else 'release\n'
assert (t.clone / 'content.txt').read_text(encoding='utf-8') == content
- assert git(t.clone, 'branch', '--show-current') == ('retained-branch' if server == 'explicit-branch' else '')
+ branch = 'retained-branch' if server in {'at-release', 'explicit-branch'} else ''
+ assert git(t.clone, 'branch', '--show-current') == branch
assert resolved == (server != 'explicit-branch')
assert git(t.clone, 'rev-parse', 'v1.1.0') == t.base
assert not git(t.clone, 'status', '--porcelain')
@@ -243,9 +257,16 @@ def test_stable_zip_consumes_the_same_commit_through_the_real_swap(update_tree,
assert error.value.code == 1
assert (t.clone / 'content.txt').read_bytes() == before
assert not any('/archive/' in url for url in urls)
+ assert t.requests == []
else:
- with pytest.raises(DependencyBoundary):
- cli_main.cmd_update(t.args)
+ cli_main.cmd_update(t.args)
+ request, = t.requests
+ plan, = t.plans
+ assert request['source'] == str(t.clone.resolve())
+ assert request['expected_sha'] == t.wanted
+ assert request['plan'] == plan.to_dict()
+ assert request['receipt']['plan'] == plan.to_dict()
+ assert request['snapshot_id'] == 'release-snapshot'
assert (t.clone / 'content.txt').read_text(encoding='utf-8') == 'release\n'
assert [url for url in urls if '/archive/' in url] == [
f'https://github.com/NousResearch/hermes-agent/archive/{t.wanted}.zip']
diff --git a/tests/hermes_cli/test_update_unit_client_budget.py b/tests/hermes_cli/test_update_unit_client_budget.py
index c9db5169f6c..5a88911b43a 100644
--- a/tests/hermes_cli/test_update_unit_client_budget.py
+++ b/tests/hermes_cli/test_update_unit_client_budget.py
@@ -6,17 +6,14 @@ import pytest
from hermes_cli import update_cmd_fleet as fleet
[email protected]("graceful,retry", [(False, False), (False, True), (True, False), ("catchup", False)])
[email protected]("graceful,retry", [(False, False), (False, True), (True, False)])
def test_unit_transaction_budget_preserves_scope_and_health(monkeypatch, graceful, retry):
- catchup = graceful == "catchup"
- scope = ["systemctl", "--user"] if catchup else ["systemctl", "--no-ask-password"]
- manage = scope if catchup else ["sudo", "-n", *scope]
+ scope = ["systemctl", "--no-ask-password"]
+ manage = ["sudo", "-n", *scope]
calls = []
def systemctl(cmd, *, timeout):
calls.append((cmd, timeout))
- if "list-units" in cmd:
- return subprocess.CompletedProcess(cmd, 0, "hermes-serve-test.service loaded active running", "")
if "show" in cmd:
assert cmd[:len(scope)] == scope
output = "42" if "--property=MainPID" in cmd else "TimeoutStopUSec=70s\nTimeoutStartUSec=90s"
@@ -27,13 +24,6 @@ def test_unit_transaction_budget_preserves_scope_and_health(monkeypatch, gracefu
return subprocess.CompletedProcess(cmd, 0, "active", "")
monkeypatch.setattr(fleet, "_systemctl", systemctl)
- if catchup:
- monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", scope),))
- failed = []
- fleet._restart_systemd_gateway_units_best_effort(failed, list(fleet._systemd_gateway_unit_listings()))
- assert not failed
- assert sum("restart" in cmd for cmd, _ in calls) == 1
- return
monkeypatch.setattr(fleet, "_drain_or_signal_gateway_for_update", lambda *a: True)
health = iter([False, True] if retry else [True])
monkeypatch.setattr(fleet, "_wait_for_service_active", lambda *a, **kw: next(health))
@@ -48,6 +38,47 @@ def test_unit_transaction_budget_preserves_scope_and_health(monkeypatch, gracefu
assert sum("restart" in cmd or "start" in cmd for cmd, _ in calls) == (2 if retry else 1)
[email protected]("healthy", [True, False])
+def test_fleet_restart_budget_preserves_user_scope_and_verifies_health(monkeypatch, healthy):
+ """Already-current updates use the normal fleet restart, not a catch-up shortcut."""
+ scope = ["systemctl", "--user"]
+ manage = [*scope, "--no-ask-password"]
+ calls, health_checks = [], []
+ name = "hermes-serve-test"
+
+ def systemctl(cmd, *, timeout):
+ calls.append((cmd, timeout))
+ assert cmd[:len(scope)] == scope
+ if "list-units" in cmd:
+ return subprocess.CompletedProcess(cmd, 0, f"{name}.service loaded active running", "")
+ if "show" in cmd:
+ return subprocess.CompletedProcess(cmd, 0, "TimeoutStopUSec=70s\nTimeoutStartUSec=90s", "")
+ if "restart" in cmd:
+ assert cmd[:len(manage)] == manage
+ assert timeout > 160
+ return subprocess.CompletedProcess(cmd, 0, "active", "")
+
+ def check_health(command, unit, *, timeout):
+ health_checks.append((command, unit))
+ return healthy
+
+ monkeypatch.setattr(fleet, "_systemctl", systemctl)
+ monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", scope),))
+ monkeypatch.setattr(fleet, "_wait_for_service_active", check_health)
+ monkeypatch.setattr("hermes_cli.gateway.supports_systemd_services", lambda: True)
+ monkeypatch.setattr("hermes_cli.gateway._ensure_user_systemd_env", lambda: None)
+ restarted, failed, scoped = [], [], set()
+ fleet._restart_systemd_gateway_units(restarted, failed, scoped, drain_budget=45)
+
+ attempts = 1 if healthy else 2
+ assert health_checks == [(scope, name)] * attempts
+ assert sum("restart" in cmd for cmd, _ in calls) == attempts
+ assert restarted == ([name] if healthy else [])
+ assert scoped == ({f"user/{name}"} if healthy else set())
+ assert failed == ([] if healthy else [name])
+
+
@pytest.mark.parametrize("limits", ["", "TimeoutStopUSec=infinity\nTimeoutStartUSec=invalid", "TimeoutStopUSec=70000000\nTimeoutStartUSec=90s"])
@pytest.mark.parametrize("outcome", [0, 7, "timeout"])
def test_budget_fallback_keeps_real_errors(monkeypatch, limits, outcome):