Skip to content

The agent that grows with you

test: consolidate updater safety and CLI lifecycle contracts

ethernet32d774564845
diff --git a/tests/hermes_cli/test_boot_bootstrap.py b/tests/hermes_cli/test_boot_bootstrap.py
index 23aaeda439e..e83b9ca7807 100644
--- a/tests/hermes_cli/test_boot_bootstrap.py
+++ b/tests/hermes_cli/test_boot_bootstrap.py
@@ -57,10 +57,6 @@ def _head_sha(root):
# ── read_git_head ────────────────────────────────────────────────────
-def test_read_git_head_branch_ref(repo):
- assert read_git_head(repo) == _head_sha(repo)
-
-
def test_git_selection_uses_pm_public_package_reader(repo, monkeypatch):
from types import SimpleNamespace
import pm
@@ -134,18 +130,6 @@ def test_read_git_head_missing_and_garbage(tmp_path):
# ── current_install_identity ─────────────────────────────────────────
-def test_identity_prefers_git(repo):
- assert current_install_identity(repo) == _head_sha(repo)
-
-
-def test_identity_sealed_stamp(tmp_path):
- (tmp_path / "install-stamp.json").write_text(
- json.dumps({"commit": "a" * 40, "distribution": "desktop-app", "updateMechanism": "electron-updater"}),
- encoding="utf-8",
- )
- assert current_install_identity(tmp_path) == "a" * 40
-
-
def test_identity_broken_tree_is_none(tmp_path):
assert current_install_identity(tmp_path) is None
(tmp_path / "install-stamp.json").write_text("garbage", encoding="utf-8")
@@ -167,21 +151,6 @@ def test_record_paths_key_on_install_root(tmp_path, monkeypatch):
assert a.name == b.name # the profile filename is the shared part
-def test_home_records_differ_per_profile(tmp_path, monkeypatch):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- base = tmp_path / ".hermes"
- profile = base / "profiles" / "coder"
- install = tmp_path / "install"
-
- monkeypatch.setenv("HERMES_HOME", str(base))
- home_default = record_path(install)
-
- monkeypatch.setenv("HERMES_HOME", str(profile))
- home_profile = record_path(install)
-
- assert home_default != home_profile # each profile bootstraps its own home
-
-
@pytest.mark.skipif(
os.name == "nt", reason="requires symlink privilege on Windows"
)
@@ -197,26 +166,11 @@ def test_symlinked_root_canonicalizes(tmp_path, monkeypatch):
# ── needs_bootstrap ──────────────────────────────────────────────────
-def test_needs_bootstrap_lifecycle(repo, tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- sha = _head_sha(repo)
-
- # No record yet → identity returned.
- assert needs_bootstrap(repo) == sha
-
- _write_record(record_path(repo), sha, {})
- assert needs_bootstrap(repo) is None
-
- # New commit → mismatch again.
- (repo / "f.txt").write_text("2", encoding="utf-8")
- _git(["add", "."], repo)
- _git(["commit", "-m", "two"], repo)
- assert needs_bootstrap(repo) == _head_sha(repo)
-
-
def test_needs_bootstrap_broken_tree_never_fires(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
assert needs_bootstrap(tmp_path / "nope") is None
+ assert run_boot_bootstrap(tmp_path / "nope") == {"home": "skipped"}
+ assert not record_path(tmp_path / "nope").exists()
# ── lock protocol ────────────────────────────────────────────────────
@@ -272,52 +226,6 @@ def fake_steps(monkeypatch):
return calls
-def test_run_boot_bootstrap_runs_then_noops(repo, tmp_path, monkeypatch, fake_steps):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
-
- first = run_boot_bootstrap(repo)
- assert fake_steps == {"home": 1}
- assert first["home"] == {"h": {"ok": True}}
-
- second = run_boot_bootstrap(repo)
- assert fake_steps == {"home": 1} # no re-run
- assert second == {"home": "skipped"}
-
-
-def test_each_profile_runs_its_own_home_steps(repo, tmp_path, monkeypatch, fake_steps):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- base = tmp_path / ".hermes"
-
- monkeypatch.setenv("HERMES_HOME", str(base))
- run_boot_bootstrap(repo)
- monkeypatch.setenv("HERMES_HOME", str(base / "profiles" / "coder"))
- run_boot_bootstrap(repo)
-
- # Each home bootstraps itself.
- assert fake_steps == {"home": 2}
-
-
-def test_step_failure_still_writes_record(repo, tmp_path, monkeypatch):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
-
- from hermes_cli import post_update
-
- def boom():
- raise RuntimeError("step exploded")
-
- monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("boom", boom),))
-
- run_boot_bootstrap(repo)
- record = read_last_known(record_path(repo))
- assert record["identity"] == _head_sha(repo)
- assert record["results"]["boom"]["ok"] is False
-
- # A broken step must not retrigger the slow path every boot.
- assert needs_bootstrap(repo) is None
-
-
def test_double_check_under_lock(repo, tmp_path, monkeypatch, fake_steps):
"""A racer that finished between our read and our acquire wins."""
monkeypatch.setattr(Path, "home", lambda: tmp_path)
diff --git a/tests/hermes_cli/test_boot_convergence.py b/tests/hermes_cli/test_boot_convergence.py
index 1dcb16069ab..30d31edfbfa 100644
--- a/tests/hermes_cli/test_boot_convergence.py
+++ b/tests/hermes_cli/test_boot_convergence.py
@@ -152,6 +152,22 @@ print(json.dumps(boot_bootstrap.run_boot_bootstrap(root)))
assert len(list(directory.glob("config.yaml.bak-*"))) == 1
with sqlite3.connect(directory / "state.db") as db:
assert db.execute("SELECT value FROM retained").fetchall() == [("before",)]
+ # A changed artifact or Git identity must run the real migration again.
+ for revision in ('sealed', 'git'):
+ (home / 'config.yaml').write_text(f"_config_version: {DEFAULT_CONFIG['_config_version'] - 1}\n")
+ if revision == 'sealed':
+ (root / 'install-stamp.json').write_text(json.dumps({
+ 'commit': 'fedcba987654', 'updateMechanism': 'external'}))
+ else:
+ subprocess.run(['git', 'init', '-q', str(root)], check=True)
+ subprocess.run(['git', '-c', 'user.name=Fixture', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'revision'],
+ cwd=root, check=True)
+ changed = subprocess.run([*command, 'go'], env=env, capture_output=True, text=True, timeout=30)
+ assert changed.returncode == 0, changed.stderr
+ assert json.loads(changed.stdout.splitlines()[-1])['home']['migrate']['ok']
+ import hermes_yaml
+ assert hermes_yaml.safe_load((home / 'config.yaml').read_text())['_config_version'] == DEFAULT_CONFIG['_config_version']
finally:
release.touch()
if first.poll() is None:
@@ -190,3 +206,6 @@ def test_failed_migration_is_restored_and_not_retried(tmp_path, monkeypatch):
assert {p: p.read_bytes() for p in original} == original
assert boot_bootstrap.run_boot_bootstrap(root) == {"home": "skipped"}
assert calls == [True]
+ record = boot_bootstrap.read_last_known(boot_bootstrap.record_path(root))
+ assert record['identity'] == 'abcdef012345'
+ assert record['results']['migrate']['ok'] is False
diff --git a/tests/hermes_cli/test_boot_wiring.py b/tests/hermes_cli/test_boot_wiring.py
index f2126874691..f53dc5ecfbb 100644
--- a/tests/hermes_cli/test_boot_wiring.py
+++ b/tests/hermes_cli/test_boot_wiring.py
@@ -68,165 +68,6 @@ def test_cli_main_skips_boot_bootstrap_during_update(hermes_home, boot_probe):
assert boot_probe == [], "the update flow owns its own maintenance pass"
-def test_boot_bootstrap_reaches_post_update_registry(hermes_home, tmp_path, monkeypatch):
- """The real maybe_run_boot_bootstrap runs due steps from ONE registry
- (no inline duplicate maintenance in the boot path)."""
- import sys
-
- from hermes_cli import boot_bootstrap, post_update
-
- ran: list[str] = []
- monkeypatch.setattr(
- post_update,
- "BOOT_HOME_STEPS",
- (("probe_home", lambda: (ran.append("home"), {"ok": True})[1]),),
- )
-
- root = tmp_path / "install"
- root.mkdir()
- (root / ".git").mkdir(parents=True)
- import subprocess as sp
-
- head = sp.run(
- ["git", "init", "-q", "-b", "main"], cwd=root, capture_output=True
- )
- assert head.returncode == 0
- (root / "f.txt").write_text("1", encoding="utf-8")
- for args in (["add", "."], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "one"]):
- sp.run(["git", *args], cwd=root, capture_output=True, check=True)
-
- boot_bootstrap.maybe_run_boot_bootstrap(root)
-
- assert sorted(ran) == ["home"]
- # second boot: record-gated no-op, no doubled maintenance
- boot_bootstrap.maybe_run_boot_bootstrap(root)
- assert sorted(ran) == ["home"]
-
-
# ── gateway entry point reaches the registry ─────────────────────────
# (the gr.main() contract is tests/gateway/test_pm_activation.py; here we
# prove the wiring call exists on the real function's module)
-
-
-# ── the cadence tick on the existing housekeeping loop ───────────────
-
-
-def test_housekeeping_chore_delegates_to_cadence(hermes_home, monkeypatch):
- import gateway.run as gr
- import hermes_cli.plugins_cadence as cad
-
- called: list = []
- monkeypatch.setattr(
- cad, "maybe_run_gateway_check", lambda **kw: called.append(kw)
- )
-
- gr._housekeeping_chore("Plugin update check", gr._housekeeping_plugin_update_check)
-
- assert len(called) == 1
-
-
-# ── the production cadence wrapper ───────────────────────────────────
-
-
-class _Result:
- def __init__(self, name, klass="git", update_available=None, needs_fixing=None):
- self.name = name
- self.klass = klass
- self.update_available = update_available
- self.needs_fixing = needs_fixing
-
-
-def _write_fresh_marker():
- import hermes_constants
-
- d = hermes_constants.get_hermes_home() / "plugin-update-checks"
- d.mkdir(parents=True, exist_ok=True)
- marker = d / "last-run"
- marker.write_text(str(int(time.time())), encoding="utf-8")
-
-
-def test_gateway_check_not_due_makes_no_request(hermes_home, monkeypatch):
- import hermes_cli.plugins_cadence as cad
-
- _write_fresh_marker()
-
- def _explode(*_a, **_kw):
- raise AssertionError("network must not be touched when not due")
-
- assert (
- cad.maybe_run_gateway_check(
- run_checks_fn=_explode, plugins_dir=hermes_home / "plugins"
- )
- is None
- )
-
-
-def test_gateway_check_disabled_makes_no_request(hermes_home, monkeypatch):
- import hermes_cli.plugins_cadence as cad
-
- monkeypatch.setattr(
- cad, "check_interval_hours", lambda config_get=None: 0.0
- )
-
- def _explode(*_a, **_kw):
- raise AssertionError("disabled cadence must not request")
-
- assert (
- cad.maybe_run_gateway_check(run_checks_fn=_explode, plugins_dir=None) is None
- )
-
-
-def test_gateway_check_due_runs_and_defaults_apply_seam(hermes_home, monkeypatch):
- import hermes_cli.plugins_cadence as cad
- import hermes_cli.plugins_cmd as plugins_cmd
-
- results = [_Result("plug", update_available=True)]
- seen: dict = {}
-
- def _checks(plugins_dir):
- seen["dir"] = plugins_dir
- return results
-
- applied: list[str] = []
- monkeypatch.setattr(
- plugins_cmd, "cmd_update", lambda name, **kw: applied.append(name), raising=True
- )
- monkeypatch.setattr(cad, "auto_apply_enabled", lambda config_get=None: True)
-
- out = cad.maybe_run_gateway_check(
- run_checks_fn=_checks, plugins_dir=hermes_home / "plugins", now=time.time()
- )
-
- assert out == results
- assert applied == ["plug"], "git-class updates apply through the manual update flow"
- # the marker was stamped
- import hermes_constants
-
- marker = hermes_constants.get_hermes_home() / "plugin-update-checks" / "last-run"
- assert marker.is_file()
-
-
-def test_gateway_check_network_error_never_applies(hermes_home, monkeypatch):
- import hermes_cli.plugins_cadence as cad
- import hermes_cli.plugins_cmd as plugins_cmd
-
- def _checks(_plugins_dir):
- raise OSError("network unreachable")
-
- applied: list[str] = []
- monkeypatch.setattr(
- plugins_cmd, "cmd_update", lambda name, **kw: applied.append(name), raising=True
- )
- monkeypatch.setattr(cad, "auto_apply_enabled", lambda config_get=None: True)
-
- out = cad.maybe_run_gateway_check(
- run_checks_fn=_checks, plugins_dir=hermes_home / "plugins", now=time.time()
- )
-
- assert out == []
- assert applied == [], "a failed check must never trigger an apply"
- # and the failed tick is stamped so it does not hammer the network
- import hermes_constants
-
- marker = hermes_constants.get_hermes_home() / "plugin-update-checks" / "last-run"
- assert marker.is_file()
diff --git a/tests/hermes_cli/test_bundled_desktop_launch.py b/tests/hermes_cli/test_bundled_desktop_launch.py
index 0e63cc923a3..dcc23873f28 100644
--- a/tests/hermes_cli/test_bundled_desktop_launch.py
+++ b/tests/hermes_cli/test_bundled_desktop_launch.py
@@ -100,6 +100,8 @@ def _host_bundle(tmp_path: Path) -> tuple[Path, Path]:
if sys.platform == "win32":
repo = _windows_bundle(tmp_path)
return repo, tmp_path / "Hermes" / "Hermes.exe"
+ if sys.platform == "darwin":
+ return _macos_bundle(tmp_path), tmp_path / "Hermes.app/Contents/MacOS/Hermes"
repo = _linux_bundle(tmp_path)
return repo, tmp_path / "linux-unpacked" / "Hermes"
@@ -177,7 +179,7 @@ class TestShapePredicate:
class TestLaunchDetached:
- def test_the_child_outlives_this_process_and_owns_no_stdio(self):
+ def test_detach_flags_and_unowned_stdio_are_forwarded(self):
seen = {}
def fake_popen(argv, **kwargs):
@@ -198,7 +200,7 @@ class TestLaunchDetached:
detach_key = "creationflags" if sys.platform == "win32" else "start_new_session"
assert seen["kwargs"][detach_key]
- def test_a_real_child_survives_and_is_reachable(self, tmp_path):
+ def test_a_real_detached_child_runs(self, tmp_path):
"""The one E2E rung: spawn a real process and prove it ran."""
marker = tmp_path / "ran.txt"
pid = launch_detached(
@@ -214,6 +216,7 @@ class TestLaunchDetached:
assert marker.read_text() == "yes"
[email protected]("windows", "linux", "macos")
class TestCmdGuiOnABundle:
"""The behavior the checkout ladder got wrong: never build in a bundle."""
diff --git a/tests/hermes_cli/test_cadence_failure_receipt.py b/tests/hermes_cli/test_cadence_failure_receipt.py
deleted file mode 100644
index b11371fb2df..00000000000
--- a/tests/hermes_cli/test_cadence_failure_receipt.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Cadence failures retain the same warning shown to the operator."""
-from unittest.mock import Mock
-
-from hermes_cli.plugins_cadence import run_scheduled_check
-from pm import receipt
-
-
-def test_failed_check_records_warning_and_nonzero_exit(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- log = Mock()
-
- def fail(_):
- raise OSError("offline")
-
- run_scheduled_check(run_checks_fn=fail, plugins_dir=tmp_path / "plugins", log=log)
- saved = receipt.latest()
- assert saved["outcome"] == "failed"
- assert saved["exit_code"] != 0
- assert saved["warnings"][0]["message"] == log.warning.call_args_list[0].args[0]
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index 9be93fcc4eb..8b14ab22130 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -18,8 +18,6 @@ def _isolate_venv_holders(monkeypatch):
monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: [])
-
-
def _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"):
"""Build a side_effect function for subprocess.run that simulates git commands."""
@@ -59,127 +57,6 @@ class TestCmdUpdateBranchFallback:
"""cmd_update falls back to main when current branch has no remote counterpart."""
-
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_update_on_fork_checks_upstream_when_origin_up_to_date(
- self, mock_run, _mock_which, mock_args, capsys
- ):
- """Regression for issue #26172: forks whose local HEAD already matches
- origin/main must still consult upstream/main before printing
- "Already up to date!" — otherwise a fork that's caught up to its own
- origin but behind NousResearch/hermes-agent silently misses updates.
- """
- from hermes_cli import main as hm
- from hermes_cli import update_cmd
-
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="0"
- )
-
- with patch.object(
- hm,
- "_get_origin_url",
- return_value="https://github.com/example/hermes-agent.git",
- ), patch.object(hm, "_sync_with_upstream_if_needed") as sync_mock, patch.object(
- update_cmd, "_check_and_apply_config_migration"
- ):
- cmd_update(mock_args)
-
- expected_git_cmd = (
- ["git", "-c", "windows.appendAtomically=false"] if hm._is_windows() else ["git"]
- )
- sync_mock.assert_called_once_with(
- expected_git_cmd,
- # Resolved live: the module autouse fixture pins PROJECT_ROOT to
- # tmp_path, so the imported constant would be stale here.
- hm.PROJECT_ROOT,
- assume_yes=False,
- input_fn=None,
- )
- captured = capsys.readouterr()
- assert "Already up to date!" in captured.out
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_yes_on_fork_without_upstream_does_not_claim_up_to_date(
- self, mock_run, _mock_which, capsys
- ):
- """#97052 review: genuine fork, no upstream remote, HEAD == origin/main,
- --yes. The prompt is skipped without mutating remotes, and because the
- official repo was never consulted the completion line must not claim
- plain "Already up to date!"."""
- from hermes_cli import main as hm
- from hermes_cli import update_cmd
-
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="0"
- )
-
- with patch.object(
- hm,
- "_get_origin_url",
- return_value="https://github.com/example/hermes-agent.git",
- ), patch.object(
- update_cmd, "_has_upstream_remote", return_value=False
- ), patch.object(
- update_cmd, "_should_skip_upstream_prompt", return_value=False
- ), patch.object(
- update_cmd, "_add_upstream_remote"
- ) as add_remote, patch.object(
- update_cmd, "_mark_skip_upstream_prompt"
- ) as mark_skip, patch("builtins.input") as stdin_input:
- cmd_update(SimpleNamespace(yes=True))
-
- stdin_input.assert_not_called()
- add_remote.assert_not_called()
- mark_skip.assert_not_called()
- captured = capsys.readouterr()
- assert "Skipping upstream setup (non-interactive run)." in captured.out
- assert "official repo not checked" in captured.out
- assert "Already up to date!" not in captured.out
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_current_checkout_runtime_verification_failure_is_durable(
- self,
- mock_run,
- _mock_which,
- mock_args,
- ):
- """Prepared products must still pass runtime and durable outcome checks."""
- from hermes_cli import main as hm
- from hermes_cli import update_cmd
-
- mock_args.gateway = True
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="0"
- )
-
- with patch.object(
- hm,
- "_get_origin_url",
- return_value="https://github.com/example/hermes-agent.git",
- ), patch.object(hm, "_sync_with_upstream_if_needed"), patch.object(
- update_cmd,
- "_post_update_sqlite_runtime_status",
- return_value=(False, SimpleNamespace(sqlite_version_string="3.46.1")),
- ) as runtime_check, patch.object(
- update_cmd, "_write_gateway_update_exit_code"
- ) as write_gateway_exit, patch(
- "hermes_cli.update_receipt.finalize_update_receipt"
- ) as finalize_receipt, patch(
- "hermes_cli.update_receipt.finalize_pending_update_receipt"
- ):
- with pytest.raises(SystemExit) as exit_info:
- cmd_update(mock_args)
-
- assert exit_info.value.code == 1
- runtime_check.assert_called_once_with()
- write_gateway_exit.assert_called_once_with(False)
- assert finalize_receipt.call_args.args[0] == "partial"
-
@patch("shutil.which", return_value=None)
@patch("subprocess.run")
def test_fork_upstream_sync_that_moves_head_runs_post_update_steps(
@@ -226,572 +103,6 @@ class TestCmdUpdateBranchFallback:
captured = capsys.readouterr()
assert "Already up to date!" not in captured.out
- def test_update_non_interactive_runs_safe_config_migrations(self, mock_args, capsys):
- """Dashboard/web updates apply non-interactive migrations before restart."""
- with patch("shutil.which", return_value=None), patch(
- "subprocess.run"
- ) as mock_run, patch("builtins.input") as mock_input, patch(
- "hermes_cli.config.get_missing_env_vars", return_value=["MISSING_KEY"]
- ), patch(
- "hermes_cli.config.get_missing_config_fields",
- return_value=[{"key": "new.option", "default": True}],
- ), patch(
- "hermes_cli.update_cmd._reload_config_modules"
- ), patch(
- "hermes_cli.config.check_config_version", return_value=(1, 2)
- ), patch(
- "hermes_cli.config.migrate_config",
- return_value={"env_added": [], "config_added": ["new.option"]},
- ) as migrate_config, patch("hermes_cli.main.sys") as mock_sys:
- mock_sys.stdin.isatty.return_value = False
- mock_sys.stdout.isatty.return_value = False
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- cmd_update(mock_args)
-
- mock_input.assert_not_called()
- migrate_config.assert_called_once_with(interactive=False, quiet=False)
- captured = capsys.readouterr()
- assert "applying safe config migrations" in captured.out
- assert "API keys require manual entry" in captured.out
-
-
-class TestCmdUpdateMigrationPrompt:
- """The config-migration prompt names what changed and skips the prompt
- entirely when only the config format version moved.
-
- Regression guard for the contentless-prompt report (ScottFive / Tt2021):
- previously the prompt printed only counts ("1 new config option") and
- asked "configure them now?" even for pure version bumps, where saying
- yes looked like a no-op.
- """
-
- def test_version_bump_only_applies_silently_without_prompt(
- self, mock_args, capsys
- ):
- """Only the version moved → apply non-interactively, never prompt."""
- with patch("shutil.which", return_value=None), patch(
- "subprocess.run"
- ) as mock_run, patch("builtins.input") as mock_input, patch(
- "hermes_cli.config.get_missing_env_vars", return_value=[]
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=[]
- ), patch(
- "hermes_cli.update_cmd._reload_config_modules"
- ), patch(
- "hermes_cli.config.check_config_version", return_value=(5, 24)
- ), patch(
- "hermes_cli.config.migrate_config",
- return_value={"env_added": [], "config_added": [], "warnings": []},
- ) as mock_migrate:
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- cmd_update(mock_args)
-
- mock_input.assert_not_called()
- mock_migrate.assert_called_once_with(interactive=False, quiet=True)
- out = capsys.readouterr().out
- assert "Updating config format (v5 → v24)" in out
- assert "no new settings to configure" in out
- # The misleading question must NOT appear for a pure version bump.
- assert "configure them now" not in out.lower()
-
- def test_version_bump_only_surfaces_migration_resets(
- self, mock_args, capsys
- ):
- """A quiet version-bump migration that RESETS a user setting must say so.
-
- Regression for #86656: the v33→v34 personality reset ran with
- quiet=True and its results dict was discarded, so the update printed
- "no new settings to configure" while silently wiping
- display.personality. Migration-step mutations (config_added) and
- warnings must be re-surfaced even in the silent branch.
- """
- with patch("shutil.which", return_value=None), patch(
- "subprocess.run"
- ) as mock_run, patch("builtins.input") as mock_input, patch(
- "hermes_cli.config.get_missing_env_vars", return_value=[]
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=[]
- ), patch(
- "hermes_cli.update_cmd._reload_config_modules"
- ), patch(
- "hermes_cli.config.check_config_version", return_value=(33, 34)
- ), patch(
- "hermes_cli.config.migrate_config",
- return_value={
- "env_added": [],
- "config_added": ["display.personality=none (one-time reset)"],
- "warnings": ["Disabled suspicious MCP server 'evil'"],
- },
- ):
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- cmd_update(mock_args)
-
- mock_input.assert_not_called()
- out = capsys.readouterr().out
- assert "Updating config format (v33 → v34)" in out
- assert "no new settings to configure" in out
- # The migration's mutation note and warning must NOT be swallowed.
- assert "display.personality=none (one-time reset)" in out
- assert "Disabled suspicious MCP server 'evil'" in out
-
- def test_new_options_are_listed_by_name_before_prompt(
- self, mock_args, capsys
- ):
- """New env/config keys are printed by name so the user can decide."""
- env_items = [
- {"name": "FOO_API_KEY", "description": "Foo service API key"},
- ]
- cfg_items = [
- {"key": "display.new_widget", "description": "New config option: display.new_widget"},
- ]
- with patch("shutil.which", return_value=None), patch(
- "subprocess.run"
- ) as mock_run, patch("builtins.input", return_value="n"), patch(
- "hermes_cli.config.get_missing_env_vars", return_value=env_items
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=cfg_items
- ), patch(
- "hermes_cli.update_cmd._reload_config_modules"
- ), patch(
- "hermes_cli.config.check_config_version", return_value=(1, 24)
- ), patch(
- "hermes_cli.config.migrate_config",
- return_value={"env_added": [], "config_added": [], "warnings": []},
- ), patch("hermes_cli.main.sys") as mock_sys:
- mock_sys.stdin.isatty.return_value = True
- mock_sys.stdout.isatty.return_value = True
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- cmd_update(mock_args)
-
- out = capsys.readouterr().out
- # Names, not just counts.
- assert "FOO_API_KEY" in out
- assert "Foo service API key" in out
- assert "display.new_widget" in out
-
-
-
-
-class TestCmdUpdateProfileSkillSync:
- """cmd_update syncs bundled skills to all profiles, including the active one.
-
- Regression guard for #16176: previously the active profile was excluded
- from the seed_profile_skills loop, leaving it on stale skill content.
- """
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_active_profile_included_in_skill_sync(
- self, mock_run, _mock_which, mock_args, capsys
- ):
- from pathlib import Path
-
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes"))
- active_p = SimpleNamespace(name="bit", path=Path("/fake/.hermes/profiles/bit"))
- other_p = SimpleNamespace(name="work", path=Path("/fake/.hermes/profiles/work"))
- all_profiles = [default_p, active_p, other_p]
-
- synced_paths = []
-
- def fake_seed(path, quiet=False):
- synced_paths.append(path)
- return {"copied": [], "updated": [], "user_modified": []}
-
- empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []}
-
- with (
- patch("hermes_cli.profiles.list_profiles", return_value=all_profiles),
- patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),
- patch("tools.skills_sync.sync_skills", return_value=empty_sync),
- ):
- cmd_update(mock_args)
-
- assert active_p.path in synced_paths, (
- f"Active profile 'bit' must be included in skill sync; got: {synced_paths}"
- )
- assert set(synced_paths) == {p.path for p in all_profiles}, (
- f"All profiles must be synced; got: {synced_paths}"
- )
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_single_profile_default_is_synced(
- self, mock_run, _mock_which, mock_args, capsys
- ):
- from pathlib import Path
-
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes"))
- synced_paths = []
-
- def fake_seed(path, quiet=False):
- synced_paths.append(path)
- return {"copied": [], "updated": [], "user_modified": []}
-
- empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []}
-
- with (
- patch("hermes_cli.profiles.list_profiles", return_value=[default_p]),
- patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),
- patch("tools.skills_sync.sync_skills", return_value=empty_sync),
- ):
- cmd_update(mock_args)
-
- assert default_p.path in synced_paths
-
-
-class TestCmdUpdateBranchFlag:
- """``hermes update --branch <name>`` targets the requested branch.
-
- The CLI default stays 'main'; --branch lets callers pick a different
- target without monkey-patching the implementation.
- """
-
- def _branch_side_effect(self, current_branch, target_branch, *, checkout_fails=False, track_fails=False, commit_count="0"):
- """Mock side-effect that knows about checkout/track behavior.
-
- - ``current_branch`` what ``git rev-parse --abbrev-ref HEAD`` returns
- - ``target_branch`` passed via --branch; what we expect the code to switch to
- - ``checkout_fails`` if True, ``git checkout <target>`` returns non-zero
- (simulates branch absent locally; code should retry with -B)
- - ``track_fails`` if True, ``git checkout -B <target> origin/<target>`` ALSO fails
- (simulates branch absent on origin too)
- - ``commit_count`` rev-list count returned (0 = up-to-date, >0 = behind)
- """
-
- def side_effect(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
-
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout=f"{current_branch}\n", stderr="")
-
- if "checkout" in joined and "-B" in joined:
- rc = 128 if track_fails else 0
- err = f"fatal: '{target_branch}' did not match any file(s) known to git\n" if track_fails else ""
- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err)
-
- if "checkout" in joined and "-B" not in joined and "rev-parse" not in joined:
- rc = 128 if checkout_fails else 0
- err = f"error: pathspec '{target_branch}' did not match\n" if checkout_fails else ""
- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err)
-
- if "rev-list" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="")
-
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
-
- return side_effect
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_branch_flag_pulls_against_named_branch(self, mock_run, _mock_which, capsys):
- """--branch bb/gui makes rev-list and pull target origin/bb/gui."""
- mock_run.side_effect = self._branch_side_effect(
- current_branch="bb/gui", target_branch="bb/gui", commit_count="3"
- )
- args = SimpleNamespace(branch="bb/gui")
-
- cmd_update(args)
-
- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]
-
- # rev-list must compare against origin/bb/gui, not origin/main
- rev_list_cmds = [c for c in commands if "rev-list" in c]
- assert any("origin/bb/gui" in c for c in rev_list_cmds), rev_list_cmds
- assert not any("origin/main" in c for c in rev_list_cmds), rev_list_cmds
-
- # the ff-only merge must target origin/bb/gui
- merge_cmds = [c for c in commands if "merge --ff-only" in c]
- assert any("origin/bb/gui" in c and "origin/main" not in c for c in merge_cmds), merge_cmds
-
-
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_branch_flag_fails_when_branch_missing_everywhere(self, mock_run, _mock_which, capsys):
- """If branch doesn't exist locally OR on origin, exit non-zero with clear error."""
- mock_run.side_effect = self._branch_side_effect(
- current_branch="main",
- target_branch="nonexistent",
- checkout_fails=True,
- track_fails=True,
- commit_count="0",
- )
- args = SimpleNamespace(branch="nonexistent")
-
- with pytest.raises(SystemExit) as exc_info:
- cmd_update(args)
- assert exc_info.value.code == 1
-
- out = capsys.readouterr().out
- assert "does not exist locally or on origin" in out
- assert "nonexistent" in out
-
-
-class TestCmdUpdateCheckBranchFlag:
- """``hermes update --check --branch <name>`` honors the branch override.
-
- The check path used to call ``git rev-list HEAD..origin/<branch> --count``
- with ``check=True``. When the branch didn't exist on origin, the fetch
- silently succeeded (no refspec) but rev-list exited 128 and a raw
- ``CalledProcessError`` propagated to the user. These tests pin the
- friendlier behavior: detect-the-missing-ref before rev-list, exit 1
- with a clear message.
- """
-
- def _check_side_effect(
- self,
- target_branch: str,
- *,
- verify_ok: bool = True,
- commit_count: str = "0",
- upstream_fetch_ok: bool = True,
- ):
- """Mock side-effect for the _cmd_update_check git pipeline.
-
- - ``target_branch`` what we expect compare ref to point at
- - ``verify_ok`` if False, ``git rev-parse --verify --quiet
- origin/<branch>`` fails (branch missing
- on origin)
- - ``commit_count`` rev-list count (0 = up-to-date)
- - ``upstream_fetch_ok`` if False, ``git fetch upstream`` fails
- (forces fallback to origin on branch==main)
- """
-
- def side_effect(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
-
- if "fetch" in joined and "upstream" in joined:
- rc = 0 if upstream_fetch_ok else 128
- err = "" if upstream_fetch_ok else "fatal: 'upstream' does not appear to be a git repository\n"
- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err)
-
- if "fetch" in joined and "origin" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
-
- if "rev-parse" in joined and "--verify" in joined:
- rc = 0 if verify_ok else 1
- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr="")
-
- if "rev-list" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="")
-
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
-
- return side_effect
-
- @patch("hermes_cli.config.detect_install_method", return_value="git")
- @patch("subprocess.run")
- def test_check_branch_compares_against_named_origin_branch(
- self, mock_run, _mock_method, capsys
- ):
- """--check --branch bb/gui compares against origin/bb/gui, never origin/main."""
- mock_run.side_effect = self._check_side_effect(
- target_branch="bb/gui", verify_ok=True, commit_count="2"
- )
- args = SimpleNamespace(check=True, branch="bb/gui")
-
- cmd_update(args)
-
- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]
- # Non-main branch skips upstream probe entirely.
- assert not any("fetch" in c and "upstream" in c for c in commands), commands
- # Verify and rev-list both target origin/bb/gui.
- verify_cmds = [c for c in commands if "rev-parse" in c and "--verify" in c]
- assert any("origin/bb/gui" in c for c in verify_cmds), verify_cmds
- rev_list_cmds = [c for c in commands if "rev-list" in c]
- assert any("origin/bb/gui" in c for c in rev_list_cmds), rev_list_cmds
- assert not any("origin/main" in c for c in rev_list_cmds), rev_list_cmds
-
- @patch("hermes_cli.config.detect_install_method", return_value="git")
- @patch("subprocess.run")
- def test_check_branch_missing_on_origin_exits_cleanly(
- self, mock_run, _mock_method, capsys
- ):
- """If origin/<branch> doesn't exist, surface a friendly error and exit 1.
-
- Pre-fix this case raised CalledProcessError from rev-list's check=True
- and dumped a Python traceback to stdout.
- """
- mock_run.side_effect = self._check_side_effect(
- target_branch="ghost", verify_ok=False
- )
- args = SimpleNamespace(check=True, branch="ghost")
-
- with pytest.raises(SystemExit) as exc_info:
- cmd_update(args)
- assert exc_info.value.code == 1
-
- out = capsys.readouterr().out
- # No raw Python traceback.
- assert "Traceback" not in out
- assert "CalledProcessError" not in out
- # Friendly message naming the branch.
- assert "ghost" in out
- assert "not found" in out
-
- # rev-list must never have been called once verify failed.
- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]
- assert not any("rev-list" in c for c in commands), commands
-
- @patch("hermes_cli.config.detect_install_method", return_value="git")
- @patch("subprocess.run")
- def test_check_default_main_still_prefers_upstream(
- self, mock_run, _mock_method, capsys
- ):
- """No --branch (or --branch=None) preserves the upstream-then-origin probe."""
- mock_run.side_effect = self._check_side_effect(
- target_branch="main", verify_ok=True, commit_count="0"
- )
- args = SimpleNamespace(check=True, branch=None)
-
- cmd_update(args)
-
- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]
- # Should have tried upstream first.
- assert any("fetch" in c and "upstream" in c for c in commands), commands
- # Compare ref is upstream/main (upstream fetch succeeded).
- rev_list_cmds = [c for c in commands if "rev-list" in c]
- assert any("upstream/main" in c for c in rev_list_cmds), rev_list_cmds
-
-
-class TestCmdUpdateZipBranchRefusal:
- """``hermes update --branch=<non-main>`` must refuse on the ZIP fallback path.
-
- The ZIP fallback hard-codes a GitHub archive URL for main.zip; honoring
- --branch arbitrarily would require remote-branch existence checks the
- fallback can't easily do. Refusing is the right move — silently lying
- about which branch got installed is the bug --branch was meant to prevent.
- """
-
- def test_zip_fallback_refuses_non_main_branch(self, capsys):
- from hermes_cli.update_cmd_zip import _update_via_zip
-
- args = SimpleNamespace(branch="bb/gui")
- with pytest.raises(SystemExit) as exc_info:
- _update_via_zip(args, completion_request={})
- assert exc_info.value.code == 1
-
- out = capsys.readouterr().out
- assert "bb/gui" in out
- assert "not supported" in out
- # No actual download attempted.
- assert "Downloading latest version" not in out
-
-
-class TestZipDesktopPreservation:
- def test_git_failure_zip_fallback_preserves_desktop(self, tmp_path, monkeypatch):
- """The Windows ZIP fallback keeps Desktop intact when replacing ``apps/``.
-
- The built app survives the source swap and preparation retains the
- pre-update desktop selection (#70337/#87331).
- """
- import zipfile
- from pathlib import Path
-
- from hermes_cli import main as hm
- from hermes_cli import update_cmd
- from hermes_cli import update_cmd_maint, update_cmd_zip
-
- project_root = tmp_path / "hermes-agent"
- (project_root / ".git").mkdir(parents=True)
- desktop_dir = project_root / "apps" / "desktop"
- packaged_exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"
- packaged_exe.parent.mkdir(parents=True)
- packaged_exe.write_bytes(b"desktop")
-
- def write_source_zip(_url, destination):
- with zipfile.ZipFile(destination, "w") as archive:
- archive.writestr("hermes-agent-main/apps/desktop/package.json", "{}")
-
- def fail_git_fetch(command, **_kwargs):
- if "fetch" in command:
- raise subprocess.CalledProcessError(1, command)
- return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
-
- preparations = []
-
- def prepare_checkout(request):
- preparations.append((Path(request["source"]), request["desktop"], packaged_exe.read_bytes()))
-
- monkeypatch.setattr(hm, "PROJECT_ROOT", project_root)
- monkeypatch.setattr(hm, "_is_windows", lambda: True)
- monkeypatch.setattr(hm, "_run_pre_update_backup", lambda _args: None)
- monkeypatch.setattr(hm, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(hm, "_get_origin_url", lambda *_args: "")
- monkeypatch.setattr(
- hm,
- "_desktop_packaged_executable",
- lambda _desktop_dir: packaged_exe if packaged_exe.exists() else None,
- )
- monkeypatch.setattr(hm, "_desktop_dist_exists", lambda _desktop_dir: False)
- monkeypatch.setattr(update_cmd, "_complete_source_update", prepare_checkout)
- monkeypatch.setattr(hm, "_clear_bytecode_cache", lambda *_args: 0)
- monkeypatch.setattr(hm, "_record_bytecode_fingerprint", lambda: None)
- monkeypatch.setattr(hm, "_refresh_bootstrap_cache_scripts", lambda _branch: None)
-
- monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *_args: None)
- monkeypatch.setattr(update_cmd, "_normalize_managed_eol", lambda *_args: None)
- monkeypatch.setattr(
- update_cmd,
- "_validate_critical_modules_import",
- lambda *_args: (True, None, None),
- )
-
- monkeypatch.setattr(update_cmd, "_print_curator_first_run_notice", lambda: None)
- monkeypatch.setattr(update_cmd, "_print_curator_recent_run_notice", lambda: None)
- monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda **kwargs: None)
- monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: tmp_path / "hermes-home")
-
- with (
- patch("hermes_cli.config.load_config", return_value={}),
- # This test legitimately exercises the real ZIP fallback; undo the
- # module autouse fixture's fail-fast tripwire for exactly this run.
- patch(
- "hermes_cli.update_cmd._update_via_zip",
- update_cmd_zip._update_via_zip,
- ),
- patch("subprocess.run", side_effect=fail_git_fetch),
- patch("urllib.request.urlretrieve", side_effect=write_source_zip),
- patch(
- "tools.skills_sync.sync_skills",
- return_value={
- "copied": [],
- "updated": [],
- "user_modified": [],
- "cleaned": [],
- "relocated": [],
- },
- ),
- patch("hermes_cli.model_catalog.seed_cache_from_checkout", return_value=False),
- ):
- update_cmd._cmd_update_impl(
- SimpleNamespace(yes=True, force=True, force_venv=True, branch=None),
- gateway_mode=False,
- )
-
- assert preparations == [(project_root, True, b"desktop")]
- assert packaged_exe.exists()
- assert packaged_exe.read_bytes() == b"desktop"
-
class TestGitTrampolineSelfHeal:
"""Proactive Git-for-Windows trampoline self-heal (#87876).
diff --git a/tests/hermes_cli/test_data_uninstall.py b/tests/hermes_cli/test_data_uninstall.py
index fc0edcb8e68..bc4920cf006 100644
--- a/tests/hermes_cli/test_data_uninstall.py
+++ b/tests/hermes_cli/test_data_uninstall.py
@@ -24,7 +24,8 @@ def layout(tmp_path, monkeypatch):
for path in witnesses:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("keep", encoding="utf-8")
- data = [home / "config.yaml", home / "sessions" / "session.json", home / "workspace" / "notes.txt"]
+ data = [home / "config.yaml", home / "sessions" / "session.json", home / "workspace" / "notes.txt",
+ home / ".env", home / "logs" / "file"]
for path in data:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("{}" if path.suffix in {".yaml", ".json"} else "user data", encoding="utf-8")
diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.py
index ba74f5512f3..bf25c1407bd 100644
--- a/tests/hermes_cli/test_doctor.py
+++ b/tests/hermes_cli/test_doctor.py
@@ -318,8 +318,6 @@ class TestDoctorToolAvailabilityOverrides:
assert unavailable == [kanban_entry]
-
-
class TestHonchoDoctorConfigDetection:
def test_reports_configured_when_enabled_with_api_key(self, monkeypatch):
fake_config = SimpleNamespace(enabled=True, api_key="***")
@@ -332,12 +330,6 @@ class TestHonchoDoctorConfigDetection:
assert doctor_state._honcho_is_configured_for_doctor()
-
-
-
-
-
-
def test_doctor_reports_vercel_backend_diagnostics(monkeypatch, tmp_path):
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", "python3.13")
@@ -766,8 +758,6 @@ def test_run_doctor_accepts_vendor_slugs_for_named_custom_provider(monkeypatch,
assert "Either set model.provider to 'openrouter', or drop the vendor prefix." not in out
-
-
def test_run_doctor_accepts_kimi_coding_cn_provider(monkeypatch, tmp_path):
home = tmp_path / ".hermes"
home.mkdir(parents=True, exist_ok=True)
@@ -1496,15 +1486,12 @@ class TestDoctorStaleMaxIterationsDrift:
assert "shadows" not in out
-
-
class TestDoctorDeprecatedConfigAndEnv:
"""Doctor must surface deprecated/legacy config keys and env vars with
modern replacements as non-failing warnings — without auto-migrating.
"""
-
def test_collect_deprecated_env_vars_ignores_empty(self):
assert doctor_config.collect_deprecated_env_vars({"TERMINAL_CWD": " "}) == []
assert doctor_config.collect_deprecated_env_vars({}) == []
@@ -1558,8 +1545,6 @@ class TestDoctorDeprecatedConfigAndEnv:
return buf.getvalue(), hermes_home
-
-
def test_report_does_not_count_as_blocking_issue(self, monkeypatch, tmp_path, capsys):
"""report_deprecated_config_and_env is warn-only — no issues list mutation."""
findings = doctor_config.report_deprecated_config_and_env(
@@ -1740,17 +1725,6 @@ class TestStagedRuntimeVenv:
# --- _staged_venv_dir: pm authority + provisioned-venv marker ---
- def test_staged_venv_dir_returns_provisioned_venv(self, tmp_path, monkeypatch):
- import pm.packages as pm_packages
-
- venv = tmp_path / "venv"
- venv.mkdir()
- (venv / "pyvenv.cfg").write_text("home = /usr\n", encoding="utf-8")
- self._stub_venv(monkeypatch, venv)
-
- assert doctor_platform._staged_venv_dir() == venv
- # Sanity: the stub really replaced pm's own Venv (no real-repo read).
- assert pm_packages.Venv is not None
def test_resolved_path_without_venv_marker_is_not_staged(self, tmp_path, monkeypatch):
empty = tmp_path / "venv"
@@ -1770,45 +1744,6 @@ class TestStagedRuntimeVenv:
# --- the check's staged-vs-active rows ---
- def test_staged_but_not_active_reports_staged_dependencies(self, monkeypatch, capsys):
- monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: Path("/payload/venv"))
- monkeypatch.setattr(doctor_platform.sys, "prefix", "/usr")
- monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr")
-
- doctor_platform._check_python_environment(False)
-
- out = capsys.readouterr().out
- assert "Runtime venv staged" in out
- assert "runs outside it" in out
- assert "Not in virtual environment" not in out # dependencies exist; no false alarm
-
- def test_unrelated_active_venv_is_not_claimed_as_the_staged_one(self, monkeypatch, capsys):
- """A process running in some OTHER venv must not be labeled active-in
- the staged one: the comparison is resolved prefix vs staged dir."""
- monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: Path("/payload/venv"))
- monkeypatch.setattr(doctor_platform.sys, "prefix", "/some/other/venv")
- monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr")
-
- doctor_platform._check_python_environment(False)
-
- out = capsys.readouterr().out
- assert "Runtime venv staged" in out
- assert "runs outside it" in out
- assert "active in this process" not in out
-
- def test_staged_and_active_names_both_facts(self, monkeypatch, capsys, tmp_path):
- from hermes_cli.runtime_paths import site_packages
-
- staged = tmp_path / "venv"
- site_packages(staged).mkdir(parents=True)
- monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: staged)
- monkeypatch.syspath_prepend(str(site_packages(staged)))
-
- doctor_platform._check_python_environment(False)
-
- out = capsys.readouterr().out
- assert "Runtime venv staged" in out
- assert "active in this process" in out
def test_nothing_staged_keeps_legacy_interpreter_probe(self, monkeypatch, capsys):
monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: None)
diff --git a/tests/hermes_cli/test_doctor_update_provenance.py b/tests/hermes_cli/test_doctor_update_provenance.py
index d61c6a15980..c673f7f9a81 100644
--- a/tests/hermes_cli/test_doctor_update_provenance.py
+++ b/tests/hermes_cli/test_doctor_update_provenance.py
@@ -45,52 +45,30 @@ def test_no_plugins_dir_is_info(tmp_path):
assert rows == [("info", "No plugins directory yet (nothing to check provenance for)", "")]
-def test_drift_plugin_warns_with_reinstall_remedy(tmp_path):
- _make_plugin(tmp_path, "drifty", sidecar={"source": "git", "update_url": "https://example.com/x"})
- rows = ds._plugin_provenance_rows(tmp_path)
- warns = [r for r in rows if r[0] == "warn"]
- assert len(warns) == 1
- assert "'drifty'" in warns[0][1] and "drift" in warns[0][1]
- assert "reinstall" in str(warns[0])
-
-
-def test_manual_and_self_cloned_are_info(tmp_path):
- _make_plugin(tmp_path, "dropped")
- _make_plugin(tmp_path, "cloned", git=True)
- rows = ds._plugin_provenance_rows(tmp_path)
- assert any("manually" in text and kind == "info" for kind, text, _ in rows)
- assert any("'cloned'" in text and "adopt" in detail for kind, text, detail in rows if kind == "info")
- assert not any(kind == "warn" for kind, _, _ in rows)
-
-
-def test_git_plugin_in_good_standing_is_ok(tmp_path):
- _make_plugin(
- tmp_path, "fine",
- sidecar={"source": "git", "update_url": "https://example.com/x"},
- git=True, manifest_update_url="https://example.com/x",
- )
- rows = ds._plugin_provenance_rows(tmp_path)
- assert not any(kind == "warn" for kind, _, _ in rows)
- assert any(kind == "ok" and "good standing" in text for kind, text, _ in rows)
-
-
-def test_manifest_url_without_saved_url_warns(tmp_path):
- _make_plugin(tmp_path, "sneaky", sidecar={"source": "git"}, git=True,
- manifest_update_url="https://evil.example/x")
- rows = ds._plugin_provenance_rows(tmp_path)
- warns = [r for r in rows if r[0] == "warn"]
- assert len(warns) == 1
- assert "'sneaky'" in warns[0][1] and "no url was saved" in warns[0][1]
-
-
[email protected]("claimed", [None, "https://evil.example/x"])
-def test_manifest_url_mismatch_warns(tmp_path, claimed):
- _make_plugin(tmp_path, "swapped", sidecar={"source": "git", "update_url": "https://example.com/x"},
- git=True, manifest_update_url=claimed)
- rows = ds._plugin_provenance_rows(tmp_path)
- warns = [r for r in rows if r[0] == "warn"]
- assert len(warns) == 1
- assert "update_url mismatch" in str(warns[0])
+def test_mixed_provenance_diagnostic_is_read_only(tmp_path, monkeypatch, capsys):
+ plugins = tmp_path / 'plugins'
+ url = 'https://example.com/x'
+ cases = [
+ ('drifty', {'source': 'git', 'update_url': url}, False, None, 'warn', 'reinstall'),
+ ('dropped', None, False, None, 'info', 'manually'),
+ ('cloned', None, True, None, 'info', 'adopt'),
+ ('fine', {'source': 'git', 'update_url': url}, True, url, 'ok', 'good standing'),
+ ('sneaky', {'source': 'git'}, True, 'https://evil.example/x', 'warn', 'no url was saved'),
+ ('swapped', {'source': 'git', 'update_url': url}, True, 'https://evil.example/x', 'warn', 'update_url mismatch'),
+ ('removed', {'source': 'git', 'update_url': url}, True, None, 'warn', 'update_url mismatch'),
+ ]
+ for name, sidecar, git, manifest, *_ in cases:
+ _make_plugin(plugins, name, sidecar=sidecar, git=git, manifest_update_url=manifest)
+ before = {p: p.read_bytes() for p in plugins.rglob('*') if p.is_file()}
+ rows = ds._plugin_provenance_rows(plugins)
+ for name, *_, severity, remedy in cases:
+ assert any(kind == severity and name in text and remedy in text + detail
+ for kind, text, detail in rows)
+ monkeypatch.setattr('hermes_constants.get_hermes_home', lambda: tmp_path)
+ ds._check_update_provenance(False)
+ output = capsys.readouterr().out
+ assert all(name in output for name, *_ in cases)
+ assert {p: p.read_bytes() for p in plugins.rglob('*') if p.is_file()} == before
# --- doctor-side wiring -------------------------------------------------
diff --git a/tests/hermes_cli/test_dump_git_commit.py b/tests/hermes_cli/test_dump_git_commit.py
index d51c1238f64..e9f57c1ee54 100644
--- a/tests/hermes_cli/test_dump_git_commit.py
+++ b/tests/hermes_cli/test_dump_git_commit.py
@@ -14,6 +14,8 @@ from pathlib import Path
from subprocess import run as _run
from unittest.mock import patch
+import pytest
+
from hermes_cli.version_info import VersionInfo, _reset_version_info_cache
@@ -21,122 +23,21 @@ def setup_function():
_reset_version_info_cache()
-def _patch_running_install(repo_dir):
- """Make the requested repo_dir the running install for the fallback path."""
- return patch("hermes_cli.dump.get_project_root", return_value=repo_dir.resolve())
-
-
-def test_get_git_commit_uses_live_git_when_available(tmp_path):
- """Source install: version_info resolves commit from live git."""
- from hermes_cli import dump
-
- repo_dir = tmp_path / "repo"
- repo_dir.mkdir()
-
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \
- patch("hermes_cli.version_info._git_version_info",
- return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git")):
- commit = dump._get_git_commit(repo_dir)
-
- assert commit == "deadbeef"
-
-
-def test_get_git_commit_uses_stamp_when_no_git(tmp_path):
- """Docker/Nix: version_info resolves commit from the install stamp."""
- from hermes_cli import dump
-
- repo_dir = tmp_path / "no-git-here"
- repo_dir.mkdir()
-
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \
- patch("hermes_cli.version_info._stamp_version_info",
- return_value=VersionInfo("0.19.0", "0.19.0", None, "cafef00d" * 5, None, "docker")):
- commit = dump._get_git_commit(repo_dir)
-
- assert commit == "cafef00d"
-
-
-def test_get_git_commit_returns_unknown_when_neither_source_available(tmp_path):
- """Pip-installed wheel: no stamp, no git → '(unknown)'."""
- from hermes_cli import dump
-
- repo_dir = tmp_path / "repo"
- repo_dir.mkdir()
-
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: None):
- commit = dump._get_git_commit(repo_dir)
-
- assert commit == "(unknown)"
-
-
-def test_get_git_commit_output_format_identical_between_sources(tmp_path):
- """Regression guard: live-git and stamp outputs share the same shape."""
- from hermes_cli import dump
-
- repo_dir = tmp_path / "repo"
- repo_dir.mkdir()
-
- # Live-git path.
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \
- patch("hermes_cli.version_info._git_version_info",
- return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "b2f477a3" * 5, "main", "git")):
- _reset_version_info_cache()
- live = dump._get_git_commit(repo_dir)
-
- # Stamp path.
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \
- patch("hermes_cli.version_info._stamp_version_info",
- return_value=VersionInfo("0.19.0", "0.19.0", None, "b2f477a3" * 5, None, "docker")):
- _reset_version_info_cache()
- baked = dump._get_git_commit(repo_dir)
-
- assert live == baked == "b2f477a3"
- assert len(live) == 8
- assert all(c in "0123456789abcdef" for c in live)
-
-
-def test_get_git_commit_date_uses_version_info(tmp_path):
- """Source install: version_info carries the commit date from live git."""
- from hermes_cli import dump
-
- repo_dir = tmp_path / "repo"
- repo_dir.mkdir()
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \
- patch("hermes_cli.version_info._git_version_info",
- return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git", False, 1718662620)):
- _reset_version_info_cache()
- date = dump._get_git_commit_date(repo_dir)
- assert date == "2024-06-17"
-
-def test_get_git_commit_date_empty_when_unknown(tmp_path):
- """Docker/pip: no git, no stamp → '' so the dump line drops the date."""
[email protected]('sha,timestamp,expected,date', [
+ ('cafef00d' * 5, 1718662620, 'cafef00d', '2024-06-17'),
+ (None, None, '(unknown)', ''),
+])
+def test_dump_uses_running_install_fallback_only(tmp_path, monkeypatch, sha, timestamp, expected, date):
from hermes_cli import dump
- repo_dir = tmp_path / "no-git-here"
- repo_dir.mkdir()
-
- with _patch_running_install(repo_dir), \
- patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \
- patch("hermes_cli.version_info._resolve_repo_dir", lambda: None):
- _reset_version_info_cache()
- date = dump._get_git_commit_date(repo_dir)
-
- assert date == ""
+ monkeypatch.setattr(dump, 'get_project_root', lambda: tmp_path)
+ info = VersionInfo('1.0', '1.0', None, sha, None, 'docker', False, timestamp)
+ monkeypatch.setattr('hermes_cli.version_info.get_version_info', lambda: info)
+ assert dump._get_git_commit(tmp_path) == expected
+ assert dump._get_git_commit_date(tmp_path) == date
# --------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index d1f51a244a1..2f161b99248 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -118,7 +118,6 @@ def _staging_dir_from(cmd) -> Path:
raise AssertionError(f"no staging output override in {cmd!r}")
-
def _packaged_exe_rel() -> Path:
"""Packaged-exe path relative to electron-builder's output dir on THIS host."""
if sys.platform == "darwin":
@@ -128,7 +127,6 @@ def _packaged_exe_rel() -> Path:
return Path("linux-unpacked") / "hermes"
-
def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):
"""``subprocess.run`` side effect mimicking a real ``npm run pack``: lays
the packaged app down inside the STAGING dir named on the command line
@@ -146,81 +144,21 @@ def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):
return _run
-
# Dependency admission and staging are exercised by test_desktop_source_build.py.
-
-
-
-
# ── Content-hash stamp tests ──────────────────────────────────────────
-
-
-
-
-
-
# ── Electron build-cache recovery tests ───────────────────────────────
-
-
-
-
-
-
-
-
-
-
# ── electronDist (re)download helper tests (#47266) ───────────────────
-
-
-
-
-
-
-
-
-
-
-
-
-
-class _FakeProc:
- """Minimal psutil.Process stand-in for the lock-breaker tests."""
-
- def __init__(self, pid: int, exe: str | None):
- self.pid = pid
- self.info = {"pid": pid, "exe": exe}
- self.terminated = False
- self.killed = False
-
- def terminate(self):
- self.terminated = True
-
- def kill(self):
- self.killed = True
-
-
-
-
-
-
-
-
-
-
-
-
# --- macOS TCC-stable local signing (relaunch fixup) -----------------------
@@ -286,8 +224,6 @@ def test_desktop_macos_local_codesign_signs_native_binaries(tmp_path, monkeypatc
assert str(app / "Contents" / "Frameworks" / "chrome_crashpad_handler") in signed
-
-
@pytest.mark.platforms("macos")
def test_relaunchable_fixup_falls_back_to_legacy_adhoc_on_failure(tmp_path, monkeypatch, capsys):
"""A failing stable sign must still leave a launchable (deep ad-hoc) bundle.
@@ -579,8 +515,6 @@ def test_cmd_gui_setup_tcc_identity_exits_before_build(tmp_path, monkeypatch):
mock_install.assert_not_called()
-
-
@pytest.mark.platforms("macos")
def test_relaunchable_fixup_stable_identity_never_touches_keychain(tmp_path, monkeypatch):
"""A successful stable-identity re-sign must NOT delete the safeStorage item.
@@ -747,8 +681,6 @@ def test_relaunchable_fixup_legacy_adhoc_success_still_verifies_and_never_delete
# --- desktop.* launch options (config.yaml) -------------------------------
-
-
# --- Linux launcher entry registration ------------------------------------
@@ -873,49 +805,6 @@ def test_desktop_launch_options_ozone_hint_defaults_auto():
assert main_desktop._desktop_launch_options()[3] == "auto"
-def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
- """COSMIC HUD: ``desktop.ozone_platform_hint: x11`` sets
- ``ELECTRON_OZONE_PLATFORM_HINT`` on the launched Electron process."""
- root = _make_desktop_tree(tmp_path)
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- _make_packaged_executable(root, monkeypatch)
-
- ok = subprocess.CompletedProcess([], 0)
- cfg = {"desktop": {"ozone_platform_hint": "x11"}}
-
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
- patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \
- patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \
- patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \
- patch("hermes_cli.config.load_config", return_value=cfg), \
- patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \
- patch("hermes_cli.main_desktop._detect_linux_password_store", return_value=None), \
- patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \
- pytest.raises(SystemExit):
- cli_main.cmd_gui(_ns())
-
- launch_env = mock_run.call_args_list[-1].kwargs["env"]
- assert launch_env.get("ELECTRON_OZONE_PLATFORM_HINT") == "x11"
-
- monkeypatch.setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland")
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
- patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \
- patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \
- patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \
- patch("hermes_cli.config.load_config", return_value=cfg), \
- patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \
- patch("hermes_cli.main_desktop._detect_linux_password_store", return_value=None), \
- patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run2, \
- pytest.raises(SystemExit):
- cli_main.cmd_gui(_ns())
-
- launch_env = mock_run2.call_args_list[-1].kwargs["env"]
- assert launch_env.get("ELECTRON_OZONE_PLATFORM_HINT") == "wayland"
-
-
# --- desktop.password_store detection & bridging (linux) ------------------
@@ -997,6 +886,30 @@ def test_gui_linux_packaged_launch_bridges_detected_password_store(tmp_path, mon
assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "gnome-libsecret"
[email protected]("explicit,configured,detected,expected", [
+ (None, "auto", "gnome-libsecret", "gnome-libsecret"),
+ (None, "kwallet6", None, "kwallet6"),
+ ("basic", "kwallet6", None, "basic"),
+])
+def test_desktop_environment_precedence(monkeypatch, explicit, configured, detected, expected):
+ _clear_keychain_env(monkeypatch)
+ monkeypatch.delenv('ELECTRON_OZONE_PLATFORM_HINT', raising=False)
+ monkeypatch.setattr('hermes_cli.config.load_config', lambda: {
+ 'desktop': {'password_store': configured, 'ozone_platform_hint': 'x11'}})
+ def detect():
+ assert configured == 'auto' and explicit is None
+ return detected
+ monkeypatch.setattr(main_desktop, '_detect_linux_password_store', detect)
+ if explicit:
+ monkeypatch.setenv('HERMES_DESKTOP_PASSWORD_STORE', explicit)
+ env, _ = main_desktop._desktop_launch_env(_ns())
+ assert env['HERMES_DESKTOP_PASSWORD_STORE'] == expected
+ assert env['ELECTRON_OZONE_PLATFORM_HINT'] == 'x11'
+ monkeypatch.setenv('ELECTRON_OZONE_PLATFORM_HINT', 'wayland')
+ assert main_desktop._desktop_launch_env(_ns())[0]['ELECTRON_OZONE_PLATFORM_HINT'] == 'wayland'
+
+
@pytest.mark.platforms("linux")
def test_gui_linux_source_launch_bridges_detected_password_store(tmp_path, monkeypatch):
_clear_keychain_env(monkeypatch)
@@ -1025,61 +938,6 @@ def test_gui_linux_source_launch_bridges_detected_password_store(tmp_path, monke
assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "kwallet6"
-def test_gui_config_password_store_skips_detection(tmp_path, monkeypatch):
- _clear_keychain_env(monkeypatch)
- root = _make_desktop_tree(tmp_path)
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- _make_packaged_executable(root, monkeypatch)
-
- ok = subprocess.CompletedProcess([], 0)
- cfg = {"desktop": {"password_store": "kwallet6"}}
-
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
- patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \
- patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \
- patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \
- patch("hermes_cli.config.load_config", return_value=cfg), \
- patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \
- patch("hermes_cli.main_desktop._detect_linux_password_store") as mock_detect, \
- patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \
- pytest.raises(SystemExit):
- cli_main.cmd_gui(_ns())
-
- mock_detect.assert_not_called()
- launch_env = mock_run.call_args_list[-1].kwargs["env"]
- assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "kwallet6"
-
-
-def test_gui_explicit_password_store_env_wins_over_config_and_detection(tmp_path, monkeypatch):
- _clear_keychain_env(monkeypatch)
- monkeypatch.setenv("HERMES_DESKTOP_PASSWORD_STORE", "basic")
- root = _make_desktop_tree(tmp_path)
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- _make_packaged_executable(root, monkeypatch)
-
- ok = subprocess.CompletedProcess([], 0)
- cfg = {"desktop": {"password_store": "kwallet6"}}
-
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
- patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \
- patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \
- patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \
- patch("hermes_cli.config.load_config", return_value=cfg), \
- patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \
- patch("hermes_cli.main_desktop._detect_linux_password_store") as mock_detect, \
- patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \
- pytest.raises(SystemExit):
- cli_main.cmd_gui(_ns())
-
- mock_detect.assert_not_called()
- launch_env = mock_run.call_args_list[-1].kwargs["env"]
- assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "basic"
-
-
@pytest.mark.platforms("macos")
def test_gui_password_store_bridge_is_linux_only(tmp_path, monkeypatch):
_clear_keychain_env(monkeypatch)
diff --git a/tests/hermes_cli/test_install_bucket_separation.py b/tests/hermes_cli/test_install_bucket_separation.py
index cf6d4227e9a..849c48427e5 100644
--- a/tests/hermes_cli/test_install_bucket_separation.py
+++ b/tests/hermes_cli/test_install_bucket_separation.py
@@ -13,50 +13,19 @@ import pytest
from hermes_cli.uninstall import remove_legacy_runtime_trees
-class TestRemoveLegacyRuntimeTrees:
- def test_removes_a_pre_split_node_tree(self, tmp_path):
- home = tmp_path / "home"
- (home / "node" / "bin").mkdir(parents=True)
- (home / "node" / "bin" / "node").write_text("#!/bin/sh\n", encoding="utf-8")
-
- removed = remove_legacy_runtime_trees(home)
-
- assert (home / "node") not in [p for p in home.iterdir()]
- assert removed == [home / "node"]
-
- def test_removes_only_the_uv_binary_not_the_whole_bin_dir(self, tmp_path):
- """A user's own scripts live in bin/ — deleting the directory would
- take them with it."""
- home = tmp_path / "home"
- (home / "bin").mkdir(parents=True)
- (home / "bin" / "uv").write_text("#!/bin/sh\n", encoding="utf-8")
- (home / "bin" / "my-script").write_text("#!/bin/sh\n", encoding="utf-8")
-
- removed = remove_legacy_runtime_trees(home)
-
- assert removed == [home / "bin" / "uv"]
- assert (home / "bin").is_dir()
- assert (home / "bin" / "my-script").is_file()
-
- def test_never_touches_profile_state(self, tmp_path):
- home = tmp_path / "home"
- home.mkdir()
- for name in ("config.yaml", "auth.json", "SOUL.md"):
- (home / name).write_text("keep me", encoding="utf-8")
- for name in ("sessions", "skills", "memories", "profiles"):
- (home / name).mkdir()
-
- remove_legacy_runtime_trees(home)
-
- for name in ("config.yaml", "auth.json", "SOUL.md"):
- assert (home / name).is_file(), name
- for name in ("sessions", "skills", "memories", "profiles"):
- assert (home / name).is_dir(), name
-
- def test_no_runtime_trees_is_a_quiet_no_op(self, tmp_path):
- home = tmp_path / "home"
- home.mkdir()
- assert remove_legacy_runtime_trees(home) == []
+def test_legacy_cleanup_removes_only_runtime_bytes_and_is_idempotent(tmp_path):
+ runtime = ('node/bin/node', 'bin/uv', 'bin/uv.exe')
+ user = ('bin/my-script', 'config.yaml', 'auth.json', 'SOUL.md',
+ 'sessions/session', 'skills/demo/SKILL.md', 'memories/MEMORY.md', 'profiles/other/config.yaml')
+ for name in (*runtime, *user):
+ p = tmp_path / name
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(name, encoding='utf-8')
+ removed = remove_legacy_runtime_trees(tmp_path)
+ assert set(removed) == {tmp_path / 'node', tmp_path / 'bin/uv', tmp_path / 'bin/uv.exe'}
+ assert all(not (tmp_path / name).exists() for name in runtime)
+ assert all((tmp_path / name).read_text(encoding='utf-8') == name for name in user)
+ assert remove_legacy_runtime_trees(tmp_path) == []
class TestProfileCopyExclusions:
diff --git a/tests/hermes_cli/test_local_models_routes.py b/tests/hermes_cli/test_local_models_routes.py
index f75f6698bec..987320b3d9b 100644
--- a/tests/hermes_cli/test_local_models_routes.py
+++ b/tests/hermes_cli/test_local_models_routes.py
@@ -232,17 +232,24 @@ def test_download_unknown_model_404s(client):
assert r.status_code == 404
-def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatch):
+def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatch, tmp_path):
"""Catalog sizes are advisory (upstream re-uploads may make them
stale — a mismatch against the CATALOG must not fail a download).
The server's own declared length is the only completeness check:
fewer bytes than the server promised means a dropped connection, so
the job errors and nothing is staged."""
- # Body is 17 bytes; the server promises 32 — a truncated stream.
- monkeypatch.setattr(
- "pm.downloader._OPENER",
- _FakeRangeOpener(b"not the real body", content_length=32))
+ from hermes_cli.web_routers import local_models as lm
+ from hermes_cli.local_runtime.bootstrap import models_dir
+ requests = []
+ class Truncated(_FakeRangeOpener):
+ def open(self, req, timeout=None):
+ requests.append(req.headers.get('Range'))
+ return super().open(req, timeout)
+ monkeypatch.setattr("pm.downloader._OPENER", Truncated(b"not the real body", content_length=32))
+ destination = models_dir() / 'truncated.gguf'
+ monkeypatch.setattr(lm, '_download_plan', lambda *_: [('https://fixture.invalid/model', destination, 32)])
+ monkeypatch.setattr('pm.paths.partials_root', lambda: tmp_path / 'partials')
# Pin a generous budget: variant selection prices against the machine
# running the test, and a GPU-less CI runner honestly refuses every
@@ -271,12 +278,11 @@ def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatc
break
time.sleep(0.05)
assert status is not None and status["status"] == "error"
- assert "range body ended before its declared bounds" in status["error"]
-
- from hermes_cli.local_runtime.bootstrap import models_dir
-
- assert not (models_dir() / f"{entry_id}.gguf").exists()
- assert not (models_dir() / f"{entry_id}.part").exists()
+ assert 'bytes=0-0' in requests and any(value != 'bytes=0-0' for value in requests)
+ assert 'IncompleteRead' in status['error']
+ assert not destination.exists()
+ assert job_id not in lm._RUNNING
+ assert not list(models_dir().glob('*.part'))
def test_download_already_downloaded_short_circuits(client, monkeypatch):
@@ -398,111 +404,6 @@ def test_download_pause_and_resume_unknown_404(client):
json={"job_id": "deadbeef"}).status_code == 404
-def test_download_finished_job_releases_handles(client, monkeypatch):
- """A finished download drops its live download + resume handles, so the
- job dict stays JSON-serializable and nothing lingers to pause/resume."""
- body = b"x" * 48
-
- monkeypatch.setattr("pm.downloader._OPENER", _FakeRangeOpener(body))
- from hermes_cli.local_runtime.estimator import HardwareBudget
-
- budget = HardwareBudget(usable_vram_bytes=64 << 30,
- total_device_bytes=64 << 30,
- ram_available_bytes=64 << 30)
- monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
- lambda **kw: budget)
- monkeypatch.setattr(
- "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",
- lambda: False)
- from hermes_cli.local_runtime.catalog import CATALOG
-
- r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id})
- job_id = r.json()["job_id"]
- deadline = time.time() + 10
- status = None
- while time.time() < deadline:
- status = client.get(f"/api/local-models/jobs/{job_id}").json()
- if status["status"] in ("done", "error"):
- break
- time.sleep(0.05)
- assert status is not None and status["status"] == "done"
-
- from hermes_cli.web_routers import local_models as lm
-
- assert job_id not in lm._RUNNING
-
-
-def test_download_pause_reaches_paused_status(client, monkeypatch):
- """A running download can be paused; the job lands in a 'paused' state
- (partials preserved for resume) instead of erroring."""
- import threading
-
- gate = threading.Event()
-
- class _BlockingOpener:
- """Stands in for pm.downloader._OPENER: the probe answers honestly
- (1 MiB, range-supported) and every body read blocks on the gate, so
- the worker is mid-download when the test pauses it."""
-
- def open(self, req, timeout=None):
- rng = req.headers.get("Range") if req.headers else None
- if rng == "bytes=0-0":
- return _FakeRangeOpener(b"x" * 1048576).open(req, timeout=timeout)
-
- class _Resp(io.BytesIO):
- status = 206
- headers = {"Content-Range": "bytes 0-1048575/1048576",
- "Content-Length": "1048576",
- "ETag": '"' + hashlib.sha256(b"x" * 1048576).hexdigest() + '"'}
-
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- def read(self, size=-1):
- gate.wait(timeout=15) # hold the worker until let go
- return super().read(size)
-
- return _Resp(b"x" * 1048576)
-
- monkeypatch.setattr("pm.downloader._OPENER", _BlockingOpener())
- from hermes_cli.local_runtime.catalog import CATALOG
- from hermes_cli.local_runtime.estimator import HardwareBudget
-
- budget = HardwareBudget(usable_vram_bytes=64 << 30,
- total_device_bytes=64 << 30,
- ram_available_bytes=64 << 30)
- monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
- lambda **kw: budget)
-
- r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id})
- job_id = r.json()["job_id"]
-
- # Pause as soon as the live download handle is in place (idempotent).
- deadline = time.time() + 10
- paused = False
- while time.time() < deadline:
- pr = client.post("/api/local-models/download/pause",
- json={"job_id": job_id})
- if pr.status_code == 200 and pr.json()["paused"] is True:
- paused = True
- break
- time.sleep(0.05)
- assert paused
- gate.set()
-
- deadline = time.time() + 10
- status = None
- while time.time() < deadline:
- status = client.get(f"/api/local-models/jobs/{job_id}").json()
- if status["status"] in ("paused", "done", "error"):
- break
- time.sleep(0.05)
- assert status is not None and status["status"] == "paused"
-
-
# ── pause / resume against a real loopback range server ──────
@@ -576,32 +477,6 @@ def _pause_when_flowing(client, job_id):
_BIG_BODY = bytes(range(256)) * (8 * 1024 * 1024 // 256) # 8 MiB, deterministic
-def test_download_pause_parks_job_with_handle_and_partials(
- client, monkeypatch, dl_server, tmp_path):
- """Mid-flight pause: the job parks as 'paused' (never 'done'/'error'),
- the resume handle stays registered, and the downloader's partial
- state survives on disk for the later resume."""
- _pin_budget(monkeypatch)
- from hermes_cli.local_runtime.catalog import CATALOG
- from hermes_cli.web_routers import local_models as lm
-
- _serve_plan(monkeypatch, dl_server, tmp_path / "partials",
- {"PartA": _BIG_BODY})
-
- job_id = client.post("/api/local-models/download",
- json={"model_id": CATALOG[0].id}).json()["job_id"]
- _pause_when_flowing(client, job_id)
-
- status = _poll_job(client, job_id)
- assert status["status"] == "paused", status
- assert status["error"] is None
- # The resume handle survives the pause — the route can pick it up.
- assert lm._RUNNING[job_id].get("resume") is not None
- # Partial state is the downloader's own and must be intact.
- partials = list(Path(tmp_path / "partials").glob("*.part"))
- assert partials and any(p.stat().st_size > 0 for p in partials)
-
-
def test_download_resume_completes_bytes(client, monkeypatch, dl_server,
tmp_path):
"""Resume after a mid-flight pause finishes the remaining ranges and
@@ -622,6 +497,10 @@ def test_download_resume_completes_bytes(client, monkeypatch, dl_server,
assert status["status"] == "paused", status
RangeHandler.slow_per_chunk = 0.0 # let the resume run at full speed
+ assert status["error"] is None
+ assert lm._RUNNING[job_id].get("resume") is not None
+ partials = list((tmp_path / "partials").glob("*.part"))
+ assert partials and any(p.stat().st_size > 0 for p in partials)
assert client.post("/api/local-models/download/resume",
json={"job_id": job_id}).json()["resumed"] is True
diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.py
index 6dd61c68705..2a5385bf799 100644
--- a/tests/hermes_cli/test_local_runtime.py
+++ b/tests/hermes_cli/test_local_runtime.py
@@ -31,6 +31,7 @@ class _StubHandler(BaseHTTPRequestHandler):
models: dict | None = None
require_auth = False
chat_answer = "Paris"
+ reasoning = ""
requests_processing = 0
slots: list = []
@@ -73,7 +74,8 @@ class _StubHandler(BaseHTTPRequestHandler):
body = json.loads(self.rfile.read(length)) if length else {}
if self.path == "/v1/chat/completions":
self._send(200, {"choices": [{"message": {
- "role": "assistant", "content": self.chat_answer}}]})
+ "role": "assistant", "content": self.chat_answer,
+ "reasoning_content": self.reasoning}}]})
elif self.path == "/models/load":
self._send(200, {"success": True})
elif self.path == "/models/unload":
@@ -218,24 +220,11 @@ def test_touch_generate_is_the_readiness_proof(stub_server, tmp_path):
assert sup.touch_generate("m") is False
-def test_touch_generate_scans_reasoning_content(stub_server, tmp_path):
- """Reasoning models answer inside reasoning_content (receipted pitfall)."""
[email protected]('reasoning,ready', [('The capital is Paris.', True), ('', False)])
+def test_touch_generate_scans_reasoning_content(stub_server, tmp_path, reasoning, ready):
port, handler = stub_server
- sup = _make_supervisor(tmp_path, port)
-
- class ReasoningHandler(handler): # type: ignore[valid-type]
- def do_POST(self): # noqa: N802
- if self.path == "/v1/chat/completions":
- self._send(200, {"choices": [{"message": {
- "role": "assistant", "content": "",
- "reasoning_content": "The capital of France is Paris."}}]})
- else:
- self._send(404, {})
-
- # Swap handler class on the live stub server socket is overkill; just
- # verify the scan logic path via the normal handler with empty content.
- handler.chat_answer = ""
- assert sup.touch_generate("m") is False # empty content, no reasoning field
+ handler.chat_answer, handler.reasoning = '', reasoning
+ assert _make_supervisor(tmp_path, port).touch_generate('m') is ready
def test_ensure_model_ready_unknown_model_raises(stub_server, tmp_path):
diff --git a/tests/hermes_cli/test_mcp_catalog.py b/tests/hermes_cli/test_mcp_catalog.py
index 78fd3d95391..7483d8d0fa9 100644
--- a/tests/hermes_cli/test_mcp_catalog.py
+++ b/tests/hermes_cli/test_mcp_catalog.py
@@ -222,11 +222,6 @@ class TestManifestParsing:
_parse_manifest(path)
-
-
-
-
-
def test_tools_default_excluded_parsed(self, catalog_dir):
body = _basic_manifest(
tools={"default_excluded": ["docs", "*_radar_*"]},
@@ -295,8 +290,9 @@ class TestInstall:
assert server["tools"]["exclude"] == ["docs", "*_radar_*"]
assert "include" not in server["tools"]
+ @pytest.mark.parametrize('stale', [False, True])
def test_reinstall_prior_include_wins_over_default_excluded(
- self, catalog_dir, monkeypatch
+ self, catalog_dir, monkeypatch, stale
):
"""A user's prior include selection survives reinstall of an
exclude-mode manifest (prior selection > manifest default)."""
@@ -316,6 +312,9 @@ class TestInstall:
}
save_config(cfg)
+ if stale:
+ cfg['mcp_servers']['demo']['tools']['exclude'] = ['tool_a']
+ save_config(cfg)
import sys as _sys
probed = [("tool_a", "a"), ("tool_b", "b")]
monkeypatch.setattr(mc, "_probe_tools", lambda name: probed)
@@ -359,38 +358,6 @@ class TestInstall:
assert server["tools"]["exclude"] == user_exclude
assert "include" not in server["tools"]
- def test_include_mode_reinstall_ignores_stale_exclude(
- self, catalog_dir, monkeypatch
- ):
- """When the user previously chose an include selection, a leftover
- exclude value must not shadow it on reinstall of an exclude-mode
- manifest — include (explicit user checklist choice) wins."""
- body = _basic_manifest(
- tools={"default_excluded": ["*_radar_*"]},
- )
- _write_manifest(catalog_dir, "demo", body)
- import hermes_cli.mcp_catalog as mc
- from hermes_cli.config import load_config, save_config
-
- cfg = load_config()
- cfg.setdefault("mcp_servers", {})["demo"] = {
- "command": "npx",
- "args": ["-y", "demo-mcp"],
- "enabled": True,
- "tools": {"include": ["tool_a"]},
- }
- save_config(cfg)
-
- import sys as _sys
- probed = [("tool_a", "a"), ("tool_b", "b")]
- monkeypatch.setattr(mc, "_probe_tools", lambda name: probed)
- monkeypatch.setattr(_sys.stdin, "isatty", lambda: False)
-
- mc.install_entry(_entry("demo"), enable=True)
-
- server = load_config()["mcp_servers"]["demo"]
- assert server["tools"]["include"] == ["tool_a"]
- assert "exclude" not in server["tools"]
def test_probe_fail_reinstall_preserves_prior_selection(self, catalog_dir):
"""A failed probe during reinstall (e.g. OAuth not yet completed)
@@ -538,8 +505,6 @@ class TestInstall:
assert "secret-val" not in raw
-
-
# ---------------------------------------------------------------------------
# Uninstall
# ---------------------------------------------------------------------------
@@ -622,8 +587,6 @@ class TestToolSelection:
assert server["tools"]["include"] == ["a", "b", "c"]
-
-
def test_reinstall_preserves_prior_user_selection(
self, catalog_dir, monkeypatch
):
diff --git a/tests/hermes_cli/test_memory_setup_provider_arg.py b/tests/hermes_cli/test_memory_setup_provider_arg.py
index 7dc163e1f40..8aaf9d56aaa 100644
--- a/tests/hermes_cli/test_memory_setup_provider_arg.py
+++ b/tests/hermes_cli/test_memory_setup_provider_arg.py
@@ -31,42 +31,3 @@ class TestMemorySetupProviderRouting:
out = capsys.readouterr().out
assert "not found" in out
assert "hermes memory setup" in out
-
-
-class TestInstallDependenciesRunner:
- """`_install_dependencies` routes through pm (venv sync of the declared
- extra) — the old uv → pip → ensurepip ladder is gone."""
-
- def test_syncs_declared_extra_via_pm(self, tmp_path):
- (tmp_path / "plugin.yaml").write_text("extra: mem0\n", encoding="utf-8")
- synced = []
-
- import pm
-
- with patch("plugins.memory.find_provider_dir", return_value=tmp_path), \
- patch.object(pm, "available", lambda extra: False), \
- patch.object(
- pm, "sync_venv",
- lambda extras=None, explicit=False: synced.append(
- (list(extras or []), explicit)
- ),
- ):
- memory_setup._install_dependencies("x")
-
- assert synced == [(["mem0"], True)]
-
- def test_available_extra_still_goes_through_pm_currency_check(self, tmp_path):
- (tmp_path / "plugin.yaml").write_text("extra: mem0\n", encoding="utf-8")
- synced = []
-
- import pm
-
- with patch("plugins.memory.find_provider_dir", return_value=tmp_path), \
- patch.object(pm, "available", lambda extra: True), \
- patch.object(
- pm, "sync_venv",
- lambda extras=None, explicit=False: synced.append(list(extras or [])),
- ):
- memory_setup._install_dependencies("x")
-
- assert synced == [["mem0"]]
diff --git a/tests/hermes_cli/test_plugin_worker_lifecycle.py b/tests/hermes_cli/test_plugin_worker_lifecycle.py
index e25a6f77dad..f2f752ea5eb 100644
--- a/tests/hermes_cli/test_plugin_worker_lifecycle.py
+++ b/tests/hermes_cli/test_plugin_worker_lifecycle.py
@@ -20,20 +20,21 @@ def test_declaration_consent_admission_and_resync(plugin_world, monkeypatch, cap
world = plugin_world
origin, revision = world.origin(surface=surface, suffix=suffix)
before = (world.home / "config.yaml").read_bytes()
- monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: False)
- world.command("install", identifier=origin.as_uri(), ref=revision, enable=True, allow_removed=True)
- assert world.enabled() == [], "non-interactive Python admission bypassed consent"
- assert (world.home / "config.yaml").read_bytes() == before
- assert "skipped (non-interactive)" in " ".join(capsys.readouterr().out.split())
-
+ if (surface, suffix) == ("pyproject", "yaml"):
+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: False)
+ world.command("install", identifier=origin.as_uri(), ref=revision, enable=True, allow_removed=True)
+ assert world.enabled() == [], "non-interactive Python admission bypassed consent"
+ assert (world.home / "config.yaml").read_bytes() == before
+ assert "skipped (non-interactive)" in " ".join(capsys.readouterr().out.split())
+ monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)
+ monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)
+ monkeypatch.setattr("builtins.input", lambda prompt: "no")
+ world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True)
+ assert world.enabled() == []
+ assert (world.home / "config.yaml").read_bytes() == before
+ assert "declined" in capsys.readouterr().out
monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True)
monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True)
- monkeypatch.setattr("builtins.input", lambda prompt: "no")
- world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True)
- assert world.enabled() == []
- assert (world.home / "config.yaml").read_bytes() == before
- assert "declined" in capsys.readouterr().out
-
monkeypatch.setattr("builtins.input", lambda prompt: "yes")
world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True)
assert world.enabled() == ["plugin-worker-proof"]
@@ -276,4 +277,4 @@ def test_concurrent_commands_keep_acknowledged_enables(plugin_world, sibling_pro
for process in processes:
if process.poll() is None:
process.kill()
- process.communicate(timeout=10)
\ No newline at end of file
+ process.communicate(timeout=10)
diff --git a/tests/hermes_cli/test_plugins_cadence.py b/tests/hermes_cli/test_plugins_cadence.py
index 28f6e561bda..94222a5eda3 100644
--- a/tests/hermes_cli/test_plugins_cadence.py
+++ b/tests/hermes_cli/test_plugins_cadence.py
@@ -30,8 +30,7 @@ class _Result:
return {"name": self.name, "class": self.klass}
-def _no_results(plugins_dir, **k):
- return []
+
def test_clock_gate_due_when_never_run(homed):
@@ -74,78 +73,44 @@ def test_run_writes_receipt_and_marker(homed):
assert len(calls) == 1
-def test_needs_fixing_logged_not_applied(homed):
[email protected]('enabled', [False, True])
+def test_auto_apply_selects_only_updateable_git_and_persists_receipt(homed, enabled, caplog):
+ from pm import receipt
applied = []
-
- import pm.receipt as receipt_mod
-
- monkey = pytest.MonkeyPatch()
- monkey.setattr(receipt_mod, "begin", lambda kind: None)
- monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None)
- try:
- results = cad.run_scheduled_check(
- run_checks_fn=lambda d: [_Result("plug", needs_fixing="mismatch")],
- plugins_dir=homed / "plugins",
- apply_updates_fn=applied.append,
- now=time.time(),
- )
- assert applied == [] # needs-fixing is never auto-applied
- finally:
- monkey.undo()
-
-
-def test_auto_apply_only_git_rows_and_only_when_opted_in(homed):
- applied = []
-
- import pm.receipt as receipt_mod
-
- monkey = pytest.MonkeyPatch()
- monkey.setattr(receipt_mod, "begin", lambda kind: None)
- monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None)
- try:
- results = [_Result("gitplug", klass="git", update_available=True),
- _Result("pipplug", klass="pip", update_available=True)]
- # opted OUT: nothing applied
- cad.run_scheduled_check(
- run_checks_fn=lambda d: results,
- plugins_dir=homed / "plugins",
- apply_updates_fn=applied.append,
- config_get=lambda s, k: (False if k == "auto_apply" else None),
- now=time.time(),
- )
- assert applied == [] # auto_apply False → nothing
-
- # opted IN: only the git row applies
- cad._markers_dir().joinpath("last-run").unlink()
- cad.run_scheduled_check(
- run_checks_fn=lambda d: results,
- plugins_dir=homed / "plugins",
- apply_updates_fn=applied.append,
- config_get=lambda s, k: (True if k == "auto_apply" else None),
- now=time.time(),
- )
- assert applied == ["gitplug"]
- finally:
- monkey.undo()
-
-
-def test_check_failure_is_never_fatal_and_stamps_marker(homed):
- import pm.receipt as receipt_mod
-
- monkey = pytest.MonkeyPatch()
- monkey.setattr(receipt_mod, "begin", lambda kind: None)
- monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None)
- try:
- def boom(d):
- raise RuntimeError("network down")
-
- results = cad.run_scheduled_check(
- run_checks_fn=boom,
- plugins_dir=homed / "plugins",
- now=time.time(),
- )
- assert results == []
- # marker stamped → a failing check doesn't hammer the network
- assert (homed / "plugin-update-checks" / "last-run").is_file()
- finally:
- monkey.undo()
+ rows = [_Result('gitplug', update_available=True),
+ _Result('pipplug', klass='pip', update_available=True),
+ _Result('broken', needs_fixing='mismatch')]
+ cad.run_scheduled_check(run_checks_fn=lambda _: rows, plugins_dir=homed / 'plugins',
+ apply_updates_fn=applied.append,
+ config_get=lambda section, key: enabled if key == 'auto_apply' else 24)
+ assert applied == (['gitplug'] if enabled else [])
+ assert receipt.latest()['outcome'] == 'updates-available'
+ assert 'broken' in caplog.text and 'trust-update-url' in caplog.text
+
+
[email protected]('failed', [False, True])
+def test_housekeeping_runs_real_cadence_and_backs_off(homed, monkeypatch, caplog, failed):
+ import gateway.run as gateway
+ from hermes_cli import plugins_updates, plugins_cmd
+ from pm import receipt
+
+ calls, applied = [], []
+ def checks(directory):
+ calls.append(directory)
+ if failed:
+ raise OSError('offline')
+ return [_Result('plug', update_available=True)]
+ monkeypatch.setattr(plugins_updates, 'run_checks', checks)
+ monkeypatch.setattr(plugins_cmd, '_plugins_dir', lambda: homed / 'plugins')
+ monkeypatch.setattr(plugins_cmd, 'cmd_update', lambda name, **kwargs: applied.append((name, kwargs)))
+ monkeypatch.setattr(cad, 'auto_apply_enabled', lambda *_: True)
+ for _ in range(2):
+ gateway._housekeeping_chore('Plugin update check', gateway._housekeeping_plugin_update_check)
+ assert calls == [homed / 'plugins']
+ assert applied == ([] if failed else [('plug', {'interactive': False})])
+ saved = receipt.latest()
+ assert saved['outcome'] == ('failed' if failed else 'updates-available')
+ assert saved['exit_code'] == int(failed)
+ assert (homed / 'plugin-update-checks/last-run').is_file()
+ if failed:
+ assert saved['warnings'][0]['message'] in caplog.text
diff --git a/tests/hermes_cli/test_plugins_check_updates.py b/tests/hermes_cli/test_plugins_check_updates.py
index c89d33f5dbe..65932f37ff8 100644
--- a/tests/hermes_cli/test_plugins_check_updates.py
+++ b/tests/hermes_cli/test_plugins_check_updates.py
@@ -180,24 +180,11 @@ def test_matching_tag_fetches_feed(tmp_path):
r = check_provenanced(prov, fetch=fetch, ls_remote=_no)
assert fetched == ["https://feed.example/f.yml"]
assert r.latest == "1.2.0"
+ assert r.current == "1.0.0"
assert r.min_hermes == "0.27.0"
assert r.update_available is True # installed 1.0.0 vs feed 1.2.0
-def test_feed_version_equal_to_installed_version_means_no_update(tmp_path):
- """C17 convergence: feed semantic version vs installed semantic version."""
- plug = tmp_path / "plug"
- plug.mkdir()
- (plug / "plugin.yaml").write_text(
- "name: plug\nversion: 1.2.0\nupdate_url: https://feed.example/f.yml\n",
- encoding="utf-8",
- )
- prov = _git_prov(update_url="https://feed.example/f.yml")
- prov.path = plug
- r = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no)
- assert r.update_available is False
-
-
def test_feed_version_with_no_installed_version_is_unknown(tmp_path):
"""A semantic feed vs a versionless manifest cannot be compared — report
unknown, never a revision-vs-version inequality."""
@@ -254,25 +241,6 @@ def test_feed_git_sha_case_equivalent_is_not_an_update(tmp_path):
assert r.update_available is False
-def test_feed_git_tag_artifact_falls_to_semantic_compare(tmp_path):
- """A non-sha artifacts.git (repo URL, tag) is not a comparable git
- identity — the feed's semantic version is compared against the
- installed manifest's version instead."""
- plug = tmp_path / "plug"
- plug.mkdir()
- (plug / "plugin.yaml").write_text(
- "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n",
- encoding="utf-8",
- )
- feed = "version: 9.9.9\nartifacts:\n git: https://example/o/r\n"
- prov = _git_prov(update_url="https://feed.example/f.yml")
- prov.path = plug
- r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no)
- assert r.update_available is True
- assert r.current == "1.0.0"
- assert r.latest == "9.9.9"
-
-
def test_feed_git_sha_with_no_recorded_revision_is_unknown(tmp_path):
plug = tmp_path / "plug"
plug.mkdir()
@@ -305,23 +273,6 @@ def test_feed_git_sha_against_tagged_revision_is_unknown(tmp_path):
assert r.update_available is None
-def test_feed_semantic_branch_reports_installed_version_as_current(tmp_path):
- """The semantic branch compares version vs version, so the reported
- current is the installed version — not the unrelated revision sha."""
- plug = tmp_path / "plug"
- plug.mkdir()
- (plug / "plugin.yaml").write_text(
- "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n",
- encoding="utf-8",
- )
- prov = _git_prov(update_url="https://feed.example/f.yml")
- prov.path = plug
- r = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no)
- assert r.update_available is True
- assert r.current == "1.0.0"
- assert r.latest == "1.2.0"
-
-
def test_malformed_yaml_feed_reports_unknown_row(tmp_path):
plug = tmp_path / "plug"
plug.mkdir()
@@ -339,14 +290,16 @@ def test_parse_feed_rejects_non_string_git_artifact():
parse_feed_yml(feed)
-def test_ls_remote_lifecycle_current_available_applied(tmp_path):
+def test_ls_remote_lifecycle_current_available_applied(tmp_path, monkeypatch):
"""The git-path gate, end to end against a real local repo: current ->
ls-remote sees a new HEAD -> revision recorded -> current. No network,
no manual manifest rewriting — every comparison is the real command."""
repo = tmp_path / "repo"
run, head = _local_repo(repo, "-b", "main")
sha1 = head()
- ls_remote = _real_ls_remote()
+ from hermes_cli.plugins_updates import default_ls_remote
+ monkeypatch.setattr('hermes_cli.plugins_cmd._resolve_git_executable', _git_exe)
+ ls_remote = default_ls_remote
plug = tmp_path / "plug"
plug.mkdir()
@@ -373,22 +326,6 @@ def test_ls_remote_lifecycle_current_available_applied(tmp_path):
assert check_provenanced(prov3, fetch=_no, ls_remote=ls_remote).update_available is False
-def _real_ls_remote():
- git = _git_exe()
- env = _git_env()
-
- def ls_remote(source):
- proc = subprocess.run(
- [git, "ls-remote", source, "HEAD"],
- capture_output=True, text=True, timeout=10, env=env,
- )
- if proc.returncode != 0:
- raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200])
- out = (proc.stdout or "").strip()
- return out.split("\t")[0] if out else ""
- return ls_remote
-
-
def test_feed_fetch_failure_is_row_level_reason(tmp_path):
plug = tmp_path / "plug"
plug.mkdir()
@@ -428,7 +365,7 @@ def test_ls_remote_fallback(tmp_path):
# ── the real git ls-remote, against a local bare repo ───────────────
-def test_real_ls_remote_against_bare_repo(tmp_path):
+def test_real_ls_remote_against_bare_repo(tmp_path, monkeypatch):
source = tmp_path / "bare.git"
git = _git_exe()
env = _git_env()
@@ -436,14 +373,9 @@ def test_real_ls_remote_against_bare_repo(tmp_path):
[git, "init", "--bare", "-q", str(source)],
check=True, capture_output=True, env=env,
)
- # ls-remote on an empty bare repo: exit 0, empty HEAD — the command
- # SHAPE works; empty maps to unknown, never a crash
- proc = subprocess.run(
- [git, "ls-remote", str(source), "HEAD"],
- capture_output=True, text=True, timeout=10, env=env,
- )
- assert proc.returncode == 0
- assert proc.stdout.strip() == ""
+ from hermes_cli.plugins_updates import default_ls_remote
+ monkeypatch.setattr('hermes_cli.plugins_cmd._resolve_git_executable', _git_exe)
+ assert default_ls_remote(str(source)) == ""
# ── feed parsing ────────────────────────────────────────────────────
@@ -465,19 +397,6 @@ class _EP:
self.dist_name = dist_name
-def test_pip_check_stateless():
- eps = [_EP("mnemosyne", "mnemosyne_hermes:register", "mnemosyne-hermes")]
- rs = check_pip_plugins(
- installed_version=lambda d: "0.5.0",
- pypi_latest=lambda d: "0.6.0",
- entry_points=eps,
- )
- assert rs[0].klass == "pip"
- assert rs[0].current == "0.5.0"
- assert rs[0].latest == "0.6.0"
- assert rs[0].update_available is True
-
-
def test_pip_not_on_pypi_reports_unknown():
eps = [_EP("local-only", "x:y", "x")]
rs = check_pip_plugins(
@@ -547,4 +466,4 @@ def test_run_checks_never_mutates(tmp_path):
include_pip=False,
)
assert results[0].update_available is True
- assert (plugins / ".install-metadata.json").read_text(encoding="utf-8") == before
\ No newline at end of file
+ assert (plugins / ".install-metadata.json").read_text(encoding="utf-8") == before
diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.py
index 406ad56d5e8..9ba46eee6d5 100644
--- a/tests/hermes_cli/test_plugins_cmd.py
+++ b/tests/hermes_cli/test_plugins_cmd.py
@@ -39,20 +39,9 @@ class TestSanitizePluginName:
_sanitize_plugin_name("../../etc/passwd", tmp_path)
-
-
-
-
-
# ── allow_subdir=True ──
-
-
-
-
-
-
# ── _resolve_git_url ──────────────────────────────────────────────────────
@@ -60,16 +49,12 @@ class TestResolveGitUrl:
"""Shorthand and full-URL resolution, with optional subdirectory."""
-
-
-
def test_url_with_fragment_subdir(self):
url, subdir = _resolve_git_url("https://github.com/owner/repo.git#my-plugin")
assert url == "https://github.com/owner/repo.git"
assert subdir == "my-plugin"
-
@pytest.mark.parametrize(
"identifier",
[
@@ -102,7 +87,6 @@ class TestResolveSubdirWithin:
assert result == (tmp_path / "a" / "b" / "c").resolve()
-
def test_rejects_symlink_escape(self, tmp_path):
clone = tmp_path / "clone"
clone.mkdir()
@@ -166,23 +150,6 @@ class TestResolveGitExecutable:
assert call.args[0][0] == "/resolved/git"
assert run.call_args_list[2].args[0][1:] == ["pull", "--ff-only"]
- def test_git_pull_clean_tree_never_stashes(self, tmp_path):
- import hermes_cli.plugins_cmd as pc
-
- _resolve_git_executable.cache_clear()
- with patch.object(pc, "_resolve_git_executable", return_value="/g"):
- with patch.object(pc.subprocess, "run") as run:
- run.side_effect = [
- MagicMock(returncode=0, stdout="", stderr=""), # status
- MagicMock(returncode=0, stdout="[email protected]:x.git\n", stderr=""), # remote get-url
- MagicMock(returncode=0, stdout="Updated\n", stderr=""), # pull
- ]
- ok, msg = pc._git_pull_plugin_dir(tmp_path)
- assert ok is True
- assert msg == "Updated"
- commands = [c.args[0][1] for c in run.call_args_list]
- assert "stash" not in commands
-
class TestGitPullPluginDirAutostash:
"""Real-git E2E: local edits in a plugin checkout must not block updates."""
@@ -294,6 +261,7 @@ class TestGitPullPluginDirAutostash:
ok, msg = pc._git_pull_plugin_dir(checkout)
assert ok is True
assert "Already up to date" in msg
+ assert git(checkout, "stash", "list").strip() == ""
# ── _repo_name_from_url ──────────────────────────────────────────────────
@@ -308,8 +276,6 @@ class TestRepoNameFromUrl:
)
-
-
# ── plugins_command dispatch ──────────────────────────────────────────────
@@ -455,7 +421,6 @@ class TestCmdRemove:
assert exc_info.value.code == 1
-
# ── _copy_example_files tests ─────────────────────────────────────────────────
@@ -503,8 +468,6 @@ class TestPromptPluginEnvVars:
"""Tests for _prompt_plugin_env_vars."""
-
-
def test_prompts_for_missing_var_rich_format(self):
from hermes_cli.plugins_cmd import _prompt_plugin_env_vars
from unittest.mock import MagicMock, patch
@@ -550,8 +513,6 @@ class TestPromptPluginEnvVars:
mock_prompt.assert_called_once()
-
-
# ── curses_radiolist ─────────────────────────────────────────────────────
@@ -573,7 +534,6 @@ class TestProviderDiscovery:
"""Test provider plugin discovery and config helpers."""
-
def test_save_context_engine(self, tmp_path, monkeypatch):
"""Saving a context engine persists to config.yaml."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -597,19 +557,14 @@ class TestProviderDiscovery:
# ── Auto-activation fix ──────────────────────────────────────────────────
-class TestNoAutoActivation:
- """Verify that plugin engines don't auto-activate when config says 'compressor'."""
-
- def test_compressor_default_ignores_plugin(self):
- """When context.engine is 'compressor', a plugin-registered engine should NOT
- be used — only explicit config triggers plugin engines."""
- # This tests the run_agent.py logic indirectly by checking that the
- # code path for default config doesn't call get_plugin_context_engine.
- import run_agent as ra_module
- source = Path(ra_module.__file__).read_text(encoding="utf-8")
- # The old code had: "Even with default config, check if a plugin registered one"
- # The fix removes this. Verify it's gone.
- assert "Even with default config, check if a plugin registered one" not in source
+def test_default_compressor_does_not_activate_an_offered_plugin(monkeypatch):
+ from agent.agent_init import _select_context_engine
+ from types import SimpleNamespace
+ candidate = SimpleNamespace(name='offered')
+ monkeypatch.setattr('plugins.context_engine.load_context_engine', lambda _: None)
+ monkeypatch.setattr('hermes_cli.plugins.get_plugin_context_engine', lambda: candidate)
+ assert _select_context_engine({'context': {'engine': 'compressor'}}) is None
+ assert _select_context_engine({'context': {'engine': 'offered'}}).name == 'offered'
# ── End-to-end subdirectory install ──────────────────────────────────────────
diff --git a/tests/hermes_cli/test_post_update.py b/tests/hermes_cli/test_post_update.py
index 0fdf4c2aff8..aba2dc101f1 100644
--- a/tests/hermes_cli/test_post_update.py
+++ b/tests/hermes_cli/test_post_update.py
@@ -101,29 +101,6 @@ def test_migrate_config_restores_backup_when_version_does_not_advance(
assert backups, "backup file must exist"
-def test_migrate_config_restores_backup_on_exception(tmp_path, monkeypatch):
- import hermes_cli.config as cfg
- import hermes_cli.config_migrations as mig
-
- config_path = tmp_path / "config.yaml"
- config_path.write_text("_config_version: 20\n", encoding="utf-8")
-
- floor = getattr(mig, "SUPPORT_FLOOR_VERSION", 12)
- monkeypatch.setattr(cfg, "check_config_version", lambda: (max(20, floor), 34))
- monkeypatch.setattr(cfg, "get_config_path", lambda: config_path)
- monkeypatch.setattr(cfg, "get_env_path", lambda: tmp_path / ".env")
-
- def exploding_migrate(**kw):
- config_path.write_text("half-written garbage", encoding="utf-8")
- raise RuntimeError("migration blew up")
-
- monkeypatch.setattr(cfg, "migrate_config", lambda **kw: exploding_migrate(**kw))
-
- with pytest.raises(RuntimeError, match="blew up"):
- step_migrate_config()
- assert config_path.read_text(encoding="utf-8") == "_config_version: 20\n"
-
-
# ── step_state_db_guard ──────────────────────────────────────────────
diff --git a/tests/hermes_cli/test_post_update_expose_cli.py b/tests/hermes_cli/test_post_update_expose_cli.py
index fb453400bdc..03388b37c8e 100644
--- a/tests/hermes_cli/test_post_update_expose_cli.py
+++ b/tests/hermes_cli/test_post_update_expose_cli.py
@@ -84,21 +84,7 @@ class TestExposeCli:
assert str(root / ".hermes" / "bin") in body
assert os.access(wrapper, os.X_OK)
- @posix_only
- def test_second_run_is_a_no_op(self, fake_install):
- _launchers.expose_cli()
- result = _launchers.expose_cli()
- assert result == {"ok": True, "written": []}
- @posix_only
- def test_repairs_a_stale_same_install_wrapper(self, fake_install):
- home, root = fake_install
- _launchers.expose_cli()
- wrapper = home / ".local" / "bin" / "hermes"
- wrapper.write_text(f'#!/bin/sh\nexec "{root}/venv/bin/python" OLD-SHAPE\n')
- result = _launchers.expose_cli()
- assert "hermes" in result["written"]
- assert "OLD-SHAPE" not in wrapper.read_text()
@posix_only
def test_leaves_another_installs_wrapper_alone(self, fake_install):
diff --git a/tests/hermes_cli/test_quarantine_orphan_rescue.py b/tests/hermes_cli/test_quarantine_orphan_rescue.py
index 28faa63e117..243d3c1394c 100644
--- a/tests/hermes_cli/test_quarantine_orphan_rescue.py
+++ b/tests/hermes_cli/test_quarantine_orphan_rescue.py
@@ -305,22 +305,3 @@ def test_helper_is_a_noop_when_installer_wrote_a_fresh_shim(tmp_path, capsys):
assert failed == []
assert original.read_bytes() == b"MZ-fresh", "must not clobber the fresh shim"
assert capsys.readouterr().err == ""
-
-
-def test_restore_reports_on_stderr(tmp_path, capsys):
- """Restore diagnostics must not pollute a JSON-RPC stdout stream."""
- scripts = _make_scripts_dir(tmp_path)
- quarantined = scripts / "hermes.exe.old.123"
- quarantined.write_bytes(b"MZ-old-hermes")
- original = scripts / "hermes.exe"
-
- def always_locked(src, dst):
- raise PermissionError(32, "being used by another process")
-
- with patch.object(er.os, "rename", always_locked):
- failed = er.restore_quarantined_shims([(original, quarantined)], backoff_ms=(0,))
-
- captured = capsys.readouterr()
- assert failed == [(original, quarantined)]
- assert "FAILED to restore hermes.exe" in captured.err
- assert captured.out == "", "stdout must stay clean for JSON-RPC"
diff --git a/tests/hermes_cli/test_run_with_idle_timeout.py b/tests/hermes_cli/test_run_with_idle_timeout.py
deleted file mode 100644
index 321543a7fa2..00000000000
--- a/tests/hermes_cli/test_run_with_idle_timeout.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""Retired build entrypoints stop old in-memory updaters without side effects."""
-import sys
-
-import pytest
-
-from hermes_cli.main_web_build import _nixos_build_env, _run_npm_install_deterministic, _run_with_idle_timeout
-
-
[email protected]("helper", ["idle", "install", "nixos"])
-def test_retired_build_helper_stops_before_running_any_command(tmp_path, helper, capsys):
- marker = tmp_path / "ran"
- script = tmp_path / "command.py"
- script.write_text(f"from pathlib import Path; Path({str(marker)!r}).touch()")
- with pytest.raises(SystemExit) as error:
- if helper == "idle":
- _run_with_idle_timeout([sys.executable, str(script)], tmp_path, idle_timeout_seconds=10)
- elif helper == "install":
- _run_npm_install_deterministic(sys.executable, tmp_path, extra_args=(str(script),))
- else:
- _nixos_build_env()
- assert error.value.code == 0
- assert not marker.exists()
- assert "run `hermes` again" in capsys.readouterr().err
diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.py
index 40d57353ba5..7b810f7f71f 100644
--- a/tests/hermes_cli/test_source_launcher_publication.py
+++ b/tests/hermes_cli/test_source_launcher_publication.py
@@ -54,6 +54,17 @@ def fixture_tree(tmp_path, monkeypatch):
return repo, home, interpreter
+def select_generation(repo, name, value):
+ selected = install_state_dir(repo) / 'environments' / str(name) / 'venv'
+ site = site_packages(selected)
+ site.mkdir(parents=True)
+ (selected / 'pyvenv.cfg').write_text('home = fixture\n', encoding='utf-8')
+ (site / 'selected_probe.py').write_text(f'VALUE = {value!r}\n', encoding='utf-8')
+ (install_state_dir(repo) / 'facts.json').write_text(
+ json.dumps({'packages': {'venv': {'environment': str(selected)}}}), encoding='utf-8')
+ return selected
+
+
@pytest.mark.platforms("windows", "posix")
@pytest.mark.parametrize("form", ["native", "shell"])
def test_source_launchers_boot_selected_generation_from_custom_home(tmp_path, monkeypatch, form):
@@ -73,13 +84,7 @@ def test_source_launchers_boot_selected_generation_from_custom_home(tmp_path, mo
]
args = ['spaces and café', 'apostrophe\'s', r'one\two', '$HOME; echo no', '']
for number in (1, 2):
- selected = install_state_dir(repo) / "environments" / str(number) / "venv"
- site = site_packages(selected)
- site.mkdir(parents=True)
- (selected / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8")
- (site / "selected_probe.py").write_text(f"VALUE = {number}\n", encoding="utf-8")
- (install_state_dir(repo) / "facts.json").write_text(
- json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8")
+ select_generation(repo, number, number)
env = dict(os.environ)
env.pop("HERMES_HOME", None)
env.pop("HERMES_RUNTIME_DIR", None)
@@ -195,13 +200,7 @@ def test_boot_migrates_legacy_conveniences_to_selected_runtime(tmp_path, monkeyp
repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)
monkeypatch.setattr(Path, "home", lambda: home)
monkeypatch.setenv("HERMES_INSTALL_ROOT", str(repo))
- selected = install_state_dir(repo) / "environments" / "current" / "venv"
- site = site_packages(selected)
- site.mkdir(parents=True)
- (selected / "pyvenv.cfg").write_text("home = fixture\n")
- (site / "selected_probe.py").write_text("VALUE = 'migrated'\n")
- (install_state_dir(repo) / "facts.json").write_text(json.dumps({
- "schema": 1, "packages": {"venv": {"environment": str(selected)}}}))
+ select_generation(repo, 'current', 'migrated')
out = home / ".local" / "bin"
out.mkdir(parents=True)
# Old venv and sibling-ACP wrappers, with an unrelated command sharing bin.
@@ -239,16 +238,9 @@ def _command_survives_generation_collection(tmp_path, monkeypatch, surface):
launcher = next(path for path in out.iterdir() if path.stem == "hermes")
args = ["café ' quoted", "", "$HOME; not a shell"]
command = []
- selected = install_state_dir(repo) / "environments" / "old" / "venv"
for value in ("old", "new"):
- selected = selected.parent.parent / value / "venv"
- site = site_packages(selected)
- site.mkdir(parents=True)
- (selected / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8")
+ selected = select_generation(repo, value, value)
(selected.parent / ".lease-managed").touch()
- (site / "selected_probe.py").write_text(f"VALUE = {value!r}\n", encoding="utf-8")
- (install_state_dir(repo) / "facts.json").write_text(
- json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8")
if value == "old":
if surface == "legacy":
command = [sys.executable, "-I", str(repo / "scripts/hermes-gateway"), "--help"]
@@ -323,13 +315,7 @@ def test_dashboard_action_boots_selected_dependencies(tmp_path, monkeypatch):
from hermes_cli import web_server, web_server_gateway
repo, home, _ = fixture_tree(tmp_path, monkeypatch)
- selected = install_state_dir(repo) / "environments" / "current" / "venv"
- site = site_packages(selected)
- site.mkdir(parents=True)
- (selected / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8")
- (site / "selected_probe.py").write_text("VALUE = 'selected'\n", encoding="utf-8")
- (install_state_dir(repo) / "facts.json").write_text(
- json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8")
+ select_generation(repo, 'current', 'selected')
monkeypatch.setattr(web_server, "PROJECT_ROOT", repo)
monkeypatch.setattr(web_server_gateway, "_ACTION_LOG_DIR", home / "logs")
proc = web_server_gateway._spawn_hermes_action(["--version"], "gateway-restart")
diff --git a/tests/hermes_cli/test_tools_config.py b/tests/hermes_cli/test_tools_config.py
index dd8a6b543cf..97d24838f2e 100644
--- a/tests/hermes_cli/test_tools_config.py
+++ b/tests/hermes_cli/test_tools_config.py
@@ -386,28 +386,7 @@ class TestAgentBrowserPostSetup:
with patch("pm.ensure") as ensure:
yield ensure
- def test_browserbase_returns_before_any_chromium_check(self):
- with patch("subprocess.run") as run, patch(
- "tools.browser_tool_install._chromium_installed"
- ) as chromium_check:
- _run_post_setup("browserbase")
- run.assert_not_called()
- chromium_check.assert_not_called()
-
- def test_docker_with_missing_chromium_warns_instead_of_installing(self, _stub_package_install):
- with patch(
- "tools.browser_tool_install._find_agent_browser", return_value="/image/agent-browser"
- ), patch("subprocess.run") as run, patch(
- "tools.browser_tool_install._chromium_installed", return_value=False
- ), patch(
- "tools.browser_tool_install._running_in_docker", return_value=True
- ), patch("hermes_cli.tools_config_post_setup._print_warning") as warn:
- _run_post_setup("agent_browser")
-
- run.assert_not_called()
- _stub_package_install.assert_not_called()
- assert any("Docker" in c.args[0] for c in warn.call_args_list)
@pytest.mark.parametrize("failure", ["pm", "timeout"])
def test_install_failure_reports_error(self, failure):
@@ -433,13 +412,6 @@ class TestBrowserUseCliInstalledForAllNonCamofoxBackends:
Camofox must attempt the CLI install, not just the explicit
"Browser Use" row."""
- @pytest.mark.parametrize("key", ["agent_browser", "browserbase", "browser_use_cli"])
- def test_browser_post_setup_attempts_cli_install(self, key):
- with patch("hermes_cli.tools_config_post_setup._ensure_browser_use_cli") as ensure, patch(
- "shutil.which", return_value=None
- ), patch("subprocess.run"), patch("pm.ensure"):
- _run_post_setup(key)
- ensure.assert_called_once()
def test_camofox_post_setup_never_touches_browser_use(self):
"""Camofox is Firefox-based with no CDP surface; the CDP-only
@@ -671,17 +643,7 @@ def test_vision_picker_custom_endpoint(tmp_path, monkeypatch):
# Subscription rows and never-installed KittenTTS/Piper).
-def _fake_features(*, logged_in: bool, paid: bool = True):
- account = (
- NousPortalAccountInfo(
- logged_in=True, source="jwt", fresh=False, paid_service_access=paid
- )
- if logged_in
- else NousPortalAccountInfo(
- logged_in=False, source="none", fresh=False, paid_service_access=None
- )
- )
- return SimpleNamespace(nous_auth_present=logged_in, account_info=account)
+
def test_visible_providers_reuses_logged_out_feature_snapshot(monkeypatch):
diff --git a/tests/hermes_cli/test_tools_config_post_setup.py b/tests/hermes_cli/test_tools_config_post_setup.py
index 7ab2bd51c6e..d3177b51cb1 100644
--- a/tests/hermes_cli/test_tools_config_post_setup.py
+++ b/tests/hermes_cli/test_tools_config_post_setup.py
@@ -13,47 +13,42 @@ import pytest
from hermes_cli.tools_config_post_setup import _run_post_setup
-def test_cloud_browser_explicit_setup_ensures_managed_driver():
- with (
- patch("tools.browser_use_cli.install_cli", return_value=(True, "ready")),
- patch("tools.browser_tool_install._find_agent_browser", return_value="/external/agent-browser"),
- patch("pm.ensure") as ensure,
- patch("subprocess.run") as run,
- ):
- _run_post_setup("browserbase")
-
- ensure.assert_called_once_with("agent-browser", explicit=True)
- run.assert_not_called()
-
-
[email protected]("playwright_present", [True, False])
-def test_local_setup_uses_pm_dependency_union_and_gives_system_library_guidance(
- capsys, playwright_present,
-):
[email protected]('provider,docker,playwright', [
+ ('browserbase', False, False), ('agent_browser', False, True),
+ ('agent_browser', False, False), ('agent_browser', True, False),
+ ('browser_use_cli', False, False),
+])
+def test_browser_setup_respects_provider_and_native_owner(monkeypatch, capsys, provider, docker, playwright):
with (
- patch("tools.browser_use_cli.install_cli", return_value=(True, "ready")),
- patch("tools.browser_tool_install._running_in_docker", return_value=False),
- patch("tools.browser_tool_install._chromium_installed", return_value=False),
- patch("importlib.util.find_spec", return_value=object() if playwright_present else None),
- patch("shutil.which", return_value="/usr/bin/apt-get"),
- patch("pm.ensure") as ensure,
- patch("subprocess.run") as run,
+ patch('tools.browser_use_cli.install_cli', return_value=(True, 'ready')) as install,
+ patch('tools.browser_tool_install._running_in_docker', return_value=docker),
+ patch('tools.browser_tool_install._find_agent_browser', return_value='/image/agent-browser'),
+ patch('tools.browser_tool_install._chromium_installed', return_value=False) as chromium,
+ patch('importlib.util.find_spec', return_value=object() if playwright else None),
+ patch('shutil.which', return_value='/usr/bin/apt-get'),
+ patch('pm.ensure') as ensure, patch('subprocess.run') as run,
):
before = dict(os.environ)
- _run_post_setup("agent_browser")
+ _run_post_setup(provider)
assert dict(os.environ) == before
-
- ensure.assert_called_once_with("agent-browser", explicit=True)
+ install.assert_called_once()
run.assert_not_called()
- output = capsys.readouterr().out
- assert "system" in output
- if playwright_present:
- assert sys.executable in output
- assert "-m playwright install-deps chromium" in output
+ if provider == 'browserbase':
+ chromium.assert_not_called()
+ if provider == 'browser_use_cli' or docker:
+ ensure.assert_not_called()
else:
- assert "https://playwright.dev/python/docs/browsers#install-system-dependencies" in output
- assert "npx" not in output
+ ensure.assert_called_once_with('agent-browser', explicit=True)
+ output = capsys.readouterr().out
+ if docker:
+ assert 'Docker' in output
+ elif provider == 'agent_browser':
+ assert 'system' in output and 'npx' not in output
+ if playwright:
+ assert sys.executable in output and '-m playwright install-deps chromium' in output
+ else:
+ assert 'https://playwright.dev/python/docs/browsers#install-system-dependencies' in output
@pytest.mark.parametrize("status", [200, 503])
diff --git a/tests/hermes_cli/test_uninstall_install_kind.py b/tests/hermes_cli/test_uninstall_install_kind.py
index 78b4d823b1f..8da30658c88 100644
--- a/tests/hermes_cli/test_uninstall_install_kind.py
+++ b/tests/hermes_cli/test_uninstall_install_kind.py
@@ -137,24 +137,6 @@ def _make_home(tmp_path: Path) -> Path:
return home
-def test_run_data_uninstall_removes_data_keeps_code(monkeypatch, tmp_path):
- home = _make_home(tmp_path)
- monkeypatch.setattr(un, "get_hermes_home", lambda: home)
- import hermes_cli.gui_uninstall as gu
-
- monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "electron-userdata-none")
-
- un.run_data_uninstall(SimpleNamespace(yes=True))
-
- # Data gone.
- assert not (home / "config.yaml").exists()
- assert not (home / ".env").exists()
- assert not (home / "sessions").exists()
- assert not (home / "logs").exists()
- # Code untouched — even on a sealed tree the data mode never touches it.
- assert (home / "hermes-agent" / "hermes_cli" / "__init__.py").exists()
-
-
def test_run_data_uninstall_removes_electron_userdata(monkeypatch, tmp_path):
home = _make_home(tmp_path)
userdata = tmp_path / "electron-userdata"
diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py
index a36d6313aca..4cdb0f55637 100644
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@ -1,579 +1,164 @@
+"""Real Git local-work safety: caller divergence, restore faults and rescue retention."""
from pathlib import Path
-from subprocess import CalledProcessError
-from types import SimpleNamespace
+import subprocess
from unittest.mock import patch
import pytest
-from hermes_cli import config as hermes_config
-from hermes_cli import main as hermes_main
-from hermes_cli import update_cmd
+from hermes_cli import main as hermes_main, update_cmd
+from tests.hermes_cli.test_update_target_identity import git, update_tree # noqa: F401
[email protected](autouse=True)
-def _patch_gateway_discovery(monkeypatch, isolated_source_completion):
- """Keep cmd_update's gateway auto-restart phase off this machine's gateways.
-
- Tests in this file that reach the full success path (e.g. the #87694
- orphan-history rescue-ref tests) would otherwise hit real gateway
- discovery: an unmocked ``find_gateway_pids`` on a box with a live gateway
- reaches the conftest live-system guard and turns into a spurious
- ``sys.exit(1)`` (#78574). Discovery returning nothing makes the phase a
- clean no-op — none of the tests here assert on gateway restarts.
-
- ``_purge_stale_hermes_modules`` must also be stubbed: it evicts
- ``hermes_cli.gateway`` from ``sys.modules`` mid-update, and the restart
- phase's fresh ``from hermes_cli.gateway import ...`` then loads an
- UNPATCHED copy of the module — silently discarding every mock here and
- letting real gateway discovery (and real ``os.kill``) run on the dev box.
- """
- 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("pm.sync_venv", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd, "_prepare_updated_checkout", lambda *a, **kw: None)
- monkeypatch.setattr("hermes_cli.update_cmd_maint._run_post_update_maintenance", lambda *a, **k: True)
- with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \
- patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \
- patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \
- patch("hermes_cli.update_inventory.collect_runtime_inventory", return_value=None), \
- patch("hermes_cli.update_inventory.report_unaccounted_runtimes", return_value=False), \
- patch.object(hermes_main, "_fleet_probe_expected_runtimes", lambda *a, **kw: False), \
- patch.object(hermes_main, "_purge_stale_hermes_modules", lambda *a, **kw: None), \
- patch("hermes_cli.update_receipt.collect_fleet_versions", return_value=[]):
- yield
-
-
-
-
-
-
-
-
-
-
-
-
-
-# ---------------------------------------------------------------------------
-# Update orchestration fixtures
-# ---------------------------------------------------------------------------
-
-def _setup_update_mocks(monkeypatch, tmp_path):
- """Common setup for cmd_update tests."""
- (tmp_path / ".git").mkdir()
- monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(hermes_main, "_stash_local_changes_if_needed", lambda *a, **kw: None)
- monkeypatch.setattr(hermes_main, "_restore_stashed_changes", lambda *a, **kw: True)
- monkeypatch.setattr(hermes_config, "get_missing_env_vars", lambda required_only=True: [])
- monkeypatch.setattr(hermes_config, "get_missing_config_fields", lambda: [])
- monkeypatch.setattr(hermes_config, "check_config_version", lambda **_kwargs: (5, 5))
- monkeypatch.setattr(hermes_config, "migrate_config", lambda **kw: {"env_added": [], "config_added": []})
-
-
-
-
-
-
-
-
-
-
-
-
-# ---------------------------------------------------------------------------
-# ff-only fallback to reset --hard on diverged history
-# ---------------------------------------------------------------------------
-
-def _make_update_side_effect(
- current_branch="main",
- commit_count="3",
- ff_only_fails=False,
- reset_fails=False,
- fetch_fails=False,
- fetch_stderr="",
- merge_base_exists=True,
- update_ref_fails=False,
- pre_pull_sha_unavailable=False,
- existing_rescue_refs=None,
[email protected]('history,failure,keep', [
+ ('ordinary', None, False), ('ordinary', None, True),
+ ('ordinary', 'reset', False), ('ordinary', 'reset', True),
+ ('orphan', None, False), ('orphan', 'reset', False),
+ ('orphan', 'ref', False), ('orphan', 'head', False),
+])
+def test_update_preserves_local_work_and_rescues_orphan_before_reset(
+ update_tree, monkeypatch, capsys, history, failure, keep,
):
- """Build a subprocess.run side_effect for cmd_update tests.
-
- ``merge_base_exists`` controls the ``git merge-base HEAD origin/<branch>``
- probe used by the ff-only-fallback orphan-history guard (#87694): True
- (default) simulates ordinary divergence (a common ancestor exists, e.g.
- upstream force-push), False simulates orphan/unrelated-history divergence
- (no common ancestor at all).
-
- ``update_ref_fails`` simulates ``git update-ref`` itself failing (disk
- full, permissions) when writing the orphan rescue ref.
-
- ``pre_pull_sha_unavailable`` simulates ``_capture_head_sha`` being unable
- to resolve HEAD before the pull (empty rev-parse output) — the rescue-ref
- guard requires a truthy ``pre_pull_sha`` and must degrade gracefully
- without one.
-
- ``existing_rescue_refs`` simulates the refs already present under
- ``refs/hermes-update-backups/orphan-<branch>-*`` (oldest first) so the
- ``_prune_orphan_rescue_refs`` cleanup pass has something to trim.
- """
- recorded = []
- head_sha_calls = []
-
- def side_effect(cmd, **kwargs):
- recorded.append(cmd)
- joined = " ".join(str(c) for c in cmd)
- if "fetch" in joined and "origin" in joined:
- if fetch_fails:
- return SimpleNamespace(stdout="", stderr=fetch_stderr, returncode=128)
- return SimpleNamespace(stdout="", stderr="", returncode=0)
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return SimpleNamespace(stdout=f"{current_branch}\n", stderr="", returncode=0)
- if "show-current" in joined:
- return SimpleNamespace(stdout=f"{current_branch}\n", stderr="", returncode=0)
- if "rev-parse" in joined and "HEAD" in joined:
- # First call = pre-pull HEAD, every later call = post-pull HEAD
- # (issue #79678's "did HEAD actually move" guard depends on these
- # differing after a successful reset/merge).
- head_sha_calls.append(1)
- if len(head_sha_calls) == 1:
- if pre_pull_sha_unavailable:
- return SimpleNamespace(stdout="", stderr="", returncode=0)
- return SimpleNamespace(
- stdout="1111111111111111111111111111111111111beef\n", stderr="", returncode=0
- )
- return SimpleNamespace(
- stdout="2222222222222222222222222222222222222cafe\n", stderr="", returncode=0
- )
- if "checkout" in joined and "main" in joined:
- return SimpleNamespace(stdout="", stderr="", returncode=0)
- if "rev-list" in joined:
- return SimpleNamespace(stdout=f"{commit_count}\n", stderr="", returncode=0)
- if "merge-base" in joined:
- if merge_base_exists:
- return SimpleNamespace(stdout="abc123deadbeef\n", stderr="", returncode=0)
- return SimpleNamespace(
- stdout="", stderr="fatal: Not a valid commit name origin/main\n", returncode=1
- )
- if "for-each-ref" in joined:
- refs = existing_rescue_refs or []
- return SimpleNamespace(stdout="\n".join(refs) + ("\n" if refs else ""), stderr="", returncode=0)
- if "update-ref" in joined and "-d" in cmd:
- return SimpleNamespace(stdout="", stderr="", returncode=0)
- if "update-ref" in joined:
- if update_ref_fails:
- return SimpleNamespace(
- stdout="", stderr="fatal: unable to write ref\n", returncode=128
- )
- return SimpleNamespace(stdout="", stderr="", returncode=0)
- if "--ff-only" in joined:
- if ff_only_fails:
- return SimpleNamespace(
- stdout="",
- stderr="fatal: Not possible to fast-forward, aborting.\n",
- returncode=128,
- )
- return SimpleNamespace(stdout="Updating abc..def\n", stderr="", returncode=0)
- if "reset" in joined and "--hard" in joined:
- if reset_fails:
- return SimpleNamespace(stdout="", stderr="error: unable to write\n", returncode=1)
- return SimpleNamespace(stdout="HEAD is now at abc123\n", stderr="", returncode=0)
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- return side_effect, recorded
-
-
-# ---------------------------------------------------------------------------
-# Non-main branch → auto-checkout main
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# Fetch failure — friendly error messages
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# reset --hard failure — don't attempt stash restore
-# ---------------------------------------------------------------------------
-
-def test_cmd_update_skips_stash_restore_when_reset_fails(monkeypatch, tmp_path, capsys):
- """When reset --hard fails, stash restore is skipped with a helpful message."""
- _setup_update_mocks(monkeypatch, tmp_path)
- # Re-enable stash so it actually returns a ref
- monkeypatch.setattr(
- hermes_main, "_stash_local_changes_if_needed",
- lambda *a, **kw: "abc123deadbeef",
- )
- restore_calls = []
- monkeypatch.setattr(
- hermes_main, "_restore_stashed_changes",
- lambda *a, **kw: restore_calls.append(1) or True,
- )
-
- side_effect, _ = _make_update_side_effect(ff_only_fails=True, reset_fails=True)
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- with pytest.raises(SystemExit, match="1"):
- hermes_main.cmd_update(SimpleNamespace())
-
- # Stash restore should NOT have been called
- assert len(restore_calls) == 0
-
- out = capsys.readouterr().out
- assert "preserved in stash" in out
-
-
-# ---------------------------------------------------------------------------
-# #87694: orphan/unrelated-history divergence must be backed up to a rescue
-# ref before `reset --hard` discards it (ordinary divergence is unaffected).
-# ---------------------------------------------------------------------------
-
-def test_cmd_update_orphan_history_backs_up_before_reset(monkeypatch, tmp_path, capsys):
- """No common ancestor with origin/<branch> → HEAD is parked behind a
- ``refs/hermes-update-backups/orphan-*`` ref before the reset proceeds."""
- _setup_update_mocks(monkeypatch, tmp_path)
-
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]
- assert len(update_ref_calls) == 1
- ref_name = update_ref_calls[0][update_ref_calls[0].index("update-ref") + 1]
- assert ref_name.startswith("refs/hermes-update-backups/orphan-main-")
- assert update_ref_calls[0][update_ref_calls[0].index("update-ref") + 2] == (
- "1111111111111111111111111111111111111beef"
- )
- # Ref name carries the pre-pull SHA, not just a second-resolution
- # timestamp, so two updates racing within the same second don't collide.
- assert ref_name.endswith("-111111111111")
-
- out = capsys.readouterr().out
- assert "orphan divergence" in out
- assert ref_name in out
- # The user is told the backup is temporary and when it expires.
- assert f"expires after {update_cmd._ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days" in out
-
-
-def test_cmd_update_orphan_rescue_ref_write_failure_message_is_honest(monkeypatch, tmp_path, capsys):
- """When ``git update-ref`` fails, the printed message must not claim a
- backup exists — it should say the write was attempted and failed."""
- _setup_update_mocks(monkeypatch, tmp_path)
-
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False, update_ref_fails=True,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- out = capsys.readouterr().out
- assert "orphan divergence" in out
- assert "backup write failed" in out
- assert "backed up current HEAD" not in out
-
-
-def test_cmd_update_orphan_rescue_refs_pruned_beyond_keep_limit(monkeypatch, tmp_path, capsys):
- """Recent orphan rescue refs beyond the retention count are deleted so a
- repeatedly corrupted install doesn't pin unbounded objects against gc."""
- from datetime import datetime, timedelta, timezone
-
- _setup_update_mocks(monkeypatch, tmp_path)
-
- # All refs are recent (within the age window) so only the count cap
- # applies — the age-expiry path is exercised separately below.
- now = datetime.now(timezone.utc)
- total = update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP + 2
- stale_refs = [
- "refs/hermes-update-backups/orphan-main-"
- f"{(now - timedelta(hours=total - i)).strftime('%Y%m%d-%H%M%S')}-abc"
- for i in range(total)
- ]
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False, existing_rescue_refs=stale_refs,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- delete_calls = [
- c for c in recorded
- if "update-ref" in " ".join(str(x) for x in c) and "-d" in c
- ]
- assert len(delete_calls) == total - update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP
- deleted_refs = {c[c.index("-d") + 1] for c in delete_calls}
- assert deleted_refs == set(stale_refs[: total - update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP])
+ t = update_tree
+ git(t.clone, 'checkout', '-q', 'main')
+ if history == 'orphan':
+ git(t.clone, 'checkout', '--orphan', 'fresh')
+ git(t.clone, 'branch', '-D', 'main')
+ git(t.clone, 'branch', '-m', 'main')
+ (t.clone / 'local.txt').write_text('committed\n', encoding='utf-8')
+ git(t.clone, 'add', 'local.txt')
+ git(t.clone, '-c', 'commit.gpgsign=false', 'commit', '-qm', 'local history')
+ before = git(t.clone, 'rev-parse', 'HEAD')
+ (t.clone / 'untracked.txt').write_text('local edit\n', encoding='utf-8')
+ t.args.channel, t.args.keep_stash = 'main', keep
+ monkeypatch.setattr(hermes_main, '_sync_with_upstream_if_needed', update_cmd._sync_with_upstream_if_needed)
+ monkeypatch.setattr(update_cmd, '_UPDATE_CRITICAL_MODULES', ())
+ original = subprocess.run
+ resets = []
+
+ def fault(command, *args, **kwargs):
+ if 'reset' in command and '--hard' in command:
+ refs = original(['git', 'for-each-ref', '--format=%(objectname)',
+ 'refs/hermes-update-backups/'], cwd=t.clone,
+ check=True, capture_output=True, text=True).stdout.split()
+ assert refs == ([before] if history == 'orphan' and failure not in {'ref', 'head'} else [])
+ resets.append(command)
+ if ((failure == 'ref' and 'update-ref' in command and '-d' not in command)
+ or (failure == 'reset' and 'reset' in command and '--hard' in command)):
+ return subprocess.CompletedProcess(command, 128, stdout='', stderr='fixture I/O refusal')
+ return original(command, *args, **kwargs)
+
+ monkeypatch.setattr(subprocess, 'run', fault)
+ if failure == 'head':
+ monkeypatch.setattr(update_cmd, '_capture_head_sha', lambda *_: None)
+ if failure == 'reset':
+ with pytest.raises(SystemExit) as error:
+ hermes_main.cmd_update(t.args)
+ assert error.value.code == 1
+ assert not t.requests
+ assert git(t.clone, 'rev-parse', 'HEAD') == before
+ assert not (t.clone / 'untracked.txt').exists()
+ else:
+ hermes_main.cmd_update(t.args)
+ assert len(t.requests) == 1
+ assert git(t.clone, 'rev-parse', 'HEAD') == t.newer
+ assert (t.clone / 'untracked.txt').exists() is (not keep)
+ assert len(resets) == 1
+ stashes = git(t.clone, 'stash', 'list')
+ assert bool(stashes) is (keep or failure == 'reset')
+ if stashes:
+ assert git(t.clone, 'show', 'stash@{0}^3:untracked.txt') == 'local edit'
+ output = capsys.readouterr().out
+ if failure == 'ref':
+ assert 'backup write failed' in output and 'backed up current HEAD' not in output
+ if failure == 'reset':
+ assert 'preserved in stash' in output
+ if history == 'orphan' and failure not in {'ref', 'head'}:
+ assert f'expires after {update_cmd._ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days' in output
-def test_cmd_update_orphan_rescue_refs_expired_by_age(monkeypatch, tmp_path, capsys):
- """Rescue refs older than the max-age window are deleted even when the
- count cap alone would have kept them — the age expiry is what bounds a
- multi-GB snapshot's lifetime for a user who never runs another orphan
- incident past the count cap."""
[email protected]('mode', ['count', 'age', 'unparseable'])
+def test_rescue_retention_uses_real_refs(tmp_path, monkeypatch, mode):
from datetime import datetime, timedelta, timezone
- _setup_update_mocks(monkeypatch, tmp_path)
-
+ git(tmp_path, 'init', '-q', '-b', 'main')
+ git(tmp_path, '-c', 'user.name=Fixture', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'base')
now = datetime.now(timezone.utc)
- old = now - timedelta(days=update_cmd._ORPHAN_RESCUE_REF_MAX_AGE_DAYS + 5)
- fresh = now - timedelta(days=1)
- expired_ref = (
- "refs/hermes-update-backups/orphan-main-"
- f"{old.strftime('%Y%m%d-%H%M%S')}-old1"
- )
- fresh_ref = (
- "refs/hermes-update-backups/orphan-main-"
- f"{fresh.strftime('%Y%m%d-%H%M%S')}-new1"
- )
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False,
- existing_rescue_refs=[expired_ref, fresh_ref],
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- delete_calls = [
- c for c in recorded
- if "update-ref" in " ".join(str(x) for x in c) and "-d" in c
- ]
- deleted_refs = {c[c.index("-d") + 1] for c in delete_calls}
- assert deleted_refs == {expired_ref}
-
-
-def test_prune_orphan_rescue_refs_leaves_unparseable_names_alone():
- """A ref whose timestamp segment doesn't parse must never be age-deleted
- (it can still fall to the count cap, but not to a guessed age)."""
- from types import SimpleNamespace as NS
- from unittest.mock import patch as mock_patch
-
- weird = "refs/hermes-update-backups/orphan-main-not-a-timestamp-xyz"
- calls = []
-
- def fake_run(cmd, **kwargs):
- calls.append(cmd)
- if "for-each-ref" in cmd:
- return NS(stdout=weird + "\n", stderr="", returncode=0)
- return NS(stdout="", stderr="", returncode=0)
-
- with mock_patch.object(hermes_main.subprocess, "run", side_effect=fake_run):
- update_cmd._prune_orphan_rescue_refs(["git"], ".", "main")
-
- delete_calls = [c for c in calls if "update-ref" in c and "-d" in c]
- assert delete_calls == []
-
-
-def test_cmd_update_ordinary_divergence_skips_rescue_ref(monkeypatch, tmp_path, capsys):
- """Common ancestor still exists (e.g. upstream force-push) → no rescue
- ref, no orphan messaging, behavior identical to before #87694."""
- _setup_update_mocks(monkeypatch, tmp_path)
-
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=True,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]
- assert update_ref_calls == []
-
- out = capsys.readouterr().out
- assert "orphan divergence" not in out
- assert "Fast-forward not possible (history diverged), resetting to match remote" in out
-
-
-def test_cmd_update_orphan_rescue_ref_write_failure_is_non_fatal(monkeypatch, tmp_path, capsys):
- """#87694 stress test: ``git update-ref`` itself fails (disk full,
- permissions) while parking the orphan rescue ref. The backup attempt is
- best-effort — so the reset must still proceed and the update succeed."""
- _setup_update_mocks(monkeypatch, tmp_path)
-
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False, update_ref_fails=True,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]
- assert len(update_ref_calls) == 1
-
- reset_calls = [
- c for c in recorded if "reset" in " ".join(str(x) for x in c) and "--hard" in c
- ]
- assert len(reset_calls) == 1
-
- out = capsys.readouterr().out
- assert "orphan divergence" in out
-
-
-def test_cmd_update_orphan_guard_skips_rescue_ref_when_pre_pull_sha_missing(
- monkeypatch, tmp_path, capsys
-):
- """#87694 stress test: if capturing the pre-pull HEAD SHA itself fails
- (empty ``rev-parse HEAD`` output), the rescue-ref guard requires a
- truthy ``pre_pull_sha`` and must skip the backup rather than writing a
- ref pointing at nothing — the reset must still proceed without crashing.
- """
- _setup_update_mocks(monkeypatch, tmp_path)
-
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False, pre_pull_sha_unavailable=True,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace())
-
- update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]
- assert update_ref_calls == []
-
- out = capsys.readouterr().out
- assert "orphan divergence" not in out
-
-
-def test_cmd_update_orphan_rescue_ref_persists_when_reset_fails(monkeypatch, tmp_path, capsys):
- """#87694 stress test: even when the subsequent ``reset --hard`` itself
- fails, the rescue ref must already have been written — the backup is
- not lost just because the overall update aborts."""
- _setup_update_mocks(monkeypatch, tmp_path)
-
- side_effect, recorded = _make_update_side_effect(
- ff_only_fails=True, merge_base_exists=False, reset_fails=True,
- )
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main.cmd_update(SimpleNamespace())
- assert exc_info.value.code == 1
-
- update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)]
- assert len(update_ref_calls) == 1
-
- out = capsys.readouterr().out
- assert "orphan divergence" in out
- assert "Failed to reset to origin/main" in out
-
-
-# ---------------------------------------------------------------------------
-# Non-interactive update.non_interactive_local_changes setting
-# (chat app / gateway): "discard" throws stashed changes away, "stash"
-# (default) restores them. Interactive terminal updates ignore the setting
-# and always go through the restore path.
-# ---------------------------------------------------------------------------
-
-def _setup_setting_test(monkeypatch, tmp_path, mode):
- """Common wiring: real stash returns a ref, restore + discard are
- recorded, and load_config reports the given non_interactive_local_changes
- mode."""
- _setup_update_mocks(monkeypatch, tmp_path)
- monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/uv" if name == "uv" else None)
- monkeypatch.setattr(
- hermes_main, "_stash_local_changes_if_needed",
- lambda *a, **kw: "abc123deadbeef",
- )
- restore_calls = []
- discard_calls = []
- monkeypatch.setattr(
- hermes_main, "_restore_stashed_changes",
- lambda *a, **kw: restore_calls.append(1) or True,
- )
- monkeypatch.setattr(
- hermes_main, "_discard_stashed_changes",
- lambda *a, **kw: discard_calls.append(1) or True,
- )
- monkeypatch.setattr(
- hermes_config, "load_config",
- lambda *a, **kw: {"updates": {"non_interactive_local_changes": mode}},
- )
- side_effect, recorded = _make_update_side_effect()
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
- return restore_calls, discard_calls, recorded
-
-
-# ---------------------------------------------------------------------------
-# --keep-stash (desktop updater): stash for the update, never re-apply.
-# ---------------------------------------------------------------------------
-
-def _setup_keep_stash_test(monkeypatch, tmp_path):
- """Wiring for --keep-stash tests: stash returns a ref; restore, discard,
- and park are all recorded."""
- _setup_update_mocks(monkeypatch, tmp_path)
- monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/uv" if name == "uv" else None)
- monkeypatch.setattr(
- hermes_main, "_stash_local_changes_if_needed",
- lambda *a, **kw: "abc123deadbeef",
- )
- restore_calls = []
- discard_calls = []
- park_calls = []
- monkeypatch.setattr(
- hermes_main, "_restore_stashed_changes",
- lambda *a, **kw: restore_calls.append(1) or True,
- )
- monkeypatch.setattr(
- hermes_main, "_discard_stashed_changes",
- lambda *a, **kw: discard_calls.append(1) or True,
- )
- monkeypatch.setattr(
- hermes_main, "_park_stashed_changes",
- lambda *a, **kw: park_calls.append(a) or None,
- )
- # Keep the update flow away from the real gateway fleet on this machine —
- # a live gateway PID would trip the test-suite kill guard and turn the
- # run into exit 1 (gateway_fleet_restart_incomplete).
- monkeypatch.setattr(
- "hermes_cli.gateway.find_gateway_pids", lambda **kw: [], raising=False
- )
- return restore_calls, discard_calls, park_calls
-
-
-def test_update_keep_stash_parks_instead_of_restoring(monkeypatch, tmp_path):
- """--keep-stash: after a successful update, the autostash is parked (left
- in git stash) — never re-applied, never discarded."""
- restore_calls, discard_calls, park_calls = _setup_keep_stash_test(monkeypatch, tmp_path)
- side_effect, _ = _make_update_side_effect()
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace(yes=True, keep_stash=True))
-
- assert len(park_calls) == 1
- assert park_calls[0][0] == "abc123deadbeef"
- assert restore_calls == []
- assert discard_calls == []
-
-
-def test_update_without_keep_stash_still_restores(monkeypatch, tmp_path):
- """Regression guard: default behavior (no --keep-stash) is unchanged —
- the autostash is auto-restored under --yes."""
- restore_calls, discard_calls, park_calls = _setup_keep_stash_test(monkeypatch, tmp_path)
- side_effect, _ = _make_update_side_effect()
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- hermes_main.cmd_update(SimpleNamespace(yes=True, keep_stash=False))
-
- assert restore_calls == [1]
- assert park_calls == []
- assert discard_calls == []
-
-
-def test_update_keep_stash_failure_path_still_preserves(monkeypatch, tmp_path, capsys):
- """--keep-stash + failed update: neither restore nor park runs; the
- existing preserved-in-stash message fires (working tree unknown)."""
- restore_calls, discard_calls, park_calls = _setup_keep_stash_test(monkeypatch, tmp_path)
- side_effect, _ = _make_update_side_effect(ff_only_fails=True, reset_fails=True)
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
-
- with pytest.raises(SystemExit, match="1"):
- hermes_main.cmd_update(SimpleNamespace(yes=True, keep_stash=True))
-
- assert restore_calls == []
- assert park_calls == []
- assert discard_calls == []
- assert "preserved in stash" in capsys.readouterr().out
+ prefix = 'refs/hermes-update-backups/orphan-main-'
+ if mode == 'count':
+ refs = [prefix + (now - timedelta(hours=20-i)).strftime('%Y%m%d-%H%M%S') + '-abc'
+ for i in range(update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP + 2)]
+ removed = set(refs[:2])
+ elif mode == 'age':
+ refs = [prefix + '20200101-000000-abc', prefix + now.strftime('%Y%m%d-%H%M%S') + '-abc']
+ removed = {refs[0]}
+ else:
+ refs, removed = [prefix + 'not-a-timestamp-abc'], set()
+ for ref in refs:
+ git(tmp_path, 'update-ref', ref, 'HEAD')
+ update_cmd._prune_orphan_rescue_refs(['git'], tmp_path, 'main')
+ assert set(git(tmp_path, 'for-each-ref', '--format=%(refname)', 'refs/hermes-update-backups/').splitlines()) == set(refs) - removed
+
+
[email protected]('fault,body,modules,message', [
+ ('syntax', '<<<<<<< Updated upstream\nVALUE = 2\n', (), 'made the Hermes agent unexecutable'),
+ ('import', "raise RuntimeError('restored local failure')\n", ('consumer',), 'restored local failure'),
+ ('preexisting', 'VALUE = 2\n', ('first',), None),
+ ('later', "raise RuntimeError('restored later failure')\n", ('first', 'consumer'), 'restored later failure'),
+ ('exit', "raise SystemExit('restored exit')\n", ('first', 'consumer'), 'restored exit'),
+ ('terminated', 'import os\nos._exit(7)\n', ('consumer',), 'exit code 7'),
+ ('paths', 'VALUE = 2\n', (), 'restored Python source discovery'),
+])
+def test_restore_validates_real_stash_and_each_import(tmp_path, monkeypatch, capsys, fault, body, modules, message):
+ import hermes_cli.update_cmd_stash as stash
+
+ git(tmp_path, 'init', '-q', '-b', 'main')
+ (tmp_path / 'first.py').write_text("raise RuntimeError('missing local config')\n", encoding='utf-8')
+ source = tmp_path / 'consumer.py'
+ source.write_text('VALUE = 1\n', encoding='utf-8')
+ git(tmp_path, 'add', 'first.py', 'consumer.py')
+ git(tmp_path, '-c', 'user.name=Fixture', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', 'commit', '-qm', 'base')
+ source.write_text(body, encoding='utf-8')
+ ref = hermes_main._stash_local_changes_if_needed(['git'], tmp_path)
+ assert ref
+ monkeypatch.setattr(update_cmd, '_UPDATE_CRITICAL_MODULES', modules)
+ if fault == 'paths':
+ monkeypatch.setattr(stash, '_restored_python_paths', lambda *_: None)
+ monkeypatch.setattr(update_cmd, '_restored_python_paths', lambda *_: None)
+ if message is None:
+ assert hermes_main._restore_stashed_changes(['git'], tmp_path, ref, prompt_user=False)
+ assert source.read_text(encoding='utf-8') == body
+ assert not git(tmp_path, 'stash', 'list')
+ else:
+ with pytest.raises(SystemExit) as error:
+ hermes_main._restore_stashed_changes(['git'], tmp_path, ref, prompt_user=False)
+ assert error.value.code == 1
+ assert source.read_text(encoding='utf-8') == 'VALUE = 1\n'
+ assert not git(tmp_path, 'status', '--porcelain')
+ assert git(tmp_path, 'stash', 'list')
+ output = capsys.readouterr().out
+ assert message in output and 'gateway was not restarted' in output
+ assert f'git stash apply {ref}' in output
+
+
[email protected]('error', [EOFError(), UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'invalid')])
+def test_unreadable_stash_prompt_keeps_work(tmp_path, monkeypatch, capsys, error):
+ def unreadable(*_):
+ raise error
+ monkeypatch.setattr('builtins.input', unreadable)
+ assert hermes_main._restore_stashed_changes(['git'], tmp_path, 'stash@{0}', prompt_user=True) is False
+ assert 'git stash apply stash@{0}' in capsys.readouterr().out
+
+
+def test_unreadable_upstream_prompt_does_not_add_remote(tmp_path, monkeypatch):
+ git(tmp_path, 'init', '-q', '-b', 'main')
+ def unreadable(*_):
+ raise UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'invalid')
+ monkeypatch.setattr('builtins.input', unreadable)
+ monkeypatch.setattr(update_cmd, '_should_skip_upstream_prompt', lambda *_: False)
+ update_cmd._sync_with_upstream_if_needed(['git'], tmp_path)
+ assert not git(tmp_path, 'remote')
def test_update_parser_accepts_keep_stash():
@@ -593,9 +178,6 @@ def test_update_parser_accepts_keep_stash():
-
-
-
def test_bootstrap_marker_not_autostashed_by_update(tmp_path):
"""#38529: the Desktop bootstrap marker must be git-ignored so that
``hermes update``'s ``git stash push --include-untracked`` does not sweep it
@@ -643,15 +225,6 @@ def test_bootstrap_marker_not_autostashed_by_update(tmp_path):
assert ".hermes-bootstrap-complete" not in status
-# ---------------------------------------------------------------------------
-# Permission-denied autostash class: undeletable untracked files (root-owned
-# packaging/ etc.) must not abort the update when the stash entry was created.
-# ---------------------------------------------------------------------------
-
-
-
-
-
def test_update_autostash_survives_undeletable_untracked_dir(tmp_path):
"""Behavioral E2E of the whole permission-denied class with real git:
@@ -702,267 +275,6 @@ def test_update_autostash_survives_undeletable_untracked_dir(tmp_path):
os.chmod(pkg, 0o755)
-def test_restore_rejects_invalid_python_and_keeps_clean_updated_tree(
- monkeypatch, tmp_path, capsys
-):
- """A cleanly-applied stash must not be allowed to brick every agent turn."""
- import subprocess
- from hermes_cli import update_cmd
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- source = tmp_path / "tools" / "terminal_tool.py"
- source.parent.mkdir()
- source.write_text("VALUE = 1\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
-
- source.write_text("<<<<<<< Updated upstream\nVALUE = 2\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ())
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
-
- assert exc_info.value.code == 1
- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"
- assert git("status", "--porcelain").stdout == ""
- assert git("stash", "list").stdout.strip()
- output = capsys.readouterr().out
- assert "made the Hermes agent unexecutable" in output
- assert "gateway was not restarted" in output
- assert f"git stash apply {stash_ref}" in output
-
-
-def test_restore_rejects_new_import_time_failure_and_preserves_stash(
- monkeypatch, tmp_path, capsys
-):
- """A valid-Python stash must not introduce a critical import failure."""
- import subprocess
- from hermes_cli import update_cmd
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- source = tmp_path / "consumer.py"
- source.write_text("VALUE = 1\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
-
- source.write_text("raise RuntimeError('restored local failure')\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
-
- assert exc_info.value.code == 1
- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"
- assert git("status", "--porcelain").stdout == ""
- assert git("stash", "list").stdout.strip()
- output = capsys.readouterr().out
- assert "agent import consumer" in output
- assert "restored local failure" in output
- assert "gateway was not restarted" in output
-
-
-def test_restore_allows_preexisting_import_time_failure(monkeypatch, tmp_path):
- """A restore may proceed when it does not worsen an environment failure."""
- import subprocess
- from hermes_cli import update_cmd
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- (tmp_path / "consumer.py").write_text(
- "raise RuntimeError('missing local config')\n", encoding="utf-8"
- )
- local_file = tmp_path / "local.txt"
- local_file.write_text("original\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
-
- local_file.write_text("restored\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
-
- assert hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
- assert local_file.read_text(encoding="utf-8") == "restored\n"
- assert git("stash", "list").stdout.strip() == ""
-
-
-def test_restore_rejects_later_failure_masked_by_preexisting_failure(
- monkeypatch, tmp_path, capsys
-):
- """Every critical module must be compared, not only the first failure."""
- import subprocess
- from hermes_cli import update_cmd
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- (tmp_path / "first.py").write_text(
- "raise RuntimeError('missing local config')\n", encoding="utf-8"
- )
- second = tmp_path / "second.py"
- second.write_text("VALUE = 1\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
-
- second.write_text("raise RuntimeError('restored later failure')\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("first", "second"))
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
-
- assert exc_info.value.code == 1
- assert second.read_text(encoding="utf-8") == "VALUE = 1\n"
- assert git("status", "--porcelain").stdout == ""
- assert git("stash", "list").stdout.strip()
- output = capsys.readouterr().out
- assert "agent import second" in output
- assert "restored later failure" in output
- assert "gateway was not restarted" in output
-
-
-def test_restore_rejects_system_exit_masked_by_preexisting_failure(
- monkeypatch, tmp_path, capsys
-):
- """A terminating import must be compared instead of hiding the marker."""
- import subprocess
- from hermes_cli import update_cmd
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- (tmp_path / "first.py").write_text(
- "raise RuntimeError('missing local config')\n", encoding="utf-8"
- )
- second = tmp_path / "second.py"
- second.write_text("VALUE = 1\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
-
- second.write_text("raise SystemExit('restored exit')\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("first", "second"))
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
-
- assert exc_info.value.code == 1
- assert second.read_text(encoding="utf-8") == "VALUE = 1\n"
- assert git("status", "--porcelain").stdout == ""
- assert git("stash", "list").stdout.strip()
- output = capsys.readouterr().out
- assert "agent import second" in output
- assert "restored exit" in output
- assert "gateway was not restarted" in output
-
-
-def test_restore_rejects_probe_termination(monkeypatch, tmp_path, capsys):
- """A stash cannot bypass import validation by terminating the probe."""
- import subprocess
- from hermes_cli import update_cmd
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- source = tmp_path / "consumer.py"
- source.write_text("VALUE = 1\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
-
- source.write_text("import os\nos._exit(7)\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
-
- assert exc_info.value.code == 1
- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"
- assert git("status", "--porcelain").stdout == ""
- assert git("stash", "list").stdout.strip()
- output = capsys.readouterr().out
- assert "critical-module probe" in output
- assert "exit code 7" in output
- assert "gateway was not restarted" in output
-
def test_restore_stays_parked_when_untracked_baseline_is_unknown(
monkeypatch, tmp_path, capsys
@@ -984,6 +296,7 @@ def test_restore_stays_parked_when_untracked_baseline_is_unknown(
assert "git stash apply stash@{0}" in output
+
def test_reject_does_not_claim_cleanup_when_git_state_is_unknown(
monkeypatch, tmp_path, capsys
):
@@ -1004,50 +317,6 @@ def test_reject_does_not_claim_cleanup_when_git_state_is_unknown(
assert "The clean updated tree has been restored" not in output
-def test_restore_rejects_unknown_restored_python_paths(
- monkeypatch, tmp_path, capsys
-):
- """A failed post-apply path query cannot skip restored syntax validation."""
- import subprocess
- from hermes_cli import update_cmd
- import hermes_cli.update_cmd_stash as update_cmd_stash
-
- def git(*args, check=True):
- return subprocess.run(
- ["git", *args],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=check,
- )
-
- git("init", "-q", "-b", "main")
- git("config", "user.email", "[email protected]")
- git("config", "user.name", "t")
- source = tmp_path / "consumer.py"
- source.write_text("VALUE = 1\n", encoding="utf-8")
- git("add", "-A")
- git("commit", "-qm", "init")
- source.write_text("VALUE = 2\n", encoding="utf-8")
- stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
- assert stash_ref
- monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ())
- monkeypatch.setattr(update_cmd, "_restored_python_paths", lambda *_args: None)
- monkeypatch.setattr(update_cmd_stash, "_restored_python_paths", lambda *_args: None)
-
- with pytest.raises(SystemExit) as exc_info:
- hermes_main._restore_stashed_changes(
- ["git"], tmp_path, stash_ref, prompt_user=False
- )
-
- assert exc_info.value.code == 1
- assert source.read_text(encoding="utf-8") == "VALUE = 1\n"
- assert git("status", "--porcelain").stdout == ""
- assert git("stash", "list").stdout.strip()
- output = capsys.readouterr().out
- assert "restored Python source discovery" in output
- assert "gateway was not restarted" in output
-
def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys):
prompts = []
@@ -1065,74 +334,6 @@ def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys):
assert "still preserved in git stash" in capsys.readouterr().out
-# ---------------------------------------------------------------------------
-# #87694: real-git sanity check for the merge-base premise the orphan guard
-# relies on — two independently-initialized repos (no shared history) must
-# report no merge-base, while an ordinary branch divergence must report one.
-# ---------------------------------------------------------------------------
-
-def test_merge_base_detects_orphan_vs_ordinary_divergence_with_real_git(tmp_path):
- """Anchors the assumption behind the #87694 orphan-history guard: `git
- merge-base` fails/empties on truly unrelated histories, and succeeds on
- ordinary (e.g. force-pushed) divergence. If a future git version changes
- this contract, this test breaks instead of the guard silently going
- inert."""
- import shutil
- import subprocess
-
- if shutil.which("git") is None:
- pytest.skip("git not available")
-
- def git(cwd, *args, check=True):
- return subprocess.run(
- ["git", *args], cwd=cwd, capture_output=True, text=True, check=check
- )
-
- # Ordinary divergence: two branches of the SAME repo, one reset to an
- # earlier point then given a new commit (simulates an upstream force-push).
- ordinary = tmp_path / "ordinary"
- ordinary.mkdir()
- git(ordinary, "init", "-q", "-b", "main")
- git(ordinary, "config", "user.email", "[email protected]")
- git(ordinary, "config", "user.name", "t")
- (ordinary / "f.txt").write_text("v1\n")
- git(ordinary, "add", "-A")
- git(ordinary, "commit", "-qm", "init")
- git(ordinary, "checkout", "-qb", "origin-main")
- (ordinary / "f.txt").write_text("v2\n")
- git(ordinary, "add", "-A")
- git(ordinary, "commit", "-qm", "upstream")
- git(ordinary, "checkout", "-q", "main")
- result = git(ordinary, "merge-base", "HEAD", "origin-main", check=False)
- assert result.returncode == 0
- assert result.stdout.strip()
-
- # Orphan divergence: two independently-init'd repos wired as remotes,
- # sharing zero history.
- orphan = tmp_path / "orphan"
- orphan.mkdir()
- git(orphan, "init", "-q", "-b", "main")
- git(orphan, "config", "user.email", "[email protected]")
- git(orphan, "config", "user.name", "t")
- (orphan / "f.txt").write_text("local\n")
- git(orphan, "add", "-A")
- git(orphan, "commit", "-qm", "local init")
-
- remote = tmp_path / "orphan-remote"
- remote.mkdir()
- git(remote, "init", "-q", "-b", "main")
- git(remote, "config", "user.email", "[email protected]")
- git(remote, "config", "user.name", "t")
- (remote / "f.txt").write_text("remote\n")
- git(remote, "add", "-A")
- git(remote, "commit", "-qm", "remote init")
-
- git(orphan, "remote", "add", "origin", str(remote))
- git(orphan, "fetch", "-q", "origin")
- result = git(orphan, "merge-base", "HEAD", "origin/main", check=False)
- assert result.returncode != 0
- assert not result.stdout.strip()
-
def test_prune_orphan_rescue_refs_with_real_git_unpins_objects(tmp_path):
"""End-to-end with real git: an orphan rescue ref pins a snapshot's
diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.py
index ea3edceb95e..6d6f7a3d5c5 100644
--- a/tests/hermes_cli/test_update_channel.py
+++ b/tests/hermes_cli/test_update_channel.py
@@ -71,11 +71,6 @@ class TestInstallId:
class TestResolve:
- def test_per_install_record_wins(self, tmp_path):
- root = tmp_path / "install"
- _stamp(root, "self")
- config = _config_for(root, "stable")
- assert resolve_update_channel(config, root) == CHANNEL_STABLE
def test_multi_install_isolation(self, tmp_path):
"""Two installs, one config: each resolves its own record and a
@@ -88,80 +83,33 @@ class TestResolve:
assert resolve_update_channel(config, a) == CHANNEL_STABLE
assert resolve_update_channel(config, b) == CHANNEL_MAIN
- def test_defaults_by_mechanism(self, tmp_path):
- source = tmp_path / "src"
- bundle = tmp_path / "bundle"
- _stamp(source, "self")
- _stamp(bundle, "electron-updater", tag="v0.27.0")
- assert default_channel(source) == CHANNEL_MAIN
- assert default_channel(bundle) == CHANNEL_STABLE
- assert resolve_update_channel({}, source) == CHANNEL_MAIN
- assert resolve_update_channel({}, bundle) == CHANNEL_STABLE
-
- @pytest.mark.parametrize("mechanism", ["electron-updater", "app-installer", "microsoft-store"])
- def test_canary_artifact_defaults_to_its_own_feed(self, tmp_path, mechanism):
- """A canary bundle with no per-install record tracks canary.
-
- The artifact publishes to canary.yml (product-identity.cjs keys the
- feed on this same tag). Defaulting it to stable made the updater ask
- for canary.yml under the newest STABLE release, which 404s and
- leaves a fresh canary install unable to update at all.
- """
- root = tmp_path / "canary-bundle"
- _stamp(root, mechanism, tag="v0.28.0-canary.20260819171926")
- assert default_channel(root) == CHANNEL_CANARY
- assert resolve_update_channel({}, root) == CHANNEL_CANARY
-
- def test_legacy_date_only_canary_tag_is_a_canary(self, tmp_path):
- root = tmp_path / "legacy-canary"
- _stamp(root, "electron-updater", tag="v0.28.0-canary.20260818")
- assert default_channel(root) == CHANNEL_CANARY
-
- def test_artifact_channel_ignores_obsolete_record(self, tmp_path):
- """A record cannot change a separately installed package identity."""
- root = tmp_path / "canary-bundle"
- _stamp(root, "electron-updater", tag="v0.28.0-canary.20260819171926")
- assert resolve_update_channel(_config_for(root, "stable"), root) == CHANNEL_CANARY
-
- def test_a_canary_tag_on_a_source_install_is_not_a_canary_channel(self, tmp_path):
- """Only electron-updater bundles have release feeds to track."""
- root = tmp_path / "src"
- _stamp(root, "self", tag="v0.28.0-canary.20260819171926")
- assert default_channel(root) == CHANNEL_MAIN
-
- def test_stampless_tree_defaults_to_main(self, tmp_path):
- root = tmp_path / "bare"
- root.mkdir()
- assert resolve_update_channel({}, root) == CHANNEL_MAIN
-
- def test_canary_remains_a_release_channel_for_source(self, tmp_path):
- root = tmp_path / "src"
- _stamp(root, "self")
- config = _config_for(root, "canary")
- assert resolve_update_channel(config, root) == CHANNEL_CANARY
-
- def test_stable_bundle_ignores_canary_record(self, tmp_path):
- root = tmp_path / "bundle"
- _stamp(root, "electron-updater")
- config = _config_for(root, "canary")
- assert resolve_update_channel(config, root) == CHANNEL_STABLE
-
- @pytest.mark.parametrize("payload", ["bundled", "light"])
- @pytest.mark.parametrize("channel, tag", [
- ("stable", "v1.2.3"), ("canary", "v1.2.4-canary.20260911125822"),
+ @pytest.mark.parametrize('mechanism,tag,payload,record,expected', [
+ ('self', None, None, None, 'main'),
+ ('self', 'v1.2.3-canary.20260818', None, None, 'main'),
+ (None, None, None, None, 'main'),
+ ('self', None, None, 'canary', 'canary'),
+ ('self', None, None, 'yolo', 'main'),
+ ('electron-updater', 'v1.2.3', None, None, 'stable'),
+ ('electron-updater', 'v1.2.3-canary.20260819171926', None, 'stable', 'canary'),
+ ('app-installer', 'v1.2.3-canary.20260819171926', None, None, 'canary'),
+ ('microsoft-store', 'v1.2.3-canary.20260819171926', None, None, 'canary'),
+ ('electron-updater', 'v1.2.3-canary.20260818', None, None, 'canary'),
+ ('electron-updater', None, None, 'canary', 'stable'),
+ ('external', 'v1.2.3', 'bundled', 'main', 'stable'),
+ ('external', 'v1.2.3', 'light', 'main', 'stable'),
+ ('external', 'v1.2.4-canary.20260911125822', 'bundled', 'main', 'canary'),
+ ('external', 'v1.2.4-canary.20260911125822', 'light', 'main', 'canary'),
])
- def test_external_packages_ignore_source_channel_records(self, tmp_path, payload, channel, tag):
- (tmp_path / "install-stamp.json").write_text(json.dumps({
- "payload": payload, "updateMechanism": "external", "tag": tag,
- }))
- assert resolve_update_channel(_config_for(tmp_path, "main"), tmp_path) == channel
- assert default_channel(tmp_path) == channel
-
- def test_garbage_record_falls_to_default(self, tmp_path):
- root = tmp_path / "src"
- _stamp(root, "self")
- config = _config_for(root, "yolo")
- assert resolve_update_channel(config, root) == CHANNEL_MAIN
+ def test_channel_policy(self, tmp_path, mechanism, tag, payload, record, expected):
+ if mechanism is not None:
+ stamp = {'updateMechanism': mechanism, 'tag': tag}
+ if payload:
+ stamp['payload'] = payload
+ (tmp_path / 'install-stamp.json').write_text(json.dumps(stamp), encoding='utf-8')
+ config = _config_for(tmp_path, record) if record else {}
+ assert resolve_update_channel(config, tmp_path) == expected
+ if not (mechanism == 'self' and record == 'canary'):
+ assert default_channel(tmp_path) == expected
class TestSetChannel:
@@ -188,55 +136,7 @@ class TestSetChannel:
assert record["path"] == str(root)
assert resolve_update_channel(written, root) == channel
- def test_preserves_other_config_and_other_installs(self, tmp_path, monkeypatch):
- import hermes_yaml as yaml
- home = self._home(tmp_path, monkeypatch)
- other = tmp_path / "other"
- other.mkdir()
- (home / "config.yaml").write_text(
- yaml.safe_dump(
- {
- "model": {"provider": "nous"},
- "update": {
- "installs": {
- install_id(other): {"path": str(other), "channel": "canary"}
- }
- },
- }
- )
- )
- root = tmp_path / "install"
- _stamp(root, "self")
- set_install_channel("stable", root)
-
- written = yaml.safe_load((home / "config.yaml").read_text())
- assert written["model"] == {"provider": "nous"}
- assert written["update"]["installs"][install_id(other)]["channel"] == "canary"
- assert written["update"]["installs"][install_id(root)]["channel"] == "stable"
-
- def test_preserves_comments_in_config(self, tmp_path, monkeypatch):
- """Persisting a channel must not strip user comments from
- config.yaml — the write goes through the shared comment-preserving
- atomic round-trip writer."""
- home = self._home(tmp_path, monkeypatch)
- (home / "config.yaml").write_text(
- "# my hand-maintained settings\n"
- "model:\n"
- " provider: nous # keep this\n"
- )
- root = tmp_path / "install"
- _stamp(root, "self")
- set_install_channel("stable", root)
-
- text = (home / "config.yaml").read_text()
- assert "# my hand-maintained settings" in text
- assert "# keep this" in text
- import hermes_yaml as yaml
-
- written = yaml.safe_load(text)
- assert written["model"] == {"provider": "nous"}
- assert written["update"]["installs"][install_id(root)]["channel"] == "stable"
@pytest.mark.parametrize("mechanism", ["external", "electron-updater", "app-installer", "microsoft-store"])
def test_os_owned_mechanism_refuses_channel_writes(self, tmp_path, monkeypatch, mechanism):
@@ -434,84 +334,24 @@ class TestSetChannelCLI:
assert "Back up your data" in out
assert "older stable release" in out
assert "Wait" not in out
- def test_canary_optin_warns_about_forward_incompatible_state(self, capsys):
- from unittest.mock import patch
-
- from hermes_cli.main import cmd_update
- with (
- patch("hermes_cli.config.is_managed", return_value=False),
- patch("hermes_cli.config.detect_install_method", return_value="unknown"),
- patch("hermes_cli.update_channel.set_install_channel", return_value="a" * 16),
- ):
- with pytest.raises(SystemExit) as exc:
- cmd_update(self._args(set_channel="canary"))
- assert exc.value.code == 0
- out = capsys.readouterr().out
- assert "forward-incompatible" in out
-
- def test_install_id_prints_and_exits(self, capsys):
- from unittest.mock import patch
- from hermes_cli.main import cmd_update
- with (
- patch("hermes_cli.config.is_managed", return_value=False),
- patch("hermes_cli.update_channel.install_id", return_value="b" * 16),
- ):
- with pytest.raises(SystemExit) as exc:
- cmd_update(self._args(install_id=True))
- assert exc.value.code == 0
- assert "b" * 16 in capsys.readouterr().out
-
-
-class TestDoctorStaleness:
- def test_missing_path_flagged(self, tmp_path):
- gone = tmp_path / "gone"
- config = {
- "update": {"installs": {"deadbeefdeadbeef": {"path": str(gone), "channel": "main"}}}
- }
- stale = stale_channel_records(config)
- assert [(sha, reason) for sha, _r, reason in stale] == [
- ("deadbeefdeadbeef", "missing")
- ]
-
- def test_replaced_install_flagged(self, tmp_path):
- """The recorded path exists but keys to a different sha16 — the
- record is a leftover from a tree that used to live elsewhere."""
- root = tmp_path / "install"
- root.mkdir()
- config = {
- "update": {"installs": {"0" * 16: {"path": str(root), "channel": "main"}}}
- }
- stale = stale_channel_records(config)
- assert [(sha, reason) for sha, _r, reason in stale] == [("0" * 16, "replaced")]
-
- def test_unclaimed_record_flagged(self, tmp_path, monkeypatch):
- """sha16 matches the path but no installs/<sha16>/install.json exists."""
- home = tmp_path / ".hermes"
- home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(home))
- root = tmp_path / "install"
[email protected]('kind,expected', [('missing', 'missing'), ('replaced', 'replaced'),
+ ('unclaimed', 'unclaimed'), ('healthy', None)])
+def test_doctor_channel_records_are_read_only(tmp_path, monkeypatch, kind, expected):
+ from copy import deepcopy
+ home, root = tmp_path / '.hermes', tmp_path / 'install'
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ if kind != 'missing':
root.mkdir()
- config = _config_for(root, "main")
- stale = stale_channel_records(config)
- assert [(sha, reason) for sha, _r, reason in stale] == [
- (install_id(root), "unclaimed")
- ]
-
- def test_healthy_record_not_flagged(self, tmp_path, monkeypatch):
- home = tmp_path / ".hermes"
- home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(home))
- root = tmp_path / "install"
- _stamp(root, "self")
- # The live install-state record the sha16 must be claimed by
- # (boot_bootstrap.ensure_install_dir writes this at boot; that
- # module is landing in a parallel lane, so write the marker
- # directly — the layout IS the contract).
- state = home / "installs" / install_id(root)
+ key = '0' * 16 if kind == 'replaced' else install_id(root)
+ config = {'update': {'installs': {key: {'path': str(root), 'channel': 'main'}}}}
+ if kind == 'healthy':
+ state = home / 'installs' / key
state.mkdir(parents=True)
- (state / "install.json").write_text(json.dumps({"root": str(root)}))
- config = _config_for(root, "main")
- assert stale_channel_records(config) == []
+ (state / 'install.json').write_text(json.dumps({'root': str(root)}), encoding='utf-8')
+ before = deepcopy(config)
+ assert [(key, reason) for key, _, reason in stale_channel_records(config)] == (
+ [(key, expected)] if expected else [])
+ assert config == before
diff --git a/tests/hermes_cli/test_update_completion_routing.py b/tests/hermes_cli/test_update_completion_routing.py
index 27f4cd2ffdc..bf52e0cf158 100644
--- a/tests/hermes_cli/test_update_completion_routing.py
+++ b/tests/hermes_cli/test_update_completion_routing.py
@@ -4,7 +4,8 @@ from unittest.mock import Mock
import pytest
-from hermes_cli import update_cmd, update_cmd_zip
+from hermes_cli import main, main_web_build, update_cmd, update_cmd_zip, update_cmd_maint
+from tests.compat.old_updater_support import fresh_child, no_external_work # noqa: F401
@pytest.mark.parametrize("hook,args,kwargs", [
@@ -12,12 +13,29 @@ from hermes_cli import update_cmd, update_cmd_zip
(update_cmd._reload_config_modules, (), {}),
(update_cmd._reload_process_scan_modules, (), {}),
(update_cmd._run_pending_fleet_restart, (), {}),
+ (main_web_build._run_with_idle_timeout, (["unused"], "unused"), {"idle_timeout_seconds": 10}),
+ (main_web_build._run_npm_install_deterministic, ("unused", "unused"), {"extra_args": ("arg",)}),
+ (main_web_build._nixos_build_env, (), {}),
+ (main._reexec_dependency_sync_off_windows_shim, (), {}),
+ (update_cmd_maint._print_update_summary, (), {
+ "node_failures": [], "desktop_build_ok": True, "pre_update_version": None}),
+ (update_cmd_maint._print_update_summary, (), {
+ "node_failures": ["dashboard"], "desktop_build_ok": False, "pre_update_version": "0.20.1"}),
+ (update_cmd_maint._finish_dashboard_update_cleanup, ([],), {}),
+ (update_cmd_maint._finish_dashboard_update_cleanup, (["dashboard"],), {
+ "already_restarted_units": {"hermes-serve"}}),
])
-def test_historical_completion_hook_never_reports_success(hook, args, kwargs, capsys):
- with pytest.raises(SystemExit) as error:
+def test_historical_completion_hook_never_reports_success(hook, args, kwargs, fresh_child, capsys):
+ if hook in {update_cmd._prepare_updated_checkout, update_cmd._reload_config_modules,
+ update_cmd._reload_process_scan_modules, update_cmd._run_pending_fleet_restart}:
+ with pytest.raises(SystemExit) as error:
+ hook(*args, **kwargs)
+ assert error.value.code == 1
+ assert fresh_child.requests == []
+ assert 'run `hermes update` again' in capsys.readouterr().err
+ return
+ with fresh_child.exits():
hook(*args, **kwargs)
- assert error.value.code != 0
- assert "update" in capsys.readouterr().err.lower()
def test_incomplete_handoff_requires_explicit_update_retry(tmp_path, monkeypatch, capsys):
diff --git a/tests/hermes_cli/test_update_config_migration_on_current.py b/tests/hermes_cli/test_update_config_migration_on_current.py
index 12175deba64..b7989c72783 100644
--- a/tests/hermes_cli/test_update_config_migration_on_current.py
+++ b/tests/hermes_cli/test_update_config_migration_on_current.py
@@ -1,123 +1,93 @@
-"""Tests for config migration on the \"Already up to date\" repair path.
-
-Covers ``_check_and_apply_config_migration`` on the ``commit_count == 0``
-retry paths (#91360): a previous update attempt can pull new code onto disk
-and then fail before reaching the config-migration block (e.g. PyPI timeout
-during dependency sync); the retry then enters the ``commit_count == 0``
-branch and returns early, skipping config migration entirely. The fresh
-code (which may require a newer ``_config_version``) keeps running against
-the old config and the next Hermes launch refuses to start.
-
-Matrix: config behind / current / ahead of the code's version, plus the
-#86656 contract (quiet-migration warnings must be re-surfaced) and the
-check-failure contract (a config-check failure must not break the repair
-path).
-"""
-
-from __future__ import annotations
-
-import contextlib
-import io
-from hermes_cli import config as update_config
-from unittest.mock import patch
-
-import hermes_cli.update_cmd as update_cmd
-
-
-def _run(current: int, latest: int):
- """Run _check_and_apply_config_migration with mocked config checks.
-
- Returns (stdout, migrate_calls).
- """
- migrate_calls = []
-
- def _fake_migrate(interactive=False, quiet=False):
- migrate_calls.append((interactive, quiet))
- return {"env_added": [], "config_added": [], "warnings": []}
-
- with patch.object(update_cmd, "_reload_config_modules"), patch(
- "hermes_cli.config.get_missing_env_vars", return_value=[]
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=[]
- ), patch.object(
- update_config, "check_config_version", return_value=(current, latest)
- ), patch.object(
- update_config, "migrate_config", side_effect=_fake_migrate
- ), patch.object(
- update_cmd, "_migrate_sibling_profile_configs", return_value=[]
- ):
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- update_cmd._check_and_apply_config_migration()
- return buf.getvalue(), migrate_calls
-
-
-def test_migrates_when_config_behind():
- """Version bump on the repair path must be applied silently."""
- out, calls = _run(current=37, latest=38)
- assert "v37 → v38" in out
- assert "Config format updated" in out
- assert calls == [(False, True)] # non-interactive, quiet
-
-
-def test_noop_when_config_current():
- """No migration when the config version is already current."""
- out, calls = _run(current=38, latest=38)
- assert "Configuration is up to date" in out
- assert calls == []
-
-
-def test_noop_when_config_ahead():
- """No migration when local config is newer than the code's default."""
- out, calls = _run(current=39, latest=38)
- assert "Configuration is up to date" in out
- assert calls == []
-
-
-def test_surfaces_migration_warnings():
- """Warnings from a quiet migration must be re-surfaced (#86656)."""
-
- def _fake_migrate(interactive=False, quiet=False):
- return {
- "env_added": [],
- "config_added": [],
- "warnings": ["personality reset: kawaii → default"],
- }
-
- with patch.object(update_cmd, "_reload_config_modules"), patch(
- "hermes_cli.config.get_missing_env_vars", return_value=[]
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=[]
- ), patch.object(
- update_config, "check_config_version", return_value=(37, 38)
- ), patch.object(
- update_config, "migrate_config", side_effect=_fake_migrate
- ), patch.object(
- update_cmd, "_migrate_sibling_profile_configs", return_value=[]
- ):
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- update_cmd._check_and_apply_config_migration()
- out = buf.getvalue()
-
- assert "personality reset" in out
-
-
-def test_check_failure_does_not_break_repair_path():
- """A config-check failure must not break the repair path."""
- with patch.object(update_cmd, "_reload_config_modules"), patch(
- "hermes_cli.config.get_missing_env_vars", return_value=[]
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=[]
- ), patch.object(
- update_config, "check_config_version", side_effect=RuntimeError("boom")
- ), patch.object(
- update_config, "migrate_config", return_value={}
- ) as mig:
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- # Should not raise and should not attempt migration.
- update_cmd._check_and_apply_config_migration()
- out = buf.getvalue()
- assert "Could not check config version" in out
- mig.assert_not_called()
+"""Migration UX policy; selected-child and real profile writes live in completion tests."""
+import sys
+
+import pytest
+
+from hermes_cli import config, update_cmd
+
+
[email protected]('case,expected', [
+ ('format', [(False, True)]), ('warnings', [(False, True)]),
+ ('migration-error', [(False, True)]), ('current', []), ('ahead', []), ('read-error', []),
+ ('yes', [(False, False)]), ('tty-yes', [(True, False)]), ('tty-decline', []),
+ ('noninteractive', [(False, False)]), ('gateway', [(False, False)]), ('eof', []), ('unicode', []),
+])
+def test_migration_policy(monkeypatch, capsys, case, expected):
+ prompts, calls = [], []
+ named = case in {'yes', 'tty-yes', 'tty-decline', 'noninteractive', 'gateway', 'eof', 'unicode'}
+ monkeypatch.setattr(config, 'get_missing_env_vars', lambda **_: [
+ {'name': 'NEW_TOKEN', 'description': 'new credential'}] if named else [])
+ monkeypatch.setattr(config, 'get_missing_config_fields', lambda: [
+ {'key': 'new.option', 'description': 'new option'}] if named else [])
+
+ def version(**kwargs):
+ assert kwargs == {'raise_on_parse_error': True}
+ if case == 'read-error':
+ raise RuntimeError('cannot read config')
+ return (4 if case == 'ahead' else 3 if case == 'current' else 2, 3)
+
+ def migrate(*, interactive, quiet):
+ calls.append((interactive, quiet))
+ if case == 'migration-error':
+ raise RuntimeError('cannot write config')
+ return {'env_added': [], 'config_added': ['setting reset'] if case == 'warnings' else [],
+ 'warnings': ['personality reset'] if case == 'warnings' else []}
+
+ def prompt(text):
+ prompts.append(text)
+ if case == 'eof':
+ raise EOFError()
+ if case == 'unicode':
+ raise UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'invalid')
+ return 'n' if case == 'tty-decline' else 'y'
+
+ monkeypatch.setattr(config, 'check_config_version', version)
+ monkeypatch.setattr(config, 'migrate_config', migrate)
+ monkeypatch.setattr(update_cmd, '_migrate_sibling_profile_configs', lambda: [])
+ monkeypatch.setattr(sys.stdin, 'isatty', lambda: case != 'noninteractive')
+ monkeypatch.setattr(sys.stdout, 'isatty', lambda: case != 'noninteractive')
+ monkeypatch.setattr('builtins.input', prompt)
+ gateway_prompts = []
+ monkeypatch.setattr(update_cmd, '_gateway_prompt', lambda text, default: gateway_prompts.append((text, default)) or 'y')
+ update_cmd._check_and_apply_config_migration(assume_yes=case == 'yes', gateway_mode=case == 'gateway')
+ assert calls == expected
+ assert bool(prompts) is (case in {'tty-yes', 'tty-decline', 'eof', 'unicode'})
+ assert bool(gateway_prompts) is (case == 'gateway')
+ output = capsys.readouterr().out
+ if named:
+ assert 'NEW_TOKEN' in output and 'new.option' in output
+ assert 'new credential' in output and 'new option' in output
+ if case in {'yes', 'noninteractive', 'gateway'}:
+ assert 'API keys require manual entry' in output
+ elif not expected:
+ assert 'hermes config migrate' in output
+ elif case in {'current', 'ahead'}:
+ assert 'Configuration is up to date' in output
+ elif case == 'read-error':
+ assert 'Could not check config version' in output
+ elif case == 'migration-error':
+ assert 'Config format update failed: cannot write config' in output
+ else:
+ assert 'v2 → v3' in output and 'no new settings to configure' in output
+ if case == 'warnings':
+ assert 'setting reset' in output and 'personality reset' in output
+
+
[email protected]('named', [False, True])
+def test_update_copies_bundled_skill_bytes_to_default_active_and_sibling(tmp_path, monkeypatch, named):
+ from pathlib import Path
+ from hermes_cli import update_cmd_maint
+
+ home = tmp_path / '.hermes'
+ homes = [home, home / 'profiles/active', home / 'profiles/sibling'] if named else [home]
+ for profile in homes:
+ profile.mkdir(parents=True, exist_ok=True)
+ (profile / 'config.yaml').write_text('{}\n', encoding='utf-8')
+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)
+ monkeypatch.setenv('HERMES_HOME', str(homes[1] if named else home))
+ monkeypatch.setattr('plugins.memory.honcho.cli.sync_honcho_profiles_quiet', lambda: [])
+ update_cmd_maint._sync_profiles_after_update()
+ bundled = Path(__file__).resolve().parents[2] / 'skills'
+ witness = next(bundled.rglob('SKILL.md'))
+ for profile in homes:
+ assert (profile / 'skills' / witness.relative_to(bundled)).read_bytes() == witness.read_bytes()
diff --git a/tests/hermes_cli/test_update_config_migration_on_current_checkout.py b/tests/hermes_cli/test_update_config_migration_on_current_checkout.py
deleted file mode 100644
index ccdb29fdae8..00000000000
--- a/tests/hermes_cli/test_update_config_migration_on_current_checkout.py
+++ /dev/null
@@ -1,74 +0,0 @@
-"""Tests for config migration on the commit_count == 0 / retry path (#91360).
-
-When an update is interrupted (or dependency install fails) after code has already
-been pulled, the subsequent update run takes the 'commit_count == 0' path.
-It must run config version checking and migrations before completing so the
-install is not left in a non-bootable state with new code on old config version.
-"""
-
-from __future__ import annotations
-
-from hermes_cli import config as update_config
-from unittest.mock import MagicMock, patch
-
-from hermes_cli import update_cmd
-
-
-
-
-
-
-def test_check_and_apply_config_migration_interactive_prompt():
- """When new config options exist in an interactive session, it prompts the user."""
- with (
- patch.object(update_cmd, "_reload_config_modules"),
- patch.object(update_config, "check_config_version", return_value=(37, 38)),
- patch("hermes_cli.config.get_missing_env_vars", return_value=[{"name": "NEW_KEY", "description": "desc"}]),
- patch("hermes_cli.config.get_missing_config_fields", return_value=[]),
- patch("sys.stdin.isatty", return_value=True),
- patch("sys.stdout.isatty", return_value=True),
- patch("builtins.input", return_value="y"),
- patch.object(
- update_config, "migrate_config",
- return_value={"env_added": ["NEW_KEY"], "config_added": [], "warnings": []},
- ) as mock_migrate,
- ):
- update_cmd._check_and_apply_config_migration(assume_yes=False, gateway_mode=False)
-
- mock_migrate.assert_called_once_with(interactive=True, quiet=False)
-
-
-def test_check_and_apply_config_migration_assume_yes():
- """When assume_yes=True, it applies migrations non-interactively without prompting."""
- with (
- patch.object(update_cmd, "_reload_config_modules"),
- patch.object(update_config, "check_config_version", return_value=(37, 38)),
- patch("hermes_cli.config.get_missing_env_vars", return_value=[{"name": "NEW_KEY"}]),
- patch("hermes_cli.config.get_missing_config_fields", return_value=[]),
- patch.object(
- update_config, "migrate_config",
- return_value={"env_added": [], "config_added": ["opt"], "warnings": []},
- ) as mock_migrate,
- ):
- update_cmd._check_and_apply_config_migration(assume_yes=True, gateway_mode=False)
-
- mock_migrate.assert_called_once_with(interactive=False, quiet=False)
-
-
-def test_check_and_apply_config_migration_non_interactive():
- """In a non-interactive session (e.g. CI/scripts), it applies safe migrations automatically."""
- with (
- patch.object(update_cmd, "_reload_config_modules"),
- patch.object(update_config, "check_config_version", return_value=(37, 38)),
- patch("hermes_cli.config.get_missing_env_vars", return_value=[]),
- patch("hermes_cli.config.get_missing_config_fields", return_value=[{"key": "new_setting"}]),
- patch("sys.stdin.isatty", return_value=False),
- patch("sys.stdout.isatty", return_value=False),
- patch.object(
- update_config, "migrate_config",
- return_value={"env_added": [], "config_added": ["new_setting"], "warnings": []},
- ) as mock_migrate,
- ):
- update_cmd._check_and_apply_config_migration(assume_yes=False, gateway_mode=False)
-
- mock_migrate.assert_called_once_with(interactive=False, quiet=False)
diff --git a/tests/hermes_cli/test_update_desktop_stale_warning.py b/tests/hermes_cli/test_update_desktop_stale_warning.py
deleted file mode 100644
index 7bef12082ef..00000000000
--- a/tests/hermes_cli/test_update_desktop_stale_warning.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""Retired soft-build hooks stop old updaters instead of claiming completion.
-
-Live source builds now raise on failure before maintenance runs. Old updaters
-can still import these frozen names after swapping their checkout.
-"""
-
-from types import SimpleNamespace
-
-import pytest
-
-from hermes_cli import update_cmd
-from hermes_cli import update_cmd_maint
-
-
- "name,args,kwargs",
- [
- ("_print_update_summary", (), {
- "node_failures": [], "desktop_build_ok": True, "pre_update_version": None,
- }),
- ("_print_update_summary", (), {
- "node_failures": ["dashboard"], "desktop_build_ok": False,
- "pre_update_version": "0.20.1",
- }),
- ("_finish_dashboard_update_cleanup", ([],), {}),
- ("_finish_dashboard_update_cleanup", (["dashboard"],), {
- "already_restarted_units": {"hermes-serve"},
- }),
- ],
-)
-def test_historical_completion_hooks_stop_before_work(name, args, kwargs, monkeypatch, capsys):
- def forbidden(*args, **kwargs):
- pytest.fail("old updater attempted post-update work")
-
- monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", forbidden)
- monkeypatch.setattr(update_cmd, "_reload_process_scan_modules", forbidden)
- monkeypatch.setattr(
- update_cmd, "_m", lambda: SimpleNamespace(_kill_stale_dashboard_processes=forbidden),
- )
- with pytest.raises(SystemExit) as exc:
- getattr(update_cmd_maint, name)(*args, **kwargs)
- assert exc.value.code == 0
- output = capsys.readouterr()
- assert "run `hermes` again" in output.err
- assert "Update complete" not in output.out
-
-
-def test_gateway_exit_code_file_tracks_verified_outcome(tmp_path, monkeypatch):
- monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: tmp_path)
- update_cmd._write_gateway_update_exit_code(True)
- assert (tmp_path / ".update_exit_code").read_text(encoding="utf-8") == "0"
- update_cmd._write_gateway_update_exit_code(False)
- assert (tmp_path / ".update_exit_code").read_text(encoding="utf-8") == "1"
-
-
-def test_verified_completion_keeps_success_banner(capsys, monkeypatch):
- monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "")
- monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))
-
- assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is True
-
- out = capsys.readouterr().out
- assert "✓ Update complete!" in out
- assert "partially complete" not in out
- assert "desktop" not in out
- assert "Node" not in out
- assert "=== hermes-update completed" not in out
-
-
-def test_verified_completion_emits_dashboard_receipt_only_on_success(monkeypatch, capsys):
- action_id = "a" * 32
- monkeypatch.setenv("HERMES_ACTION_ID", action_id)
- monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "")
- monkeypatch.setattr(
- update_cmd, "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- )
- assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is False
- assert f"=== hermes-update completed {action_id} ===" not in capsys.readouterr().out
-
- monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))
- assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is True
- assert f"=== hermes-update completed {action_id} ===" in capsys.readouterr().out
-
-
-def test_unavailable_sqlite_probe_retains_existing_nonblocking_behavior(monkeypatch, capsys):
- monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "")
- monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (False, None))
-
- assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is True
- assert "✓ Update complete!" in capsys.readouterr().out
-
-
-def test_maintenance_returns_sqlite_verdict_without_frontend_flags(monkeypatch, tmp_path, capsys):
- monkeypatch.setattr(update_cmd, "_m", lambda: SimpleNamespace(PROJECT_ROOT=tmp_path))
- monkeypatch.setattr("hermes_cli.macos_tcc_anchor.ensure_tcc_anchor", lambda: None)
- monkeypatch.setattr("hermes_cli.model_catalog.seed_cache_from_checkout", lambda root: False)
- monkeypatch.setattr(update_cmd, "_check_and_apply_config_migration", lambda **kwargs: None)
- for name in (
- "_verify_and_restore_state_dbs_post_update", "_print_bundled_skills_sync_report",
- "_sync_profiles_after_update", "_print_post_update_notices_and_self_heals",
- ):
- monkeypatch.setattr(update_cmd_maint, name, lambda: None)
- monkeypatch.setattr(
- update_cmd, "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- )
-
- complete = update_cmd_maint._run_post_update_maintenance(
- assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None,
- had_desktop_app_before_update=False, pre_update_version=None,
- )
-
- assert complete is False
- assert "Update complete" not in capsys.readouterr().out
- monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))
- monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "")
- assert update_cmd_maint._run_post_update_maintenance(
- assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None,
- had_desktop_app_before_update=False, pre_update_version=None,
- ) is True
- assert "✓ Update complete!" in capsys.readouterr().out
-
-
[email protected]("already_restarted_units", [None, {"hermes-serve"}])
-def test_dashboard_refresh_preserves_restart_bookkeeping(
- already_restarted_units, monkeypatch, capsys,
-):
- order = []
- monkeypatch.setattr(update_cmd, "_reload_process_scan_modules", lambda: order.append("reload"))
-
- def kill(**kwargs):
- order.append(kwargs)
- return {"unrecovered": [1234]}
-
- monkeypatch.setattr(
- update_cmd, "_m", lambda: SimpleNamespace(_kill_stale_dashboard_processes=kill),
- )
- update_cmd_maint._refresh_dashboard_after_update(already_restarted_units=already_restarted_units)
-
- assert order == [{
- "restart_managed": True, "already_restarted_units": already_restarted_units,
- }]
- assert "could not be auto-restarted" in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_update_fleet_check_fail_closed.py b/tests/hermes_cli/test_update_fleet_check_fail_closed.py
index 296aa3b9834..42dd9aae965 100644
--- a/tests/hermes_cli/test_update_fleet_check_fail_closed.py
+++ b/tests/hermes_cli/test_update_fleet_check_fail_closed.py
@@ -35,103 +35,6 @@ def _plan(runtimes):
return types.SimpleNamespace(runtimes=runtimes)
-class TestEmptySnapshotFailClosed:
- """Signals under which zero fleet rows means verification failure."""
-
- def test_incomplete_when_pre_update_plan_saw_gateway_runtimes(self):
- # (a) The plan inventoried a live gateway runtime pre-update but the
- # restart phase's POSIX bookkeeping is empty (e.g. Windows, or an
- # externally-supervised gateway). Zero rows must fail closed.
- assert (
- _fleet_probe_expected_runtimes(
- _plan([RuntimeRecord(kind="gateway", profile="default")]),
- [], # pre_restart_pids: probe saw nothing
- None, # no Windows resume token
- [], # restarted_services
- set(), # killed_pids
- )
- is True
- )
-
- def test_plan_expectation_keys_on_gateway_kind_only(self):
- # #97332: serve/dashboard plan records have no gateway_state.json row, so a
- # dashboard-only or serve-only plan must not demand rows (that made a successful
- # update exit 1); one gateway record alongside them still carries the expectation.
- non_gateway = [RuntimeRecord(kind="dashboard", profile="default"), RuntimeRecord(kind="serve", profile="default")]
- assert _fleet_probe_expected_runtimes(_plan(non_gateway), [], None, [], set()) is False
- mixed = non_gateway + [RuntimeRecord(kind="gateway", profile="work")]
- assert _fleet_probe_expected_runtimes(_plan(mixed), [], None, [], set()) is True
-
- def test_windows_resume_token_alone_is_not_expected(self):
- # (c) The Windows pause/resume token is EXCLUDED from the expectation
- # (#93406 residual): it is pause/resume bookkeeping, not a runtime
- # inventory, and collect_fleet_versions() cannot return rows for its
- # entries (unmapped Scheduled-Task gateways never publish
- # gateway_state.json; a resumed profile gateway relaunches detached).
- # Counting it made a healthy Windows update wait out the probe window
- # and exit 1 on zero rows. Full coverage lives in
- # test_update_fleet_probe_resume_token.py.
- token = {"resume_needed": False, "profiles": {"default": 4321}}
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
- token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]}
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
-
- def test_windows_resume_token_services_do_not_demand_rows(self):
- # Deliberately inverted from the original pin (#93406/#95589): SCM
- # services the updater itself paused/resumed produce NO probe rows —
- # counting them as "expected runtimes" made every healthy Windows
- # desktop update stall ~14min in fleet verification and exit 1.
- # The token is excluded wholesale; restart-phase and pre-restart
- # signals below still fail closed.
- token = {
- "resume_needed": False,
- "profiles": {},
- "unmapped": [],
- "services": ["HermesGateway"],
- }
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
-
- def test_incomplete_when_restart_phase_touched_gateways(self):
- # The original #93410 signal still counts.
- assert (
- _fleet_probe_expected_runtimes(None, [], None, ["hermes-gateway"], set())
- is True
- )
- assert _fleet_probe_expected_runtimes(None, [], None, [], {4321}) is True
-
- def test_incomplete_when_pre_restart_pids_seen(self):
- assert _fleet_probe_expected_runtimes(None, [4321], None, [], set()) is True
-
- def test_incomplete_when_pre_restart_state_unreadable(self):
- # None means the pre-state could not be read — cannot prove nothing
- # was running, same contract as _restart_phase_failure_is_incomplete.
- assert _fleet_probe_expected_runtimes(None, None, None, [], set()) is True
-
-
-class TestEmptySnapshotGenuinelyIdle:
- def test_success_when_nothing_was_running_pre_update(self):
- # (b) Positive control: no plan runtimes, empty PID snapshot, no
- # Windows token, no restart bookkeeping — zero rows stays a success.
- assert (
- _fleet_probe_expected_runtimes(_plan([]), [], None, [], set()) is False
- )
-
- def test_success_with_no_plan_at_all(self):
- assert _fleet_probe_expected_runtimes(None, [], None, [], set()) is False
-
- def test_success_with_empty_windows_token(self):
- # A token that paused nothing (e.g. Windows host with no gateways)
- # is not a liveness signal.
- token = {"resume_needed": False, "profiles": {}, "unmapped": []}
- assert _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
-
-
class TestCallSiteWiring:
@pytest.mark.parametrize("had_gateway", [False, True], ids=["idle", "plan-saw-gateway"])
def test_empty_probe_settles_and_fails_only_when_rows_expected(self, monkeypatch, tmp_path, capsys, had_gateway):
diff --git a/tests/hermes_cli/test_update_fleet_probe_resume_token.py b/tests/hermes_cli/test_update_fleet_probe_resume_token.py
index d30835ded09..a9946bfec03 100644
--- a/tests/hermes_cli/test_update_fleet_probe_resume_token.py
+++ b/tests/hermes_cli/test_update_fleet_probe_resume_token.py
@@ -1,101 +1,27 @@
-"""Regression for #93406 (residual) — the Windows pause/resume token is NOT a
-fleet runtime and must not be counted by ``_fleet_probe_expected_runtimes``.
+"""Only row-capable runtime evidence can make an empty fleet probe fail."""
+from types import SimpleNamespace
-The first #93406 guard counted the ``_windows_gateway_resume`` token
-(``profiles`` / ``unmapped`` entries) as an "expected fleet rows" signal. But
-the token is pause/resume *bookkeeping*, not a runtime inventory:
-
-* ``unmapped`` entries (Scheduled-Task gateways) never publish
- ``gateway_state.json`` rows at all, and
-* a paused-then-resumed profile gateway relaunches DETACHED and may not
- republish its identity within the probe's window,
-
-so ``collect_fleet_versions()`` can legitimately return zero rows for a
-perfectly healthy Windows update. With the token counted as an expected
-runtime, ``_fleet_rows_expected`` is True, the verification loop silently
-waits out its polling window (~14 min wall clock on an end-user report with
-the retry loop), prints "Fleet version check returned no rows", and ``hermes
-update`` exits 1 — for an update that succeeded.
-
-The invariant this file pins: ``_fleet_probe_expected_runtimes`` may only
-return True for signals that correspond to rows ``collect_fleet_versions()``
-is actually capable of returning (restart-phase bookkeeping, the pre-restart
-PID snapshot, the pre-update plan inventory). A genuinely live pre-update
-Windows gateway is already covered by ``pre_restart_pids`` and the plan
-inventory — the token adds no row-capable information on top.
-
-Counterfactual: every test in ``TestResumeTokenIsNotARuntime`` FAILS on the
-pre-fix ``_fleet_probe_expected_runtimes`` (which returns True for a
-token-only signal).
-"""
-
-from __future__ import annotations
-
-import types
+import pytest
from hermes_cli.main import _fleet_probe_expected_runtimes
from hermes_cli.update_inventory import RuntimeRecord
-def _plan(runtimes):
- return types.SimpleNamespace(runtimes=runtimes)
-
-
-class TestResumeTokenIsNotARuntime:
- """Token-only signals must NOT mark fleet rows as expected (#93406)."""
-
- def test_token_profiles_alone_do_not_expect_rows(self):
- # A paused/resumed profile gateway relaunches detached; its row is
- # not guaranteed within the probe window. Token-only == no rows
- # expected, so zero rows stays exit 0 instead of a false failure.
- token = {"resume_needed": False, "profiles": {"default": 4321}}
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
-
- def test_token_unmapped_alone_does_not_expect_rows(self):
- # Scheduled-Task gateways (token["unmapped"]) never publish
- # gateway_state.json rows — collect_fleet_versions() CANNOT return a
- # row for them, so they must not be counted as expected rows.
- token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]}
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
-
- def test_token_with_empty_pid_snapshot_is_still_not_expected(self):
- # Even alongside an affirmatively-empty PID snapshot and an empty
- # plan, the token alone must not flip the expectation.
- token = {"resume_needed": True, "profiles": {"work": 777}, "unmapped": []}
- assert (
- _fleet_probe_expected_runtimes(_plan([]), [], token, [], set())
- is False
- )
-
-
-class TestRowCapableSignalsStillCount:
- """The row-capable liveness signals are unaffected by the exclusion."""
-
- def test_pre_restart_pids_still_expect_rows_alongside_token(self):
- # A live pre-update gateway is covered by the PID snapshot — the
- # row-capable signal — regardless of the token riding along.
- token = {"resume_needed": False, "profiles": {"default": 4321}}
- assert (
- _fleet_probe_expected_runtimes(None, [4321], token, [], set())
- is True
- )
-
- def test_plan_inventory_still_expects_rows_alongside_token(self):
- token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]}
- assert (
- _fleet_probe_expected_runtimes(
- _plan([RuntimeRecord(kind="gateway", profile="default")]),
- [],
- token,
- [],
- set(),
- )
- is True
- )
-
- def test_unreadable_pre_state_still_expects_rows(self):
- assert _fleet_probe_expected_runtimes(None, None, None, [], set()) is True
[email protected]('plan,pids,token,services,killed,expected', [
+ (None, [], {'profiles': {'default': 4321}}, [], set(), False),
+ (None, [], {'unmapped': [{'pid': 99}]}, [], set(), False),
+ ([], [], {'profiles': {'work': 777}}, [], set(), False),
+ (None, [], {'services': ['HermesGateway']}, [], set(), False),
+ (None, [], {}, [], set(), False), (None, [], None, [], set(), False),
+ ([], [], None, [], set(), False), (None, None, None, [], set(), True),
+ (None, [4321], {'profiles': {'default': 4321}}, [], set(), True),
+ (['gateway'], [], {'unmapped': [{'pid': 99}]}, [], set(), True),
+ (['serve', 'dashboard'], [], None, [], set(), False),
+ (['serve', 'gateway'], [], None, [], set(), True),
+ (None, [], None, ['hermes-gateway'], set(), True),
+ (None, [], None, [], {4321}, True),
+])
+def test_expected_rows(plan, pids, token, services, killed, expected):
+ inventory = None if plan is None else SimpleNamespace(
+ runtimes=[RuntimeRecord(kind=kind, profile='default') for kind in plan])
+ assert _fleet_probe_expected_runtimes(inventory, pids, token, services, killed) is expected
diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.py
index 7359ea4fe64..ae8c13cb7df 100644
--- a/tests/hermes_cli/test_update_fleet_restart_pending.py
+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py
@@ -60,28 +60,11 @@ def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
return side_effect
-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)
-
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return SimpleNamespace(returncode=0, stdout="main\n", stderr="")
-
- if "rev-list" in joined:
- return SimpleNamespace(returncode=0, stdout="0\n", stderr="")
-
- if joined.endswith("rev-parse HEAD"):
- return SimpleNamespace(returncode=0, stdout=f"{sha}\n", stderr="")
-
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- return side_effect
def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
- """Patch ``_cmd_update_impl`` helpers. Mirrors test_update_head_moved_gate."""
+ """Isolate machine maintenance while exercising interrupted fleet updates."""
monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect)
monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)
monkeypatch.setattr(update_cmd, "_prepare_updated_checkout", lambda *a, **k: None)
@@ -376,8 +359,6 @@ def test_stale_fleet_matrix_on_latest_receipt_is_pending(monkeypatch):
assert update_cmd._pending_fleet_restart_needed() is True
-
-
# ---------------------------------------------------------------------------
# cmd_update integration (mocked git / restart)
# ---------------------------------------------------------------------------
@@ -406,33 +387,6 @@ def test_marker_written_after_pull_cleared_after_successful_restart(
assert "✓ Code updated!" in out
-def test_clean_update_warns_about_surviving_pre_update_serve_runtime(
- monkeypatch, tmp_path, capsys
-):
- """The successful update path must surface an inventoried stale serve."""
- args = _update_args()
- _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())
- monkeypatch.setattr(
- update_cmd,
- "_surviving_pre_update_serve_runtimes",
- lambda _plan: [
- {
- "pid": 5555,
- "kind": "serve",
- "profile": "default",
- "supervisor": "manual-serve",
- }
- ],
- )
-
- hermes_main.cmd_update(args)
-
- out = capsys.readouterr().out
- assert "pid 5555" in out
- assert "serve" in out
- assert "pre-update code" in out
-
-
def test_clean_update_escalates_surviving_serve_as_unaccounted(
monkeypatch, tmp_path, capsys
):
@@ -516,79 +470,6 @@ def test_interrupt_between_pull_and_restart_leaves_marker(
assert "expected_sha=def456" in marker.read_text(encoding="utf-8")
-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())
- update_cmd._write_fleet_restart_pending_marker(expected_sha="def456")
-
- seen = {"ran": False}
-
- original = update_cmd._restart_gateway_fleet_after_update
- def _restart(*args):
- seen["ran"] = True
- return original(*args)
-
- monkeypatch.setattr(update_cmd, "_restart_gateway_fleet_after_update", _restart)
-
- hermes_main.cmd_update(args)
-
- assert seen["ran"] is True
- assert not update_cmd._fleet_restart_pending_marker_path().exists()
- out = capsys.readouterr().out
- assert "Already up to date!" 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}
- original = update_cmd._restart_gateway_fleet_after_update
- def restart(*args):
- seen["ran"] = True
- return original(*args)
- monkeypatch.setattr(update_cmd, "_restart_gateway_fleet_after_update", restart)
-
- hermes_main.cmd_update(args)
-
- assert seen["ran"] is True
- out = capsys.readouterr().out
- assert "Already up to date!" in 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 --git a/tests/hermes_cli/test_update_handoff_exit.py b/tests/hermes_cli/test_update_handoff_exit.py
deleted file mode 100644
index 255745a52ec..00000000000
--- a/tests/hermes_cli/test_update_handoff_exit.py
+++ /dev/null
@@ -1,120 +0,0 @@
-"""Historical handoff markers cannot bypass normal update cleanup or exits."""
-
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import pytest
-
-import hermes_cli.main as main_mod
-from hermes_cli import update_cmd
-from hermes_cli.main import cmd_update
-from hermes_cli.update_receipt import COMMAND_BOUNDARY_STOP_REASON
-
-
-class _FakeLock:
- def __init__(self, events):
- self._events = events
-
- def acquire(self):
- self._events.append("acquire")
- return True
-
- def release(self):
- self._events.append("release")
-
-
-# Events from the most recent _run_cmd_update call, also filled in when
-# cmd_update propagates an exception (the return value is unreachable then).
-_LAST = {}
-
-
-def _run_cmd_update(monkeypatch, impl, *, reexec: bool):
- """Run cmd_update with everything external mocked; return the events."""
- events = {"order": [], "exit_codes": [], "receipts": []}
-
- def fake_impl(args, gateway_mode=False):
- events["order"].append("impl")
- impl(args, gateway_mode=gateway_mode)
-
- def fake_finalize_io(state):
- events["order"].append("restore-stdio")
-
- def fake_receipt(code, reason):
- events["receipts"].append((code, reason))
-
- def fake_exit(code):
- events["order"].append("hard-exit")
- events["exit_codes"].append(code)
-
- monkeypatch.setattr("hermes_cli.config.is_managed", lambda: False)
- monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda root: "git")
- monkeypatch.setattr("hermes_cli.update_lock.UpdateLock", lambda: _FakeLock(events["order"]))
- monkeypatch.setattr(update_cmd, "_cmd_update_impl", fake_impl)
- monkeypatch.setattr(main_mod, "_install_hangup_protection", lambda gateway_mode=False: None)
- monkeypatch.setattr(main_mod, "_finalize_update_output", fake_finalize_io)
- monkeypatch.setattr("hermes_cli.update_receipt.finalize_pending_update_receipt", fake_receipt)
- monkeypatch.setattr("os._exit", fake_exit)
- if reexec:
- monkeypatch.setenv("HERMES_UPDATE_REEXEC", "1")
- else:
- monkeypatch.delenv("HERMES_UPDATE_REEXEC", raising=False)
-
- args = SimpleNamespace(plan=False, check=False, gateway=False, branch=None)
- try:
- cmd_update(args)
- finally:
- _LAST.clear()
- _LAST.update(events)
- return events
-
-
-def _noop_impl(args, gateway_mode=False):
- return None
-
-
-def test_historical_handoff_marker_does_not_bypass_normal_shutdown(monkeypatch):
- events = _run_cmd_update(monkeypatch, _noop_impl, reexec=True)
- assert events["exit_codes"] == []
- assert events["receipts"] == [(0, COMMAND_BOUNDARY_STOP_REASON)]
- # Cleanup remains ordered even if an old parent supplied its handoff marker.
- assert events["order"] == ["acquire", "impl", "release", "restore-stdio"]
-
-
-def test_non_handoff_run_never_hard_exits(monkeypatch):
- events = _run_cmd_update(monkeypatch, _noop_impl, reexec=False)
- assert events["exit_codes"] == []
- assert "hard-exit" not in events["order"]
- assert events["receipts"] == [(0, COMMAND_BOUNDARY_STOP_REASON)]
-
-
-def test_handoff_child_propagates_early_systemexit_code(monkeypatch):
- def early_refusal(args, gateway_mode=False):
- raise SystemExit(3)
-
- with pytest.raises(SystemExit) as excinfo:
- _run_cmd_update(monkeypatch, early_refusal, reexec=True)
- assert excinfo.value.code == 3
- # The original exception propagates after normal cleanup.
- assert _LAST["exit_codes"] == []
-
-
-def test_handoff_child_systemexit_none_means_zero(monkeypatch):
- def bare_exit(args, gateway_mode=False):
- raise SystemExit(None)
-
- with pytest.raises(SystemExit):
- _run_cmd_update(monkeypatch, bare_exit, reexec=True)
- assert _LAST["exit_codes"] == []
-
-
-def test_unhandled_exception_keeps_raise_path_no_hard_exit(monkeypatch):
- def boom(args, gateway_mode=False):
- raise RuntimeError("update tail exploded")
-
- # With os._exit patched to record, the re-raised RuntimeError reaches
- # pytest with the finally block already run — and no hard exit fires.
- with pytest.raises(RuntimeError, match="update tail exploded"):
- _run_cmd_update(monkeypatch, boom, reexec=True)
- assert "hard-exit" not in _LAST["order"]
- assert _LAST["receipts"] == [(1, "RuntimeError: update tail exploded")]
diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.py
deleted file mode 100644
index d6d9091a721..00000000000
--- a/tests/hermes_cli/test_update_head_moved_gate.py
+++ /dev/null
@@ -1,148 +0,0 @@
-"""Tests for the post-pull HEAD-movement gate in ``hermes update``.
-
-Issue #79678: a detached/pinned checkout can report "N new commit(s)"
-against origin, run the ff-only merge successfully, and still sit on the
-old commit afterward (the branch-switch step re-detaches to the raw SHA).
-Before this guard ``hermes update`` printed "✓ Code updated!" and
-reinstalled deps + rebuilt the desktop app against the stale tree — no
-error, no warning. The gate compares the pre-pull and post-pull HEAD SHA
-and fails loudly when the update was a no-op.
-"""
-
-from types import SimpleNamespace
-
-from copy import deepcopy
-
-import pytest
-
-from hermes_cli import main as hermes_main
-from hermes_cli import update_cmd
-from hermes_cli.update_inventory import UpdatePlan
-
-
[email protected](autouse=True)
-def _isolate_venv_holders(monkeypatch):
- """The update flow's venv-holder guard sees the live gateway processes on
- a dev machine and aborts with SystemExit 2 before reaching the HEAD-move
- gate under test. Isolate it so the test exercises the intended path."""
- monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: [])
-
-
-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 side_effect(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
-
- # git rev-parse --abbrev-ref HEAD (get current branch)
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return SimpleNamespace(returncode=0, stdout="main\n", stderr="")
-
- # git rev-list HEAD..origin/main --count (behind count)
- if "rev-list" in joined:
- return SimpleNamespace(returncode=0, stdout="3\n", stderr="")
-
- # git rev-parse HEAD — pre-pull capture (first call) sees pre_sha;
- # post-pull capture (second call) sees post_sha. get_version_info
- # is mocked in _patch_update_deps so the startup banner makes no
- # rev-parse calls of its own.
- if joined.endswith("rev-parse HEAD"):
- if calls["n"] < 1:
- calls["n"] += 1
- return SimpleNamespace(returncode=0, stdout=f"{pre_sha}\n", stderr="")
- return SimpleNamespace(returncode=0, stdout=f"{post_sha}\n", stderr="")
-
- # Everything else (merge, checkout, etc.) succeeds quietly.
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- return side_effect
-
-
-def _make_head_pinned_side_effect(sha="abc123"):
- """Simulate a detached checkout pinned to ``sha``: HEAD never moves."""
-
- def side_effect(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
-
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return SimpleNamespace(returncode=0, stdout="HEAD\n", stderr="")
-
- if "rev-list" in joined:
- return SimpleNamespace(returncode=0, stdout="3\n", stderr="")
-
- if joined.endswith("rev-parse HEAD"):
- return SimpleNamespace(returncode=0, stdout=f"{sha}\n", stderr="")
-
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- return side_effect
-
-
-def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
- """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)
- (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_cli.version_info.get_version_info", lambda *a, **k: SimpleNamespace(),
- )
- 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 = []
-
- 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)
- 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 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)
- 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
- assert "checkout main" in out
diff --git a/tests/hermes_cli/test_update_products.py b/tests/hermes_cli/test_update_products.py
index a9981e5c3c6..3c0d14d4211 100644
--- a/tests/hermes_cli/test_update_products.py
+++ b/tests/hermes_cli/test_update_products.py
@@ -1,8 +1,6 @@
"""Update retries use the same dependency transaction as a newly pulled tree."""
-import json
import subprocess
-import venv
from types import SimpleNamespace
import pytest
@@ -15,34 +13,45 @@ from hermes_cli import main, update_cmd
[email protected]("failure", [
- pm.InstallError("venv", "conflict"),
- subprocess.CalledProcessError(23, ["python", "-m", "hermes_cli.source_build"]),
[email protected]("failure,exception,code", [
+ (None, None, 0), (SystemExit(3), SystemExit, 3),
+ (SystemExit(None), SystemExit, 1), (RuntimeError("tail exploded"), RuntimeError, 1),
+ (pm.InstallError("venv", "conflict"), SystemExit, 1),
+ (subprocess.CalledProcessError(23, ["python", "-m", "hermes_cli.source_build"]), SystemExit, 1),
])
-def test_command_reports_failed_preparation_and_releases_lock(tmp_path, monkeypatch, capsys, failure):
[email protected]("reexec", [False, True])
+def test_command_reports_outcome_and_releases_real_lock(tmp_path, monkeypatch, failure, exception, code, reexec):
from hermes_cli import update_lock, update_receipt
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_UPDATE_REEXEC", "1" if reexec else "")
+ monkeypatch.setattr("os._exit", lambda *_: pytest.fail("normal cleanup bypassed"))
monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False)
monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None)
finalized = []
monkeypatch.setattr(main, "_finalize_update_output", finalized.append)
def fail(args, gateway_mode):
+ assert update_lock.update_marker_path().is_file()
update_receipt.begin_update_receipt()
- raise failure
+ if failure is not None:
+ raise failure
monkeypatch.setattr(update_cmd, "_cmd_update_impl", fail)
- with pytest.raises(SystemExit) as error:
+ if exception is None:
main.cmd_update(SimpleNamespace(gateway=True))
- assert error.value.code == 1
+ else:
+ with pytest.raises(exception) as error:
+ main.cmd_update(SimpleNamespace(gateway=True))
+ if exception is SystemExit:
+ assert error.value.code == (failure.code if isinstance(failure, SystemExit) else code)
receipt = update_receipt.read_latest_receipt()
assert receipt is not None
- assert receipt["exit_code"] == 1
- assert receipt["outcome"] == "failed"
- assert (tmp_path / ".update_exit_code").read_text().strip() == "1"
+ assert receipt["exit_code"] == code
+ assert receipt["outcome"] == ("failed" if code else "success")
+ if code:
+ assert (tmp_path / ".update_exit_code").read_text().strip() == "1"
assert finalized == [None]
lock = update_lock.UpdateLock()
assert lock.acquire()
lock.release()
- assert "Update failed" in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_update_secret_import_lock.py b/tests/hermes_cli/test_update_secret_import_lock.py
index 3dd95042d52..e175af92357 100644
--- a/tests/hermes_cli/test_update_secret_import_lock.py
+++ b/tests/hermes_cli/test_update_secret_import_lock.py
@@ -38,7 +38,8 @@ secrets:
)
dispatch = (
- "hermes_main.cmd_update = lambda _args: 0\n"
+ "from hermes_cli import update_cmd\n"
+ "update_cmd._cmd_update_check = lambda **kwargs: 0\n"
"hermes_main.main()\n"
if run_main
else ""
diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.py
deleted file mode 100644
index 6ce876dcd5a..00000000000
--- a/tests/hermes_cli/test_update_self_lock.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""CLI metadata dispatch keeps credential implementations lazy."""
-import subprocess
-import sys
-import textwrap
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[2]
-
-class TestUpdateEntrypointImportHygiene:
- """Subprocess-verified: the CLI/update path never eagerly loads crypto.
-
- Empirical sys.modules assertions in a clean interpreter — the technique
- that pinned #86735's root cause. If any future module-level import of
- cryptography (or another self-locking native module) creeps back into
- the startup path, these fail before a Windows user ever hits the loop.
- """
-
- def _run(self, code: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-c", code],
- capture_output=True,
- text=True,
- cwd=str(ROOT),
- timeout=120,
- )
-
- def test_import_main_does_not_load_self_locking_modules(self):
- result = self._run(
- textwrap.dedent(
- """
- import sys
- import hermes_cli.main
- assert "cryptography.hazmat.bindings._rust" not in sys.modules
- print("OK")
- """
- )
- )
- assert result.returncode == 0, result.stdout + result.stderr
- assert "OK" in result.stdout
-
- def test_update_dispatch_does_not_load_cryptography(self):
- result = self._run(
- textwrap.dedent(
- """
- import sys
- from unittest.mock import patch
- sys.argv = ["hermes", "update", "--check"]
- import hermes_cli.main as m
- with patch("hermes_cli.update_cmd._cmd_update_check", lambda *a, **k: 0):
- try:
- m.main()
- except SystemExit:
- pass
- assert "cryptography.hazmat.bindings._rust" not in sys.modules, (
- "update dispatch eagerly loaded cryptography._rust"
- )
- print("OK")
- """
- )
- )
- assert result.returncode == 0, result.stdout + result.stderr
- assert "OK" in result.stdout
diff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.py
index ef2308c60be..3ab6c6992e2 100644
--- a/tests/hermes_cli/test_update_shim_self_lock.py
+++ b/tests/hermes_cli/test_update_shim_self_lock.py
@@ -6,20 +6,6 @@ import pytest
from hermes_cli import main as cli_main, main_install_repair
-def test_historical_dependency_handoff_stops_for_relaunch(monkeypatch, capsys):
- import subprocess
-
- def forbidden(*args, **kwargs):
- pytest.fail("historical sync must not spawn another updater")
-
- monkeypatch.setattr(subprocess, "Popen", forbidden)
- monkeypatch.setenv("HERMES_UPDATE_REEXEC", "1")
- with pytest.raises(SystemExit) as stopped:
- cli_main._reexec_dependency_sync_off_windows_shim()
- assert stopped.value.code == 0
- assert "run `hermes` again" in capsys.readouterr().err
-
-
def test_pending_rename_filter_drops_only_our_shim_pairs():
shims = [Path(r"C:\hermes\venv\Scripts\hermes.exe")]
entries = [
@@ -49,4 +35,4 @@ def test_legacy_shim_recovery_finds_both_layouts(tmp_path, monkeypatch, venv_nam
scripts = tmp_path / venv_name / "Scripts"
scripts.mkdir(parents=True)
monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path)
- assert main_install_repair._venv_scripts_dir() == scripts
\ No newline at end of file
+ assert main_install_repair._venv_scripts_dir() == scripts
diff --git a/tests/hermes_cli/test_update_sqlite_remediation.py b/tests/hermes_cli/test_update_sqlite_remediation.py
index 3843dbe0b92..d0f662e61b2 100644
--- a/tests/hermes_cli/test_update_sqlite_remediation.py
+++ b/tests/hermes_cli/test_update_sqlite_remediation.py
@@ -1,93 +1,43 @@
-"""Post-update reporting for unresolved SQLite WAL-reset risk."""
-
+"""Selected-runtime admission and dashboard completion bookkeeping."""
from pathlib import Path
from types import SimpleNamespace
-
-from hermes_cli import update_cmd
-import hermes_cli.update_cmd_maint as update_cmd_maint
-
-
-def test_runtime_status_probes_running_venv_outside_checkout(tmp_path, monkeypatch):
- running_python = tmp_path / "venv312" / "bin" / "python"
- observed = []
- vulnerable = SimpleNamespace(wal_reset_vulnerable=True)
- monkeypatch.setattr("hermes_constants.project_venv_dir", lambda _root: None)
- monkeypatch.setattr(update_cmd.sys, "executable", str(running_python))
- monkeypatch.setattr(
- "hermes_cli.sqlite_runtime.probe_sqlite_runtime",
- lambda python: observed.append(Path(python)) or vulnerable,
- )
-
- safe, info = update_cmd._post_update_sqlite_runtime_status()
-
- assert observed == [running_python]
- assert safe is False
- assert info is vulnerable
-
-
-def test_runtime_status_uses_selected_python_not_legacy_repo_venv(tmp_path, monkeypatch):
- selected = tmp_path / "selected/bin/python"
- monkeypatch.setattr("hermes_constants.project_venv_dir", lambda root: tmp_path / "obsolete-venv")
- monkeypatch.setattr(update_cmd.sys, "executable", str(selected))
- observed = []
- safe = SimpleNamespace(wal_reset_vulnerable=False)
- monkeypatch.setattr("hermes_cli.sqlite_runtime.probe_sqlite_runtime", lambda python: observed.append(Path(python)) or safe)
- assert update_cmd._post_update_sqlite_runtime_status() == (True, safe)
- assert observed == [selected]
-
-
-def test_summary_withholds_success_when_sqlite_remediation_failed(capsys, monkeypatch):
- monkeypatch.setattr(
- update_cmd,
- "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd_maint,
- "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd,
- "_update_complete_message",
- lambda _version: "✓ Update complete! (v0.20.5)",
- )
- monkeypatch.setattr(
- update_cmd_maint,
- "_update_complete_message",
- lambda _version: "✓ Update complete! (v0.20.5)",
- )
-
- complete = update_cmd_maint._print_verified_update_completion(
- update_cmd_maint._update_complete_message("0.20.4"),
- )
-
- out = capsys.readouterr().out
- assert complete is False
- assert "Update complete" not in out
- assert "SQLite 3.46.1" in out
- assert "WAL-reset" in out
- assert "uv-managed Python" in out
- assert "hermes doctor" in out
-
-
-def test_current_checkout_completion_is_verified_before_success(capsys, monkeypatch):
- monkeypatch.setattr(
- update_cmd,
- "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- )
- monkeypatch.setattr(
- update_cmd_maint,
- "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- )
-
- complete = update_cmd._print_verified_update_completion("✓ Already up to date!")
-
- out = capsys.readouterr().out
- assert complete is False
- assert "Already up to date" not in out
- assert "SQLite 3.46.1" in out
+import sys
+
+import pytest
+
+from hermes_cli import update_cmd, update_cmd_maint
+
+
[email protected]('verdict', ['safe', 'unsafe', 'unavailable'])
[email protected]('message', ['✓ Update complete!', '✓ Already up to date!'])
[email protected]('action_id', ['a' * 32, 'invalid'])
+def test_selected_sqlite_controls_completion_and_action_receipt(tmp_path, monkeypatch, capsys, verdict, message, action_id):
+ selected = tmp_path / 'selected/python'
+ info = None if verdict == 'unavailable' else SimpleNamespace(
+ wal_reset_vulnerable=verdict == 'unsafe', sqlite_version_string='3.46.1')
+ probes = []
+ monkeypatch.setattr(sys, 'executable', str(selected))
+ monkeypatch.setattr('hermes_constants.project_venv_dir', lambda _: tmp_path / 'obsolete-venv')
+ monkeypatch.setattr('hermes_cli.sqlite_runtime.probe_sqlite_runtime', lambda python: probes.append(python) or info)
+ monkeypatch.setattr(update_cmd, '_branch_head_suffix', lambda: '')
+ monkeypatch.setenv('HERMES_ACTION_ID', action_id)
+ assert update_cmd_maint._print_verified_update_completion(message) is (verdict != 'unsafe')
+ assert probes == [Path(selected)]
+ output = capsys.readouterr().out
+ assert (message in output) is (verdict != 'unsafe')
+ assert ('=== hermes-update completed' in output) is (verdict != 'unsafe' and action_id != 'invalid')
+ if verdict == 'unsafe':
+ for text in ('SQLite 3.46.1', 'WAL-reset', 'uv-managed Python', 'hermes doctor'):
+ assert text in output
+ elif action_id != 'invalid':
+ assert f'=== hermes-update completed {action_id} ===' in output
+
+
[email protected]('already_restarted_units', [None, {'hermes-serve'}])
+def test_dashboard_refresh_preserves_restart_bookkeeping(already_restarted_units, monkeypatch, capsys):
+ calls = []
+ monkeypatch.setattr(update_cmd, '_m', lambda: SimpleNamespace(
+ _kill_stale_dashboard_processes=lambda **kwargs: calls.append(kwargs) or {'unrecovered': [1234]}))
+ update_cmd_maint._refresh_dashboard_after_update(already_restarted_units=already_restarted_units)
+ assert calls == [{'restart_managed': True, 'already_restarted_units': already_restarted_units}]
+ assert 'could not be auto-restarted' in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.py
index d3ced430a39..1047f0bad8d 100644
--- a/tests/hermes_cli/test_update_target_identity.py
+++ b/tests/hermes_cli/test_update_target_identity.py
@@ -14,6 +14,7 @@ import pytest
from hermes_cli import main as cli_main, update_cmd, update_receipt
from hermes_cli.update_inventory import UpdatePlan
+from hermes_cli.update_cmd import _sync_with_upstream_if_needed
def git(root, *args):
@@ -86,6 +87,77 @@ def update_tree(tmp_path, monkeypatch):
args=args, resumed=resumed, requests=requests, plans=plans)
[email protected]('case', ['main', 'explicit', 'missing', 'no-move', 'wrong-branch',
+ 'fork-no-upstream', 'fork-upstream', 'check-main',
+ 'check-explicit', 'check-missing', 'check-upstream'])
+def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkeypatch, case, capsys):
+ t = update_tree
+ git(t.clone, 'checkout', '-q', 'main')
+ t.args.channel = 'main'
+ t.args.gateway = True
+ t.args.check = case.startswith('check-')
+ monkeypatch.setattr(cli_main, '_sync_with_upstream_if_needed', _sync_with_upstream_if_needed)
+ if case in {'explicit', 'check-explicit'}:
+ git(t.origin, 'branch', 'chosen', t.wanted)
+ t.args.branch = 'chosen'
+ if case in {'missing', 'check-missing'}:
+ t.args.branch = 'absent'
+ if case.startswith('fork-') or case == 'check-upstream':
+ # Origin is current; only upstream has the next commit.
+ git(t.origin, 'reset', '--hard', t.base)
+ if case in {'fork-upstream', 'check-upstream'}:
+ upstream = t.origin.parent / 'upstream'
+ git(t.origin.parent, 'clone', '-q', str(t.origin), str(upstream))
+ git(upstream, 'reset', '--hard', t.newer)
+ git(t.clone, 'remote', 'add', 'upstream', str(upstream))
+ run = subprocess.run
+
+ def fault(command, *args, **kwargs):
+ if 'merge' in command and '--ff-only' in command:
+ if case == 'no-move':
+ return subprocess.CompletedProcess(command, 0, stdout='', stderr='')
+ result = run(command, *args, **kwargs)
+ if case == 'wrong-branch':
+ run(['git', 'checkout', '-qb', 'wrong'], cwd=t.clone, check=True, capture_output=True)
+ return result
+ return run(command, *args, **kwargs)
+
+ monkeypatch.setattr(subprocess, 'run', fault)
+ if case == 'fork-upstream':
+ # The checkout policy must consult upstream even when origin is current.
+ plan = update_cmd._prepare_checkout_for_update(
+ ['git'], 'main', 'main', is_fork=True, assume_yes=True, gateway_mode=False,
+ gw_input_fn=None, switch_branch=False, _windows_gateway_resume=None)
+ assert plan.commit_count > 0 and plan.upstream_checked
+ assert git(t.clone, 'rev-parse', 'HEAD') == t.newer
+ return
+ fails = case in {'missing', 'check-missing', 'no-move', 'wrong-branch'}
+ if fails:
+ with pytest.raises(SystemExit) as error:
+ cli_main.cmd_update(t.args)
+ assert error.value.code == 1
+ assert t.requests == []
+ else:
+ cli_main.cmd_update(t.args)
+ if t.args.check:
+ assert t.requests == []
+ assert git(t.clone, 'rev-parse', 'HEAD') == t.base
+ output = capsys.readouterr().out
+ assert ('absent' if case == 'check-missing' else 'update') in output.lower()
+ if case == 'check-upstream':
+ assert git(t.clone, 'rev-parse', 'upstream/main') == t.newer
+ else:
+ request, = t.requests
+ assert request['assume_yes'] is True
+ assert request['gateway_mode'] is True
+ expected = t.base if case == 'fork-no-upstream' else t.wanted if case == 'explicit' else t.newer
+ assert git(t.clone, 'rev-parse', 'HEAD') == expected
+ assert request['source'] == str(t.clone)
+ if case == 'fork-no-upstream':
+ assert 'official repo not checked' in request['completion_message']
+ assert git(t.clone, 'remote') == 'origin'
+
+
@pytest.mark.parametrize('server', ['sha', 'tag-fallback', 'moved-sha', 'moved-fallback',
'at-release', 'ahead-release', 'explicit-branch'])
def test_stable_git_uses_remote_identity_without_moving_local_tags(update_tree, monkeypatch, server):
diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.py
deleted file mode 100644
index 4ba8774658a..00000000000
--- a/tests/hermes_cli/test_update_yes_flag.py
+++ /dev/null
@@ -1,259 +0,0 @@
-"""Tests for `hermes update --yes / -y` — assume yes for interactive prompts.
-
-Covers:
- 1. argparse parses the flag
- 2. Config-migration prompt is auto-answered (no input() call) and migrate_config
- runs with interactive=False so API-key prompts are skipped
- 3. Autostash restore prompt is auto-answered (prompt_for_restore == False, no
- input() call) and the stash is applied automatically
-"""
-
-import subprocess
-from types import SimpleNamespace
-from unittest.mock import patch
-
-import pytest
-
-from hermes_cli.main import cmd_update
-
-pytestmark = pytest.mark.usefixtures(
- "isolated_update_processes", "isolated_update_checkout",
-)
-
-
[email protected](autouse=True)
-def _isolate_venv_holders(monkeypatch):
- """The update flow's venv-holder guard sees the live gateway processes on
- a dev machine and aborts with SystemExit 2 before reaching the branch
- logic under test. Isolate it so the test exercises the intended path."""
- monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: [])
- monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)
-
-
[email protected](autouse=True)
-def _isolate_update(monkeypatch):
- from hermes_cli import update_cmd
-
- monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))
-
-
-def _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1", dirty=False
-):
- """Minimal subprocess.run side_effect for the update flow."""
-
- def side_effect(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
-
- if "rev-parse" in joined and "--abbrev-ref" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout=f"{branch}\n", stderr="")
- if "rev-parse" in joined and "--verify" in joined:
- return subprocess.CompletedProcess(
- cmd, 0 if verify_ok else 128, stdout="", stderr=""
- )
- if "rev-list" in joined:
- return subprocess.CompletedProcess(
- cmd, 0, stdout=f"{commit_count}\n", stderr=""
- )
- # `git status --porcelain` for dirty-tree detection during autostash.
- if "status" in joined and "--porcelain" in joined:
- out = " M hermes_cli/main.py\n" if dirty else ""
- return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr="")
- # `git stash list` — return a stash ref when dirty (so _stash_local_changes
- # gets something to return). _stash_local_changes_if_needed is what we
- # actually patch in tests that exercise restore, so this is a catch-all.
- if "stash" in joined and "list" in joined:
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
-
- return side_effect
-
-
-class TestUpdateYesConfigMigration:
- """--yes auto-answers the config-migration prompt and skips API-key prompts."""
-
- @patch("hermes_cli.update_cmd._reload_config_modules")
- @patch("hermes_cli.config.migrate_config")
- @patch("hermes_cli.config.check_config_version", return_value=(1, 2))
- @patch("hermes_cli.config.get_missing_config_fields", return_value=[])
- @patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"])
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_yes_auto_migrates_without_input(
- self,
- mock_run,
- _mock_which,
- _mock_missing_env,
- _mock_missing_cfg,
- _mock_version,
- mock_migrate,
- _mock_reload,
- capsys,
- ):
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
- mock_migrate.return_value = {"env_added": [], "config_added": []}
-
- args = SimpleNamespace(yes=True)
-
- with patch("builtins.input") as mock_input:
- cmd_update(args)
- # Never prompted the user.
- mock_input.assert_not_called()
-
- # migrate_config was invoked with interactive=False — API-key prompts
- # are suppressed, matching gateway-mode semantics.
- assert mock_migrate.call_count == 1
- _, kwargs = mock_migrate.call_args
- assert kwargs.get("interactive") is False
-
- out = capsys.readouterr().out
- assert "--yes: auto-applying config migration" in out
- # The "Would you like to configure them now?" prompt text never appears.
- assert "Would you like to configure them now?" not in out
-
- @patch("hermes_cli.update_cmd._reload_config_modules")
- @patch("hermes_cli.config.migrate_config")
- @patch("hermes_cli.config.check_config_version", return_value=(1, 2))
- @patch("hermes_cli.config.get_missing_config_fields", return_value=[])
- @patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"])
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_no_yes_flag_still_prompts_in_tty(
- self,
- mock_run,
- _mock_which,
- _mock_missing_env,
- _mock_missing_cfg,
- _mock_version,
- mock_migrate,
- _mock_reload,
- capsys,
- ):
- """Regression guard: without --yes, the TTY prompt path still fires."""
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
- mock_migrate.return_value = {"env_added": [], "config_added": []}
-
- args = SimpleNamespace(yes=False)
-
- # Patch ``sys.stdin.isatty`` and ``sys.stdout.isatty`` directly on the
- # real ``sys`` module instead of replacing ``hermes_cli.main.sys`` with
- # a MagicMock. The MagicMock approach was flaky under parallel test runs
- # — a sibling test that imported ``hermes_cli.main`` first could leave
- # a different ``sys`` reference resolved inside the function and the
- # mock would never be consulted, with CI then taking the
- # "Non-interactive session" branch instead of prompting.
- import sys as _sys
-
- with patch("builtins.input", return_value="n") as mock_input, patch.object(
- _sys.stdin, "isatty", return_value=True
- ), patch.object(_sys.stdout, "isatty", return_value=True):
- cmd_update(args)
- # The user was actually prompted.
- assert mock_input.called
- prompts = [c.args[0] if c.args else "" for c in mock_input.call_args_list]
- assert any("configure them now" in p for p in prompts)
-
-
-class TestUpdateYesStashRestore:
- """--yes auto-restores the pre-update autostash without prompting."""
-
-
-
-class TestUnicodeDecodeErrorInUpdatePrompts:
- """Regression tests (review of #68497): input() can raise
- UnicodeDecodeError when the terminal encoding can't decode the byte
- sequence (e.g. a non-UTF-8 locale, or an embedded terminal). Three
- interactive update prompts call input() directly -- the config-
- migration prompt, the stash-restore prompt, and the upstream-remote
- prompt -- and each must fail safe (skip, don't crash) rather than let
- the exception escape and crash `hermes update` mid-flight.
- """
-
- @patch("hermes_cli.update_cmd._reload_config_modules")
- @patch("hermes_cli.config.migrate_config")
- @patch("hermes_cli.config.check_config_version", return_value=(1, 2))
- @patch("hermes_cli.config.get_missing_config_fields", return_value=[])
- @patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"])
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_unicode_decode_error_in_tty_skips_and_prints_hint(
- self,
- mock_run,
- _mock_which,
- _mock_missing_env,
- _mock_missing_cfg,
- _mock_version,
- mock_migrate,
- _mock_reload,
- capsys,
- ):
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
- mock_migrate.return_value = {"env_added": [], "config_added": []}
- args = SimpleNamespace(yes=False)
-
- import sys as _sys
-
- with patch(
- "builtins.input",
- side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"),
- ), patch.object(_sys.stdin, "isatty", return_value=True), patch.object(
- _sys.stdout, "isatty", return_value=True
- ):
- cmd_update(args) # must not raise
-
- out = capsys.readouterr().out
- assert "hermes config migrate" in out
- mock_migrate.assert_not_called()
-
- def test_stash_restore_unicode_decode_error_falls_through_to_skip(self, tmp_path, capsys):
- from hermes_cli.update_cmd import _restore_stashed_changes
-
- with patch(
- "builtins.input",
- side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"),
- ):
- result = _restore_stashed_changes(
- ["git"], tmp_path, "stash@{0}", prompt_user=True, input_fn=None,
- ) # must not raise
-
- assert result is False
- out = capsys.readouterr().out
- assert "Skipped restoring local changes" in out
- assert "git stash apply stash@{0}" in out
-
- def test_stash_restore_eof_error_still_falls_through_to_skip(self, tmp_path):
- """Sanity: this fix must not regress the pre-existing EOFError case,
- which the raw input() path had no guard for at all before this fix."""
- from hermes_cli.update_cmd import _restore_stashed_changes
-
- with patch("builtins.input", side_effect=EOFError()):
- result = _restore_stashed_changes(
- ["git"], tmp_path, "stash@{0}", prompt_user=True, input_fn=None,
- ) # must not raise
-
- assert result is False
-
- def test_upstream_remote_prompt_unicode_decode_error_falls_through_to_skip(
- self, tmp_path
- ):
- from hermes_cli.update_cmd import _sync_with_upstream_if_needed
-
- with patch(
- "hermes_cli.update_cmd._has_upstream_remote", return_value=False
- ), patch(
- "hermes_cli.update_cmd._should_skip_upstream_prompt", return_value=False
- ), patch(
- "hermes_cli.update_cmd._add_upstream_remote"
- ) as mock_add, patch(
- "builtins.input",
- side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"),
- ):
- _sync_with_upstream_if_needed(["git"], tmp_path) # must not raise
-
- mock_add.assert_not_called()
diff --git a/tests/hermes_cli/test_update_zip_atomic_replace.py b/tests/hermes_cli/test_update_zip_atomic_replace.py
deleted file mode 100644
index 51eaa5ba644..00000000000
--- a/tests/hermes_cli/test_update_zip_atomic_replace.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""Regression: the ZIP-update directory replace must never leave a half-deleted tree.
-
-Issue #49145: on Windows the ZIP-update path did ``rmtree(dst); copytree(...)``.
-A copy that failed partway (file locks / flaky I/O — the very conditions the ZIP
-path exists to work around) left the directory deleted with nothing copied back,
-which broke ``hermes --tui`` because ``ui-tui/`` had vanished.
-
-``_atomic_replace_dir`` stages the new copy first and only swaps it in on full
-success, so a mid-copy failure leaves the original directory intact.
-"""
-
-from __future__ import annotations
-
-import shutil
-from pathlib import Path
-
-import pytest
-
-from hermes_cli.update_cmd import _atomic_replace_dir
-
-
-def test_atomic_replace_swaps_content_on_success(tmp_path: Path) -> None:
- src = tmp_path / "src" / "ui-tui"
- src.mkdir(parents=True)
- (src / "new.txt").write_text("NEW")
-
- dst = tmp_path / "install" / "ui-tui"
- dst.mkdir(parents=True)
- (dst / "old.txt").write_text("OLD")
-
- _atomic_replace_dir(str(src), str(dst))
-
- assert (dst / "new.txt").read_text() == "NEW"
- assert not (dst / "old.txt").exists()
- # No staging/backup siblings left behind.
- assert not (dst.parent / "ui-tui.hermes-update-staging").exists()
- assert not (dst.parent / "ui-tui.hermes-update-old").exists()
-
-
diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.py
index 60542b88389..72e025b4327 100644
--- a/tests/hermes_cli/test_update_zip_completion.py
+++ b/tests/hermes_cli/test_update_zip_completion.py
@@ -41,10 +41,18 @@ def zip_update(tmp_path, monkeypatch, isolated_source_completion):
root.mkdir()
(root / "pyproject.toml").write_text('[project]\nversion="1.0"\n', encoding="utf-8")
(root / "payload.txt").write_text("old", encoding="utf-8")
+ for name in ("tools/code.py", "apps/desktop/source.js", "apps/desktop/release/Hermes.exe",
+ "venv/keep", "node_modules/keep", ".env"):
+ path = root / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("retained", encoding="utf-8")
archive = tmp_path / "source.zip"
with zipfile.ZipFile(archive, "w") as out:
out.writestr("hermes-agent-main/pyproject.toml", '[project]\nversion="2.0"\n')
out.writestr("hermes-agent-main/payload.txt", "new")
+ for name in ("new-entry/data", "tools/code.py", "apps/desktop/source.js",
+ "venv/keep", "node_modules/keep", ".env"):
+ out.writestr("hermes-agent-main/" + name, "new")
# Only redirect transport: extraction, staging, dirty recheck and swap run.
monkeypatch.setattr("urllib.request.urlretrieve", lambda url, dst: urlretrieve(archive.as_uri(), dst))
monkeypatch.setattr(main, "PROJECT_ROOT", root)
@@ -133,6 +141,10 @@ def test_zip_command_migrates_profiles_recovers_snapshot_and_verifies_fleet(
assert (state.sibling / ".env").read_bytes() == (state.active / ".env").read_bytes()
assert json.loads(state.jobs.read_text()) == state.original_jobs
assert (state.root / "payload.txt").read_text() == "new"
+ for name in ("tools/code.py", "apps/desktop/source.js", "new-entry/data"):
+ assert (state.root / name).read_text(encoding="utf-8") == "new"
+ for name in ("apps/desktop/release/Hermes.exe", "venv/keep", "node_modules/keep", ".env"):
+ assert (state.root / name).read_text(encoding="utf-8") == "retained"
assert "v1.0 → v2.0" in capsys.readouterr().out
assert state.events == ["prepare", *([("marker", True)] if gateway_mode else []),
"restart", "resume", "finalize"]
@@ -174,7 +186,7 @@ def test_zip_helper_propagates_completion_status_after_real_verification(zip_upd
@pytest.mark.parametrize("route", ["direct", "git-failure"])
[email protected]("failure", ["swap", "preparation"])
[email protected]("failure", ["swap", "late-swap", "stage", "preparation"])
def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monkeypatch, route, failure):
import os
import pm
@@ -183,6 +195,8 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon
before = {profile: (profile / "config.yaml").read_bytes()
for profile in (state.active, state.sibling)}
old_project = (state.root / "pyproject.toml").read_bytes()
+ original_tree = {p.relative_to(state.root): p.read_bytes()
+ for p in state.root.rglob("*") if p.is_file()}
monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False))
monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None)
monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True)
@@ -191,17 +205,28 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon
raise subprocess.CalledProcessError(1, ["git", "fetch"])
monkeypatch.setattr(update_cmd, "_git_run", fail_fetch)
installed = []
- if failure == "swap":
+ if failure in {"swap", "late-swap"}:
rename = os.rename
def fail_second_swap(src, dst):
if str(src).endswith(".hermes-update-staging"):
installed.append(dst)
- if len(installed) == 2:
+ if len(installed) == (5 if failure == "late-swap" else 2):
raise OSError("locked replacement")
return rename(src, dst)
monkeypatch.setattr(os, "rename", fail_second_swap)
expected = SystemExit
+ elif failure == "stage":
+ import shutil
+
+ copytree = shutil.copytree
+
+ def fail_copy(src, dst, *args, **kwargs):
+ if str(dst).endswith(".hermes-update-staging"):
+ raise OSError("staging disk full")
+ return copytree(src, dst, *args, **kwargs)
+ monkeypatch.setattr(shutil, "copytree", fail_copy)
+ expected = SystemExit
else:
def fail_preparation(*args, **kwargs):
assert (state.root / "payload.txt").read_text() == "new"
@@ -210,11 +235,14 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon
expected = pm.InstallError
with pytest.raises(expected) as raised:
update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=True)
- if failure == "swap":
+ if failure in {"swap", "late-swap"}:
assert raised.value.code == 1
- assert len(installed) == 2
+ assert len(installed) == (5 if failure == "late-swap" else 2)
assert (state.root / "pyproject.toml").read_bytes() == old_project
assert (state.root / "payload.txt").read_text() == "old"
+ if failure != "preparation":
+ assert {p.relative_to(state.root): p.read_bytes()
+ for p in state.root.rglob("*") if p.is_file()} == original_tree
assert state.events == ["resume"]
assert state.token["resume_needed"] is False
assert {profile: (profile / "config.yaml").read_bytes() for profile in before} == before
@@ -222,3 +250,67 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon
assert json.loads(state.jobs.read_text()) == state.original_jobs
assert not (state.active / "logs/update_receipts/latest.json").exists()
assert not list(state.root.glob("*.hermes-update-*"))
+
+
[email protected]("entry", ["payload.txt", "tools"])
+def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, monkeypatch, entry):
+ import shutil
+
+ root = zip_update.root
+ target = root / entry
+ backup = root / (entry + ".hermes-update-old")
+ target.rename(backup)
+ leftover = root / (entry + ".hermes-update-staging")
+ leftover.write_text("interrupted copy", encoding="utf-8")
+ function = "copytree" if entry == "tools" else "copy2"
+ original = getattr(shutil, function)
+
+ def fail(src, dst, *args, **kwargs):
+ if str(dst) == str(leftover):
+ raise OSError("copy refused after crash")
+ return original(src, dst, *args, **kwargs)
+
+ with monkeypatch.context() as fault:
+ fault.setattr(shutil, function, fail)
+ with pytest.raises(SystemExit) as error:
+ update_cmd_zip._download_and_swap_zip("main", "local fixture")
+ assert error.value.code == 1
+ witness = target / "code.py" if entry == "tools" else target
+ assert witness.read_text(encoding="utf-8") == ("retained" if entry == "tools" else "old")
+ assert not list(root.glob("*.hermes-update-*"))
+ update_cmd_zip._download_and_swap_zip("main", "local fixture")
+ assert witness.read_text(encoding="utf-8") == "new"
+ assert not list(root.glob("*.hermes-update-*"))
+
+
+def test_atomic_directory_compat_entrypoint(tmp_path):
+ src, dst = tmp_path / "src", tmp_path / "dst"
+ src.mkdir()
+ dst.mkdir()
+ (src / "new").write_text("new", encoding="utf-8")
+ (dst / "old").write_text("old", encoding="utf-8")
+ update_cmd_zip._atomic_replace_dir(str(src), str(dst))
+ assert {p.name for p in dst.iterdir()} == {"new"}
+ assert (dst / "new").read_text(encoding="utf-8") == "new"
+ assert not list(tmp_path.glob("*.hermes-update-*"))
+
+
+def test_zip_refuses_non_main_before_transport(zip_update, monkeypatch, capsys):
+ monkeypatch.setattr('urllib.request.urlretrieve', lambda *_: pytest.fail('unsupported branch downloaded'))
+ before = (zip_update.root / 'payload.txt').read_bytes()
+ with pytest.raises(SystemExit) as error:
+ update_cmd_zip._update_via_zip(SimpleNamespace(branch='feature'), completion_request={})
+ assert error.value.code == 1
+ assert '--branch=feature is not supported' in capsys.readouterr().out
+ assert (zip_update.root / 'payload.txt').read_bytes() == before
+
+
[email protected]("windows,folder,executable", [(True, "Scripts", "python.exe"), (False, "bin", "python")])
+def test_venv_layout_explicit_and_native(tmp_path, windows, folder, executable):
+ import os
+ from hermes_constants import venv_bin_dir, venv_python_path
+
+ assert venv_bin_dir(tmp_path, windows=windows) == tmp_path / folder
+ assert venv_python_path(str(tmp_path), windows=windows) == tmp_path / folder / executable
+ if windows == (os.name == "nt"):
+ assert venv_python_path(tmp_path) == tmp_path / folder / executable
diff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.py
index e68cf66a6f1..5acb6c8fe69 100644
--- a/tests/hermes_cli/test_update_zip_fallback_guards.py
+++ b/tests/hermes_cli/test_update_zip_fallback_guards.py
@@ -338,18 +338,6 @@ def test_preserved_filter_does_not_split_non_rename_lines():
)
-def test_swap_preserve_set_is_the_module_constant():
- """The swap loop and the dirty-tree filter must share one source of
- truth for the preserved entries (no comment-synced duplicate)."""
- import inspect
-
- from hermes_cli import update_cmd_zip
-
- # The swap loop lives in the download/swap collaborator the ZIP path calls.
- src = inspect.getsource(update_cmd_zip._download_and_swap_zip)
- assert "_ZIP_PRESERVED_TOP_LEVEL" in src
-
-
def test_zip_overlay_allows_ignored_preserved_entries(tmp_path, monkeypatch):
"""venv/node_modules are gitignored on every normal install and the swap
preserves them — the ignored probe must not turn them into a false
diff --git a/tests/hermes_cli/test_update_zip_release_preserve.py b/tests/hermes_cli/test_update_zip_release_preserve.py
deleted file mode 100644
index 61478821a7b..00000000000
--- a/tests/hermes_cli/test_update_zip_release_preserve.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""#70337/#87331: the ZIP swap must preserve apps/desktop/release/.
-
-The GitHub source ZIP carries only source; the BUILT desktop app
-(release/win-unpacked/Hermes.exe) exists only in the live tree. Swapping
-`apps` without grafting the live release dir deletes the desktop build.
-"""
-
-from __future__ import annotations
-
-import os
-import shutil
-from pathlib import Path
-
-
-def test_staged_apps_swap_preserves_live_release_dir(tmp_path, monkeypatch):
- from hermes_cli import main as hermes_main
- from hermes_cli.update_cmd import (
- _commit_staged_replacements,
- _stage_replacement,
- )
-
- # live tree: apps/desktop/release/win-unpacked/Hermes.exe + old source
- root = tmp_path / "install"
- live_apps = root / "apps" / "desktop"
- (live_apps / "release" / "win-unpacked").mkdir(parents=True)
- (live_apps / "release" / "win-unpacked" / "Hermes.exe").write_bytes(b"MZbuilt")
- (live_apps / "electron").mkdir()
- (live_apps / "electron" / "main.ts").write_text("old source")
-
- # extracted ZIP: new source, NO release dir (GitHub source archive shape)
- extracted = tmp_path / "extracted"
- zip_apps = extracted / "apps" / "desktop"
- (zip_apps / "electron").mkdir(parents=True)
- (zip_apps / "electron" / "main.ts").write_text("new source")
-
- monkeypatch.setattr(hermes_main, "PROJECT_ROOT", root)
-
- # Reproduce the _update_via_zip staging loop for the `apps` entry,
- # including the release-dir graft.
- src = str(extracted / "apps")
- dst = str(root / "apps")
- staged_path = _stage_replacement(src, dst)
- live_release = os.path.join(dst, "desktop", "release")
- staged_release = os.path.join(staged_path, "desktop", "release")
- if os.path.isdir(live_release) and not os.path.exists(staged_release):
- os.makedirs(os.path.dirname(staged_release), exist_ok=True)
- shutil.copytree(live_release, staged_release)
-
- _commit_staged_replacements([(staged_path, dst)])
-
- # New source landed AND the built desktop app survived.
- assert (root / "apps" / "desktop" / "electron" / "main.ts").read_text() == (
- "new source"
- )
- exe = root / "apps" / "desktop" / "release" / "win-unpacked" / "Hermes.exe"
- assert exe.exists() and exe.read_bytes() == b"MZbuilt"
diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.py
deleted file mode 100644
index e2c40f2970a..00000000000
--- a/tests/hermes_cli/test_update_zip_two_phase.py
+++ /dev/null
@@ -1,411 +0,0 @@
-"""Tests for the two-phase ZIP replace and the shared venv-layout helpers.
-
-``_atomic_replace_dir`` (#49145) made each *individual* directory swap safe,
-but the ZIP update replaced ~70 top-level entries in a loop with no atomicity
-across iterations. An interruption partway left some entries at the new
-version and the rest at the old one -- every file valid Python, the
-combination unbootable. That is the mechanism behind the ``ImportError`` in
-#76091 and the field report in #63717.
-
-Reference: issues #76104 (ZIP atomicity) and #76105 (venv-helper duplication).
-"""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-
-import pytest
-
-from hermes_cli import update_cmd
-from hermes_constants import venv_bin_dir, venv_python_path
-from hermes_cli import main_install_repair
-
-
-# ---------------------------------------------------------------------------
-# Two-phase replace
-# ---------------------------------------------------------------------------
-
-def _live_tree(root: Path, names: dict[str, str]) -> None:
- for name, marker in names.items():
- d = root / name
- d.mkdir(parents=True, exist_ok=True)
- (d / "version.txt").write_text(marker)
-
-
-def _stage_all(root: Path, new: Path, names: list[str]) -> list[tuple[str, str]]:
- return [
- (
- update_cmd._stage_replacement(str(new / n), str(root / n)),
- str(root / n),
- )
- for n in names
- ]
-
-
-def test_staging_touches_nothing_live(tmp_path):
- """Phase 1 must not modify the install -- a failure there is a no-op."""
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"agent": "old", "tools": "old"})
- _live_tree(new, {"agent": "new", "tools": "new"})
-
- _stage_all(live, new, ["agent", "tools"])
-
- assert (live / "agent" / "version.txt").read_text() == "old"
- assert (live / "tools" / "version.txt").read_text() == "old"
-
-
-def test_commit_swaps_every_entry(tmp_path):
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"agent": "old", "tools": "old"})
- _live_tree(new, {"agent": "new", "tools": "new"})
-
- update_cmd._commit_staged_replacements(_stage_all(live, new, ["agent", "tools"]))
-
- assert (live / "agent" / "version.txt").read_text() == "new"
- assert (live / "tools" / "version.txt").read_text() == "new"
- # No staging/backup litter left behind.
- assert not [p for p in os.listdir(live) if "hermes-update" in p]
-
-
-def test_failed_swap_rolls_back_every_earlier_swap(tmp_path, monkeypatch):
- """The regression: a mid-loop failure must not leave a mixed-version tree.
-
- Before the two-phase split this produced `agent/` new + `tools/` stale --
- the exact shape that yields
- `ImportError: cannot import name 'TODO_INJECTION_HEADER'`.
- """
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"agent": "old", "tools": "old"})
- _live_tree(new, {"agent": "new", "tools": "new"})
- staged = _stage_all(live, new, ["agent", "tools"])
-
- real_rename = os.rename
- calls = {"n": 0}
-
- def flaky_rename(src, dst):
- calls["n"] += 1
- # Let the first entry swap fully (2 renames), then break the second.
- if calls["n"] == 4:
- raise OSError("simulated AV interference")
- return real_rename(src, dst)
-
- monkeypatch.setattr(update_cmd.os, "rename", flaky_rename)
-
- with pytest.raises(OSError):
- update_cmd._commit_staged_replacements(staged)
-
- monkeypatch.undo()
- # Both entries must be back at the OLD version -- not one new, one old.
- versions = {
- n: (live / n / "version.txt").read_text() for n in ("agent", "tools")
- }
- assert versions == {"agent": "old", "tools": "old"}, (
- f"mixed-version tree after rollback: {versions}"
- )
-
-
-def test_commit_handles_entries_absent_from_the_install(tmp_path):
- """A brand-new top-level dir has no live counterpart to move aside."""
- live, new = tmp_path / "live", tmp_path / "new"
- live.mkdir()
- _live_tree(new, {"brand_new": "new"})
-
- update_cmd._commit_staged_replacements(_stage_all(live, new, ["brand_new"]))
-
- assert (live / "brand_new" / "version.txt").read_text() == "new"
-
-
-def test_staging_clears_leftovers_from_an_interrupted_run(tmp_path):
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"agent": "old"})
- _live_tree(new, {"agent": "new"})
- stale = Path(f"{live / 'agent'}.hermes-update-staging")
- stale.mkdir()
- (stale / "junk.txt").write_text("from a previous crash")
-
- update_cmd._commit_staged_replacements(_stage_all(live, new, ["agent"]))
-
- assert (live / "agent" / "version.txt").read_text() == "new"
- assert not (live / "agent" / "junk.txt").exists()
-
-
-# ---------------------------------------------------------------------------
-# Shared venv helpers (#76105)
-# ---------------------------------------------------------------------------
-
-def test_venv_helpers_agree_with_each_other():
- v = Path("/opt/proj/venv")
- assert venv_python_path(v).parent == venv_bin_dir(v)
-
-
-def test_venv_helpers_accept_str_and_path():
- assert venv_python_path("/opt/x/venv") == venv_python_path(Path("/opt/x/venv"))
-
-
-def test_venv_helpers_are_platform_consistent():
- """Whatever the platform, the two halves must not disagree."""
- v = Path("/opt/proj/venv")
- bin_name = venv_bin_dir(v).name
- exe_name = venv_python_path(v).name
- assert (bin_name, exe_name) in {("Scripts", "python.exe"), ("bin", "python")}
-
-
-
-def test_top_level_files_are_swapped_atomically(tmp_path):
- """The repo root holds 20 first-party modules (run_agent.py, cli.py,
- hermes_constants.py, ...). Covering only directories would leave exactly
- the bug class this PR closes."""
- live, new = tmp_path / "live", tmp_path / "new"
- live.mkdir()
- new.mkdir()
- (live / "run_agent.py").write_text("old")
- (new / "run_agent.py").write_text("new")
-
- staged = [
- (
- update_cmd._stage_replacement(
- str(new / "run_agent.py"), str(live / "run_agent.py")
- ),
- str(live / "run_agent.py"),
- )
- ]
- update_cmd._commit_staged_replacements(staged)
-
- assert (live / "run_agent.py").read_text() == "new"
- assert not [p for p in os.listdir(live) if "hermes-update" in p]
-
-
-def test_file_swap_failure_restores_the_original_file(tmp_path, monkeypatch):
- """A mid-swap failure must not leave a stale-or-corrupt root module."""
- live, new = tmp_path / "live", tmp_path / "new"
- live.mkdir()
- new.mkdir()
- for name in ("cli.py", "run_agent.py"):
- (live / name).write_text("old")
- (new / name).write_text("new")
-
- staged = [
- (update_cmd._stage_replacement(str(new / n), str(live / n)), str(live / n))
- for n in ("cli.py", "run_agent.py")
- ]
-
- real_rename = os.rename
- calls = {"n": 0}
-
- def flaky_rename(src, dst):
- calls["n"] += 1
- if calls["n"] == 4:
- raise OSError("simulated AV interference")
- return real_rename(src, dst)
-
- monkeypatch.setattr(update_cmd.os, "rename", flaky_rename)
- with pytest.raises(OSError):
- update_cmd._commit_staged_replacements(staged)
- monkeypatch.undo()
-
- versions = {n: (live / n).read_text() for n in ("cli.py", "run_agent.py")}
- assert versions == {"cli.py": "old", "run_agent.py": "old"}, (
- f"mixed/corrupt root modules after rollback: {versions}"
- )
-
-
-def test_failed_staging_leaves_no_orphaned_copies(tmp_path, monkeypatch):
- """#76104 review C2: orphaned staging dirs make the retry we recommend
- fail harder than the original attempt (less free space each time)."""
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"agent": "old", "tools": "old", "gateway": "old"})
- _live_tree(new, {"agent": "new", "tools": "new", "gateway": "new"})
-
- real_copytree = update_cmd.shutil.copytree
- calls = {"n": 0}
-
- def flaky_copytree(src, dst, *a, **kw):
- calls["n"] += 1
- if calls["n"] == 3:
- raise OSError(28, "No space left on device")
- return real_copytree(src, dst, *a, **kw)
-
- monkeypatch.setattr(update_cmd.shutil, "copytree", flaky_copytree)
-
- staged: list[tuple[str, str]] = []
- with pytest.raises(OSError):
- try:
- for n in ("agent", "tools", "gateway"):
- staged.append(
- (
- update_cmd._stage_replacement(
- str(new / n), str(live / n)
- ),
- str(live / n),
- )
- )
- except Exception:
- update_cmd._discard_staged(staged)
- raise
- monkeypatch.undo()
-
- leftovers = [p for p in os.listdir(live) if "hermes-update" in p]
- assert leftovers == [], f"orphaned staging copies: {leftovers}"
- # And nothing live was touched.
- for n in ("agent", "tools", "gateway"):
- assert (live / n / "version.txt").read_text() == "old"
-
-
-def test_atomic_replace_dir_still_works_as_a_shim(tmp_path):
- """W1: it is now an alias over the two-phase helpers; #49145 must hold."""
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"ui-tui": "old"})
- _live_tree(new, {"ui-tui": "new"})
-
- update_cmd._atomic_replace_dir(str(new / "ui-tui"), str(live / "ui-tui"))
-
- assert (live / "ui-tui" / "version.txt").read_text() == "new"
- assert not [p for p in os.listdir(live) if "hermes-update" in p]
-
-
-def test_venv_helpers_honour_an_explicit_platform_verdict():
- """Callers must be able to override the platform check (#76107 CI).
-
- The suite exercises Windows paths on Linux CI by patching predicates like
- `hermes_main._is_windows`. A helper that reads `sys.platform`
- unconditionally silently drops those paths out of coverage -- and broke
- `test_verify_core_dependencies.py::test_uses_virtual_env_from_environment`,
- which patches `_is_windows` and then asserts on a `Scripts/python.exe`
- path.
- """
- v = Path("/opt/proj/venv")
- assert venv_bin_dir(v, windows=True).name == "Scripts"
- assert venv_bin_dir(v, windows=False).name == "bin"
- assert venv_python_path(v, windows=True).name == "python.exe"
- assert venv_python_path(v, windows=False).name == "python"
- # Halves must stay consistent under an explicit verdict.
- for flag in (True, False):
- assert venv_python_path(v, windows=flag).parent == venv_bin_dir(
- v, windows=flag
- )
-
-
-
-
-# ---------------------------------------------------------------------------
-# Crash between "move dst aside" and "move staging in" (Phase 2 review HIGH)
-# ---------------------------------------------------------------------------
-
-def test_staging_restores_backup_when_dst_is_missing(tmp_path, monkeypatch):
- """A previous run that died mid-swap leaves dst missing and the backup as
- the ONLY copy of that entry. On retry, _stage_replacement must restore
- the backup to dst BEFORE clearing leftovers — otherwise a staging failure
- right after (disk exhaustion is likeliest exactly then) leaves a hole in
- the install with nothing to roll back to."""
- live, new = tmp_path / "live", tmp_path / "new"
- live.mkdir()
- _live_tree(new, {"agent": "new"})
- # Simulate the crashed state: dst gone, backup holds the old tree.
- backup = live / "agent.hermes-update-old"
- backup.mkdir()
- (backup / "version.txt").write_text("old")
-
- # Staging fails (disk full) on the fresh copy.
- def boom(src, dst, *a, **kw):
- raise OSError(28, "No space left on device")
-
- monkeypatch.setattr(update_cmd.shutil, "copytree", boom)
- with pytest.raises(OSError):
- update_cmd._stage_replacement(str(new / "agent"), str(live / "agent"))
- monkeypatch.undo()
-
- # The old tree must have been restored to dst before the failure.
- assert (live / "agent" / "version.txt").read_text() == "old"
- assert not backup.exists()
-
- # And a clean retry completes the update normally.
- staged = _stage_all(live, new, ["agent"])
- update_cmd._commit_staged_replacements(staged)
- assert (live / "agent" / "version.txt").read_text() == "new"
- assert not [p for p in os.listdir(live) if "hermes-update" in p]
-
-
-def test_commit_failure_plus_discard_leaves_no_staging_litter(tmp_path, monkeypatch):
- """Phase-2 failure must not orphan staging copies for unswapped entries.
-
- _update_via_zip calls _discard_staged when _commit_staged_replacements
- raises. The rollback restores every swapped entry, but staging copies for
- the not-yet-swapped entries (potentially most of a full tree) would
- otherwise survive — and the retry's up-front free-space check runs BEFORE
- the lazy per-entry leftover cleanup, so the litter makes the retry fail
- harder than the original attempt. This pins the combination: rollback +
- discard leaves the old tree intact and ZERO update litter."""
- live, new = tmp_path / "live", tmp_path / "new"
- _live_tree(live, {"agent": "old", "tools": "old", "gateway": "old"})
- _live_tree(new, {"agent": "new", "tools": "new", "gateway": "new"})
- staged = _stage_all(live, new, ["agent", "tools", "gateway"])
-
- real_rename = os.rename
- calls = {"n": 0}
-
- def flaky_rename(src, dst):
- calls["n"] += 1
- if calls["n"] == 4: # first entry fully swapped, second breaks
- raise OSError("simulated AV interference")
- return real_rename(src, dst)
-
- monkeypatch.setattr(update_cmd.os, "rename", flaky_rename)
- with pytest.raises(OSError):
- try:
- update_cmd._commit_staged_replacements(staged)
- except OSError:
- # Mirrors the _update_via_zip wiring.
- update_cmd._discard_staged(staged)
- raise
- monkeypatch.undo()
-
- # Old tree intact...
- for n in ("agent", "tools", "gateway"):
- assert (live / n / "version.txt").read_text() == "old"
- # ...and zero litter of any kind (staging OR backup).
- litter = [p for p in os.listdir(live) if "hermes-update" in p]
- assert litter == [], f"orphaned update litter: {litter}"
-
-
-def test_update_via_zip_wires_discard_into_the_commit_failure_path():
- """AST wiring contract: _update_via_zip must call _discard_staged from an
- exception handler around _commit_staged_replacements. The behavioral test
- above mirrors that wiring; this pins the production function itself so a
- refactor can't silently drop the cleanup."""
- import ast
- import inspect
- import textwrap
-
- # The swap lives in the download/swap collaborator the ZIP path calls.
- from hermes_cli import update_cmd_zip
-
- src = textwrap.dedent(inspect.getsource(update_cmd_zip._download_and_swap_zip))
- tree = ast.parse(src)
-
- def _calls(node, name):
- return any(
- isinstance(n, ast.Call)
- and isinstance(n.func, ast.Name)
- and n.func.id == name
- for n in ast.walk(node)
- )
-
- wired = False
- for node in ast.walk(tree):
- if not isinstance(node, ast.Try):
- continue
- body_commits = any(
- _calls(stmt, "_commit_staged_replacements") for stmt in node.body
- )
- handler_discards = any(
- _calls(handler, "_discard_staged") for handler in node.handlers
- )
- if body_commits and handler_discards:
- wired = True
- break
- assert wired, (
- "_update_via_zip no longer discards staging copies when "
- "_commit_staged_replacements fails — commit-phase litter will make "
- "the retry's free-space check fail harder than the first attempt"
- )
diff --git a/tests/hermes_cli/test_venv_sync.py b/tests/hermes_cli/test_venv_sync.py
index f07c71294cc..b7c66e1ec93 100644
--- a/tests/hermes_cli/test_venv_sync.py
+++ b/tests/hermes_cli/test_venv_sync.py
@@ -23,75 +23,29 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
def _run_bare(snippet: str) -> subprocess.CompletedProcess:
- """Run a snippet in an isolated interpreter (-I: no env, no user site)
- from the repo root, so a bare import graph is what gets exercised."""
- return subprocess.run(
- [sys.executable, "-I", "-c", textwrap.dedent(snippet)],
- capture_output=True,
- text=True,
- cwd=REPO_ROOT,
- timeout=120,
- )
-
-
-# ── the stdlib-only contract, RUN not parsed ─────────────────────────────
-
-
-class TestStdlibOnly:
- def test_imports_and_answers_bare(self, tmp_path):
- """The whole CLI surface must survive a stripped interpreter."""
- result = _run_bare(
- f"""
- import sys
- sys.path.insert(0, {str(REPO_ROOT)!r})
- from hermes_cli import venv_sync
- root = {str(tmp_path)!r}
- out = venv_sync.sync(root, check=True)
- assert out["state"] == "failed", out # empty dir: no pyproject
- print("ok")
- """
- )
- assert result.returncode == 0, result.stderr
-
- def test_no_third_party_module_ends_up_loaded(self):
- """Importing it must not drag in ANY non-stdlib module.
-
- Check sys.modules after import, because a parser cannot see lazy
- or conditional imports fire. First-party pm is allowed at SYNC
- time but must not load at IMPORT time either — the bare import
- happens on trees where even reading pm's ledger is premature.
-
- Measure the *delta*: snapshot the foreign modules already loaded
- before the import and only flag what the import adds. A hardcoded
- allowlist of ".pth"-injected bootstrap names is not portable — the
- interpreter loads ``.pth`` hooks at startup (setuptools'
- ``_distutils_hack``, pywin32's ``pywin32_bootstrap``, the
- editable-install ``__editable___…_finder``, ``_virtualenv``…) before
- the snippet runs, and that set varies per platform and install
- shape. A before/after diff is sensitive to the import and immune to
- that harness noise.
- """
- result = _run_bare(
- f"""
- import sys
- sys.path.insert(0, {str(REPO_ROOT)!r})
- stdlib = set(sys.stdlib_module_names)
-
- def _foreign():
- return {{
- name.split(".")[0]
- for name, mod in sys.modules.items()
- if mod is not None and getattr(mod, "__file__", None)
- }} - stdlib
-
- before = _foreign()
- import hermes_cli.venv_sync
- dragged_in = {{n for n in _foreign() - before if n != "hermes_cli"}}
- assert not dragged_in, f"venv_sync loaded non-stdlib: {{dragged_in}}"
- print("ok")
- """
- )
- assert result.returncode == 0, result.stderr
+ program = f"import sys\nsys.path.insert(0, {str(REPO_ROOT)!r})\n" + textwrap.dedent(snippet)
+ return subprocess.run([sys.executable, '-I', '-S', '-c', program],
+ capture_output=True, text=True, cwd=REPO_ROOT, timeout=120)
+
+
+def test_bare_import_and_passive_paths(tmp_path):
+ result = _run_bare(f"""
+ from pathlib import Path
+ from hermes_cli import venv_sync
+ assert 'pm' not in sys.modules
+ root = Path({str(tmp_path)!r})
+ assert venv_sync.sync(root, check=True)['state'] == 'failed'
+ (root / 'install-stamp.json').write_text('{{"updateMechanism":"external"}}')
+ assert venv_sync.sync(root) == {{'state': 'sealed', 'ok': True}}
+ assert venv_sync.prepare_launch(root, []) is None
+ assert 'pm' not in sys.modules
+ """)
+ assert result.returncode == 0, result.stderr
+
+
+def test_bare_harness_rejects_third_party_import():
+ result = _run_bare('import requests')
+ assert result.returncode != 0 and 'ModuleNotFoundError' in result.stderr
def _checkout(tmp_path: Path, name: str = "co") -> Path:
@@ -126,11 +80,6 @@ class TestCheckoutSync:
assert venv_sync.sync(root if foreign else None) == {"state": "synced", "ok": True}
assert calls == [(root, True)]
- def test_current_selection_needs_no_transaction(self, tmp_path, monkeypatch):
- root = _checkout(tmp_path)
- calls = _wire_pm(monkeypatch, current=True)
- assert venv_sync.sync(root) == {"state": "current", "ok": True}
- assert calls == []
def test_check_is_passive(self, tmp_path, monkeypatch):
root = _checkout(tmp_path)
diff --git a/tests/hermes_cli/test_verify_console_scripts.py b/tests/hermes_cli/test_verify_console_scripts.py
index 74346d3c4a3..53e9968da7f 100644
--- a/tests/hermes_cli/test_verify_console_scripts.py
+++ b/tests/hermes_cli/test_verify_console_scripts.py
@@ -7,6 +7,8 @@ import textwrap
import pytest
from hermes_cli import main_install_repair
+pytestmark = pytest.mark.platforms("windows")
+
@pytest.fixture
def temp_pyproject(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_web_ui_build.py b/tests/hermes_cli/test_web_ui_build.py
index 165cc5e2576..460b62fe919 100644
--- a/tests/hermes_cli/test_web_ui_build.py
+++ b/tests/hermes_cli/test_web_ui_build.py
@@ -36,40 +36,6 @@ def _make_web_dir(tmp_path: Path) -> tuple[Path, Path]:
-class TestBuildWebUIFlock:
- def test_contended_lock_without_dist_waits_then_skips_fresh_build(self, tmp_path):
- """First-ever build race: the waiter blocks, and once it acquires the
- lock the callee's own staleness check (running under the lock) sees
- the winner's output and skips a duplicate build."""
- import fcntl
- import threading
- from hermes_cli.main_web_build import _build_web_ui as build
-
- web_dir, dist_dir = _make_web_dir(tmp_path)
- # No dist yet — contender must take the blocking-wait path.
- lock_path = tmp_path / ".web_ui_build.lock"
- holder = open(lock_path, "a")
- fcntl.flock(holder.fileno(), fcntl.LOCK_EX)
-
- def release_after_building():
- # Simulate the winning process finishing its build.
- _touch(dist_dir / "index.html")
- stamp_product(tmp_path, "web", dist_dir)
- holder.close() # releases the flock
-
- t = threading.Timer(0.2, release_after_building)
- t.start()
- try:
- with patch("hermes_cli.source_build.source_build_env", side_effect=AssertionError("fresh build must skip preparation")) as mock_run:
- result = build(web_dir)
- finally:
- t.join()
-
- assert result is True
- mock_run.assert_not_called() # fresh after the wait -> no rebuild
-
-
@pytest.mark.platforms("posix")
def test_web_build_prepares_once_and_skips_a_current_product(source_products):
root, acquired = source_products
@@ -122,29 +88,40 @@ def test_web_rebuild_reuses_the_existing_desktop_union(source_products):
@pytest.mark.platforms("linux")
-def test_contended_stale_dist_waits_for_the_lock_holder(tmp_path):
[email protected]('existing', [False, True])
+def test_contended_build_waits_and_rechecks_winner(tmp_path, monkeypatch, existing):
import fcntl
import threading
web, dist = _make_web_dir(tmp_path)
- dist.mkdir(parents=True)
- (dist / "index.html").write_text("stale")
- holder = open(tmp_path / ".web_ui_build.lock", "a")
+ if existing:
+ _touch(dist / 'index.html')
+ holder = open(tmp_path / '.web_ui_build.lock', 'a', encoding='utf-8')
fcntl.flock(holder, fcntl.LOCK_EX)
-
- def finish_build():
- (dist / "index.html").write_text("winner")
- stamp_product(tmp_path, "web", dist)
- holder.close()
-
- worker = threading.Timer(2, finish_build)
+ real_flock = fcntl.flock
+ contended = threading.Event()
+ def flock(fd, operation):
+ contended.set()
+ return real_flock(fd, operation)
+ monkeypatch.setattr(fcntl, 'flock', flock)
+ def finish():
+ try:
+ assert contended.wait(10), 'waiter never attempted the lock'
+ _touch(dist / 'index.html')
+ (dist / 'index.html').write_text('winner', encoding='utf-8')
+ stamp_product(tmp_path, 'web', dist)
+ finally:
+ holder.close()
+ worker = threading.Thread(target=finish)
worker.start()
try:
- assert _build_web_ui(web, fatal=True)
- at_return = (dist / "index.html").read_text()
+ with patch('hermes_cli.source_build.source_build_env', side_effect=AssertionError('duplicate preparation')):
+ assert _build_web_ui(web, fatal=True)
+ assert (dist / 'index.html').read_text(encoding='utf-8') == 'winner'
finally:
- worker.join()
- assert at_return == "winner", "a contended stale index must not count as success"
+ worker.join(timeout=15)
+ holder.close()
+ assert not worker.is_alive()
@pytest.mark.platforms("posix")
diff --git a/tests/hermes_cli/test_windows_native_docs.py b/tests/hermes_cli/test_windows_native_docs.py
deleted file mode 100644
index 659f586e0a5..00000000000
--- a/tests/hermes_cli/test_windows_native_docs.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from pathlib import Path
-
-
-def test_windows_native_install_path_docs_match_installer() -> None:
- doc = Path("website/docs/user-guide/windows-native.md").read_text()
-
- # The launchers live in the managed binary dir OUTSIDE the git checkout
- # (HERMES_HOME\bin, next to the managed uv) — NOT the whole venv\Scripts
- # (which would shadow the user's python, #83797) and NOT a dir inside
- # the checkout (which `hermes update`'s autostash swept off disk).
- assert "%LOCALAPPDATA%\\hermes\\bin" in doc
- assert (
- "Get-Command hermes # should print "
- "C:\\Users\\<you>\\AppData\\Local\\hermes\\bin\\hermes.exe"
- ) in doc