Skip to content

The agent that grows with you

test: purge low-value tests, lane py14 (360 removed)

teknium18f6109e493d2
diff --git a/tests/hermes_cli/test_update_handoff_backend_reap.py b/tests/hermes_cli/test_update_handoff_backend_reap.py
index 28eb094e0da..7800012fd88 100644
--- a/tests/hermes_cli/test_update_handoff_backend_reap.py
+++ b/tests/hermes_cli/test_update_handoff_backend_reap.py
@@ -26,7 +26,6 @@ import types
from unittest.mock import MagicMock, patch
from hermes_cli import main as cli_main
-from hermes_cli import update_cmd
class _FakeNoSuchProcess(Exception):
@@ -78,16 +77,6 @@ def test_live_parent_backend_reaped_in_handoff():
assert cli_main._handoff_reapable_backend_pids(holders) == [200]
-def test_swarm_of_profile_backends_all_reaped():
- profiles = ["mr-tester", "probe-inherit", "turqoise", "clippy", "maroon"]
- procs = {200 + i: _proc(200 + i, _serve_argv(p)) for i, p in enumerate(profiles)}
- fake = _fake_psutil(procs)
- with patch.dict(sys.modules, {"psutil": fake}):
- holders = [
- _holder(200 + i, f"python.exe -m hermes_cli.main --profile {p} serve")
- for i, p in enumerate(profiles)
- ]
- assert sorted(cli_main._handoff_reapable_backend_pids(holders)) == sorted(procs)
def test_dashboard_backend_reaped():
diff --git a/tests/hermes_cli/test_update_handoff_desktop_rebuild.py b/tests/hermes_cli/test_update_handoff_desktop_rebuild.py
index 5be2707b0b6..447ed1f2a2f 100644
--- a/tests/hermes_cli/test_update_handoff_desktop_rebuild.py
+++ b/tests/hermes_cli/test_update_handoff_desktop_rebuild.py
@@ -34,7 +34,7 @@ def test_current_checkout_repair_rebuilds_desktop_under_project_root():
rebuild.assert_called_once()
assert rebuild.call_args[0][0] == update_cmd.Path("/fake/hermes/apps/desktop")
assert rebuild.call_args[1]["had_desktop_app_before_update"] is True
- completion.assert_called_once_with("✓ Already up to date!")
+ completion.assert_called_once()
def test_failed_desktop_rebuild_withholds_success_completion():
@@ -87,4 +87,4 @@ def test_handoff_venv_repair_finishes_node_and_web_phase(tmp_path):
assert complete is True
update_node.assert_called_once_with()
m.return_value._build_web_ui.assert_called_once_with(project_root / "web")
- completion.assert_called_once_with("✓ Update complete!")
+ completion.assert_called_once()
diff --git a/tests/hermes_cli/test_update_hangup_protection.py b/tests/hermes_cli/test_update_hangup_protection.py
index 61a6f489587..a4b6c5a5413 100644
--- a/tests/hermes_cli/test_update_hangup_protection.py
+++ b/tests/hermes_cli/test_update_hangup_protection.py
@@ -12,7 +12,6 @@ import io
import signal
import sys
-import pytest
from hermes_cli.main_dashboard import _UpdateOutputStream, _finalize_update_output, _install_hangup_protection
from hermes_cli.update_cmd import _log_only_write, _print_update_completion, _run_logged_subprocess
@@ -77,19 +76,6 @@ class TestUpdateOutputStream:
- def test_isatty_delegates_to_original(self):
- class _TtyStream:
- def isatty(self):
- return True
-
- def write(self, data):
- return len(data)
-
- def flush(self):
- return None
-
- stream = _UpdateOutputStream(_TtyStream(), io.StringIO())
- assert stream.isatty() is True
# -----------------------------------------------------------------------------
@@ -124,7 +110,6 @@ class TestInstallHangupProtection:
assert log_path.exists()
contents = log_path.read_text(encoding="utf-8")
assert "checking mirror" in contents
- assert "hermes update started" in contents
finally:
_finalize_update_output(state)
# Sanity-check restoration
@@ -169,8 +154,6 @@ class TestInstallHangupProtection:
class TestFinalizeUpdateOutput:
- def test_none_state_is_noop(self):
- _finalize_update_output(None) # must not raise
def test_skipped_install_leaves_stdio_alone(self):
@@ -206,12 +189,6 @@ class TestLogOnlyWrite:
_log_only_write("something") # should not raise
assert plain.getvalue() == ""
- def test_empty_text_is_noop(self, monkeypatch):
- terminal = io.StringIO()
- log = io.StringIO()
- monkeypatch.setattr(sys, "stdout", _UpdateOutputStream(terminal, log))
- _log_only_write("")
- assert log.getvalue() == ""
class TestRunLoggedSubprocess:
diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.py
index 0e3faafe7b8..2bc4bc238cc 100644
--- a/tests/hermes_cli/test_update_head_moved_gate.py
+++ b/tests/hermes_cli/test_update_head_moved_gate.py
@@ -19,35 +19,6 @@ import hermes_cli.main_install_repair as main_install_repair
from hermes_cli import update_cmd
-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 — first call (pre-pull) returns pre_sha,
- # subsequent calls (post-pull) return post_sha.
- if joined.endswith("rev-parse HEAD"):
- if calls["n"] == 0:
- 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."""
@@ -129,16 +100,6 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
)
-def test_update_success_when_head_moves(monkeypatch, tmp_path, capsys):
- """When the pull advances HEAD, the update proceeds normally."""
- args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)
- _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())
-
- hermes_main.cmd_update(args) # completes normally (no SystemExit)
-
- out = capsys.readouterr().out
- assert "✓ Code updated!" in out
- assert "Code did not move" not in out
def test_update_fails_loudly_when_head_pinned(monkeypatch, tmp_path, capsys):
@@ -152,6 +113,5 @@ def test_update_fails_loudly_when_head_pinned(monkeypatch, tmp_path, capsys):
assert exc_info.value.code == 1
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_host_obligation.py b/tests/hermes_cli/test_update_host_obligation.py
index 421455996f0..1c554c83f49 100644
--- a/tests/hermes_cli/test_update_host_obligation.py
+++ b/tests/hermes_cli/test_update_host_obligation.py
@@ -91,7 +91,6 @@ def test_host_gateway_restarts_once_when_two_profiles_run_the_catch_up(
assert update_cmd._run_pending_fleet_restart() is True
assert len(kills) == 1, "the one host gateway must be stopped once per update, not once per profile"
- assert "already restarted for this update" in capsys.readouterr().out
def test_legacy_per_home_marker_is_still_read_and_cleared(two_profiles, no_live_fleet, monkeypatch):
@@ -132,8 +131,6 @@ def test_leftover_per_profile_units_restart_their_one_host_process_once(monkeypa
assert restarted == ["hermes-gateway"]
assert failed == []
- out = capsys.readouterr().out
- assert "hermes-gateway-coder" in out and "legacy per-profile unit" in out
def test_units_with_distinct_live_pids_are_each_restarted(monkeypatch):
@@ -193,15 +190,6 @@ def test_recovery_keeps_separate_processes_separate(tmp_path, monkeypatch):
assert len([argv for argv in argvs if argv[-2:] == ["gateway", "restart"]]) == 2
-def test_host_obligation_lives_beside_the_host_rendezvous_record(two_profiles, monkeypatch, tmp_path):
- """The record is written ONCE PER HOST, in the cross-profile rendezvous dir."""
- _enter(monkeypatch, two_profiles["coder"])
- _arm("coder")
-
- path = host_obligation.host_obligation_path()
- assert path == tmp_path / "gateway-locks" / "host-update-restart.json"
- assert path.is_file()
- assert not (two_profiles["coder"] / "fleet_restart_pending").exists()
@pytest.mark.skipif(getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores directory permissions")
@@ -271,7 +259,6 @@ def test_restart_runs_once_per_host_on_a_non_git_install(two_profiles, monkeypat
assert update_cmd._run_pending_fleet_restart() is True
assert len(kills) == 1, "the host gateway must be stopped once per update, not once per profile"
- assert "already restarted for this update" in capsys.readouterr().out
def test_a_failing_main_pid_probe_keeps_its_own_restart():
diff --git a/tests/hermes_cli/test_update_import_guard.py b/tests/hermes_cli/test_update_import_guard.py
index 699804ef11a..400a314e0c2 100644
--- a/tests/hermes_cli/test_update_import_guard.py
+++ b/tests/hermes_cli/test_update_import_guard.py
@@ -21,7 +21,6 @@ from pathlib import Path
import pytest
-from hermes_cli import main as hermes_main
from hermes_cli import update_cmd
import hermes_cli.update_cmd_deps as update_cmd_deps
from hermes_constants import partial_update_hint
@@ -150,7 +149,7 @@ def test_import_guard_reports_probe_termination_when_comparing_states(
assert ok is False
assert module == "critical-module probe"
- assert error == "terminated before reporting import health (exit code 7)"
+ assert error and "7" in error
def test_import_guard_reports_probe_termination_by_default(monkeypatch, tmp_path):
@@ -163,7 +162,7 @@ def test_import_guard_reports_probe_termination_by_default(monkeypatch, tmp_path
assert ok is False
assert module == "critical-module probe"
- assert error == "terminated before reporting import health (exit code 9)"
+ assert error and "9" in error
def test_import_guard_reports_system_exit_by_default(monkeypatch, tmp_path):
@@ -194,7 +193,7 @@ def test_import_guard_does_not_accept_forged_static_marker(monkeypatch, tmp_path
assert ok is False
assert module == "critical-module probe"
- assert error == "terminated before reporting import health (exit code 7)"
+ assert error and "7" in error
def test_import_guard_rejects_malformed_health_payload(monkeypatch, tmp_path):
@@ -213,11 +212,9 @@ def test_import_guard_rejects_malformed_health_payload(monkeypatch, tmp_path):
assert ok is False
assert module == "critical-module probe"
- assert error == "reported malformed import health data"
def test_import_guard_reports_probe_timeout(monkeypatch, tmp_path):
- import subprocess
def timeout(*_args, **_kwargs):
return None
@@ -228,7 +225,6 @@ def test_import_guard_reports_probe_timeout(monkeypatch, tmp_path):
assert ok is False
assert module == "critical-module probe"
- assert error == "timed out before reporting import health"
def test_untracked_enumeration_failure_is_visible(monkeypatch, tmp_path, capsys):
@@ -239,15 +235,8 @@ def test_untracked_enumeration_failure_is_visible(monkeypatch, tmp_path, capsys)
monkeypatch.setattr(update_cmd.subprocess, "run", lambda *_a, **_kw: Result())
assert update_cmd._git_untracked_paths(["git"], tmp_path) is None
- assert "Could not enumerate untracked files" in capsys.readouterr().out
-def test_import_guard_reports_bounded_probe_failure(monkeypatch, tmp_path):
- """A wedged child reports promptly instead of blocking update teardown."""
- monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", lambda *_a, **_kw: None)
- assert update_cmd._validate_critical_modules_import(tmp_path) == (
- False, "critical-module probe", "timed out before reporting import health",
- )
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX exec-bit PermissionError")
@@ -265,14 +254,6 @@ def test_import_guard_is_non_fatal_when_probe_cannot_run(tmp_path):
# partial_update_hint
# ---------------------------------------------------------------------------
-def test_hint_fires_for_first_party_import_error():
- exc = ImportError("cannot import name 'TODO_INJECTION_HEADER'")
- exc.name = "tools.todo_tool"
-
- hint = partial_update_hint(exc)
-
- assert hint, "expected recovery guidance for a first-party ImportError"
- assert any("hermes update" in line for line in hint)
@pytest.mark.parametrize(
@@ -418,43 +399,3 @@ def test_hint_fires_for_each_first_party_root(modname):
assert partial_update_hint(exc), f"expected guidance for {modname}"
-def test_probe_and_hint_share_one_first_party_definition():
- """The guard that BLOCKS and the hint that EXPLAINS must never disagree.
-
- These started as two hand-maintained lists and immediately diverged:
- `cli` was first-party to the hint but not the probe, and `hermesx`
- (third-party) matched the probe's loose `startswith("hermes")`. A user
- could get a rollback with no explanation, or an explanation with no
- detection. Both now derive from FIRST_PARTY_MODULE_ROOTS; this test
- fails if either grows a private copy.
- """
- from hermes_constants import FIRST_PARTY_MODULE_ROOTS, is_first_party_module
-
- captured = {}
-
- class _Result:
- returncode = 0
- stdout = ""
- stderr = ""
-
- def capture(cmd, **_kw):
- captured["probe"] = cmd[-1]
- return _Result()
-
- real_run = update_cmd_deps.bounded_probe_run
- update_cmd_deps.bounded_probe_run = capture
- try:
- update_cmd._validate_critical_modules_import("/tmp")
- finally:
- update_cmd_deps.bounded_probe_run = real_run
-
- probe_src = captured["probe"]
- # Every first-party root must appear in the probe's injected tuple.
- for root in FIRST_PARTY_MODULE_ROOTS:
- assert repr(root) in probe_src, f"{root} missing from the probe's root set"
- # And the hint must agree on each of them.
- for root in FIRST_PARTY_MODULE_ROOTS:
- assert is_first_party_module(f"{root}.anything")
- # Lookalikes stay out of both.
- for lookalike in ("agents", "agentops", "toolsets_x", "hermesx"):
- assert not is_first_party_module(lookalike)
diff --git a/tests/hermes_cli/test_update_interrupted_recovery.py b/tests/hermes_cli/test_update_interrupted_recovery.py
index ea009515335..c7a4fc9057a 100644
--- a/tests/hermes_cli/test_update_interrupted_recovery.py
+++ b/tests/hermes_cli/test_update_interrupted_recovery.py
@@ -1,18 +1,12 @@
"""Tests for interrupted-install self-heal (the ``.update-incomplete`` marker).
-Covers the breadcrumb lifecycle and the launch-time recovery guard added so a
-``hermes update`` killed mid-install (Ctrl-C, terminal close, WSL OOM) gets
-finished automatically on the next launch instead of leaving a half-built venv.
+Covers the breadcrumb lifecycle so a ``hermes update`` killed mid-install
+(Ctrl-C, terminal close, WSL OOM) leaves a marker the next launch can act on.
"""
from __future__ import annotations
-from pathlib import Path
-
import hermes_cli.main as m
-import hermes_cli.main_install_repair as hermes_cli_main_install_repair
-from hermes_cli import main_install_repair
-from hermes_cli import update_cmd
def test_marker_round_trip(tmp_path, monkeypatch):
@@ -29,90 +23,3 @@ def test_marker_round_trip(tmp_path, monkeypatch):
m._clear_update_incomplete_marker()
assert not marker.exists()
-
-
-
-
-
-
-def _stub_install_env(monkeypatch, m, seen):
- """Common stubs so recovery's install path is inert and observable."""
- import hermes_cli.main_install_repair as hermes_cli_main_install_repair
-
- class R:
- returncode = 0
-
- monkeypatch.setattr(m.subprocess, "run", lambda *a, **k: R())
- monkeypatch.setattr(m, "_is_termux_env", lambda *a, **k: False)
- monkeypatch.setattr(hermes_cli_main_install_repair, "_is_termux_env", lambda *a, **k: False)
- monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", lambda: None)
- # The install executor moved to hermes_cli._install_repair (shared between
- # the pre-import early pass and this late recovery path) — stub WHERE it
- # is executed, not the legacy main.py wrapper it replaced.
- import hermes_cli._install_repair as ir
-
- monkeypatch.setattr(
- ir, "run_core_install", lambda _root: seen.__setitem__("install", True)
- )
-
-
-def test_recovery_self_lock_does_not_clear_core_marker_via_import_probes(
- tmp_path, monkeypatch
-):
- # ``.update-incomplete`` is the generic core-install marker. Healthy
- # lazy-refresh import probes alone must NOT clear it and skip full
- # reinstall — a missing dep outside the 7-probe set would look healthy
- # (#58004 review blocker).
- monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
- (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n")
- m._write_update_incomplete_marker()
-
- scripts_dir = tmp_path / "venv" / "Scripts"
- scripts_dir.mkdir(parents=True)
- shim = scripts_dir / "hermes.exe"
- shim.write_text("")
-
- monkeypatch.setattr(m, "_is_windows", lambda: True)
- monkeypatch.setattr(hermes_cli_main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(m, "_venv_scripts_dir", lambda: scripts_dir)
- monkeypatch.setattr(hermes_cli_main_install_repair, "_venv_scripts_dir", lambda: scripts_dir)
- monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: [shim])
- monkeypatch.setattr(main_install_repair, "_default_venv_install_target",
- lambda: (["uv", "pip"], {"VIRTUAL_ENV": str(tmp_path / "venv")}),
- )
- monkeypatch.setattr(
- m, "_repair_venv_via_import_probes", lambda *a, **k: "healthy"
- )
- monkeypatch.setattr(
- hermes_cli_main_install_repair, "_repair_venv_via_import_probes", lambda *a, **k: "healthy"
- )
-
- class FakeProc:
- def __init__(self, exe_path):
- self._exe = exe_path
-
- def exe(self):
- return self._exe
-
- def parents(self):
- return [FakeProc(str(shim))]
-
- monkeypatch.setattr("psutil.Process", lambda: FakeProc(sys_executable_path()))
-
- seen = {"install": False}
- _stub_install_env(monkeypatch, m, seen)
-
- m._recover_from_interrupted_install()
-
- assert seen["install"] is True, "core marker still requires full reinstall"
- assert not m._update_marker_path().exists(), "cleared only after full reinstall"
-
-
-
-
-def sys_executable_path():
- import sys
-
- return sys.executable
-
-
diff --git a/tests/hermes_cli/test_update_inventory.py b/tests/hermes_cli/test_update_inventory.py
index f0f2ee39e5f..fb4d120b0c8 100644
--- a/tests/hermes_cli/test_update_inventory.py
+++ b/tests/hermes_cli/test_update_inventory.py
@@ -140,31 +140,6 @@ class TestCollectInventory:
assert restored["runtimes"][0]["kind"] == "gateway"
-class TestPrintPlan:
- def test_git_fleet_output(self, fleet, capsys):
- ui.print_update_plan(ui.collect_runtime_inventory())
- out = capsys.readouterr().out
- assert "Update plan:" in out
- assert "Install: git" in out
- assert "default, work" in out
- assert "pid 100" in out and "systemd" in out
- assert "pid 200" in out and "manual" in out
-
- def test_docker_warns_not_in_place(self, fleet, monkeypatch, capsys):
- monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda *a, **k: "docker")
- monkeypatch.setattr(
- "hermes_cli.config.recommended_update_command_for_method",
- lambda m: "docker pull nousresearch/hermes-agent:latest",
- )
- ui.print_update_plan(ui.collect_runtime_inventory())
- out = capsys.readouterr().out
- assert "NOT updatable in place" in out
- assert "docker pull" in out
-
- def test_empty_fleet_message(self, fleet, monkeypatch, capsys):
- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
- ui.print_update_plan(ui.collect_runtime_inventory())
- assert "none detected" in capsys.readouterr().out
class TestReceiptIntegration:
@@ -183,8 +158,3 @@ class TestReceiptIntegration:
assert payload["plan"]["install_method"] == "git"
assert len(payload["plan"]["runtimes"]) == 2
- def test_noop_without_active_receipt(self, fleet):
- import hermes_cli.update_receipt as ur
-
- ur._current = None
- ui.record_plan_in_receipt(ui.collect_runtime_inventory()) # must not raise
diff --git a/tests/hermes_cli/test_update_launchd_fleet_restart.py b/tests/hermes_cli/test_update_launchd_fleet_restart.py
index 85fba9dcb62..e1114e489f0 100644
--- a/tests/hermes_cli/test_update_launchd_fleet_restart.py
+++ b/tests/hermes_cli/test_update_launchd_fleet_restart.py
@@ -21,7 +21,6 @@ in a domain it does not live in.
from __future__ import annotations
import subprocess
-import sys
from pathlib import Path
import pytest
@@ -30,7 +29,6 @@ import hermes_cli.gateway as gw
import hermes_cli.profiles
from hermes_cli.gateway import (
_locate_launchd_gateway_service,
- _parse_launchd_pid_from_print_output,
_probe_launchd_domain_for_label,
launchd_gateway_labels_for_install,
)
@@ -106,12 +104,6 @@ class TestLaunchdGatewayLabelsForInstall:
assert launchd_gateway_labels_for_install() == []
-class TestParseLaunchdPidFromPrintOutput:
- def test_running_service_pid(self):
- assert _parse_launchd_pid_from_print_output(PRINT_RUNNING) == 4242
-
- def test_loaded_but_not_running_has_no_pid(self):
- assert _parse_launchd_pid_from_print_output(PRINT_LOADED_NOT_RUNNING) is None
class TestLocateLaunchdGatewayService:
@@ -228,19 +220,6 @@ class TestGetServicePidsScoping:
self._wire(monkeypatch)
assert gw._get_service_pids() == {100}
- def test_find_gateway_pids_passes_profile_scope_through(self, monkeypatch):
- calls: list[bool] = []
- monkeypatch.setattr(
- gw,
- "_get_service_pids",
- lambda all_profiles=False: (calls.append(all_profiles), set())[1],
- )
- monkeypatch.setattr(gw, "_scan_gateway_pids", lambda *a, **k: [])
- monkeypatch.setattr(gw, "supports_systemd_services", lambda: True)
-
- gw.find_gateway_pids(all_profiles=False)
- gw.find_gateway_pids(all_profiles=True)
- assert calls == [False, True]
def _fleet(monkeypatch, tmp_path, *, current, labels, located,
@@ -736,6 +715,5 @@ class TestIncompleteWarningOnMacos:
def test_launchd_labels_get_bootstrap_hint(self, capsys):
_warn_incomplete_gateway_fleet_restart(["ai.hermes.gateway-merit-ops"])
out = capsys.readouterr().out
- assert "Update incomplete" in out
assert "launchctl bootstrap" in out
assert "systemctl" not in out
diff --git a/tests/hermes_cli/test_update_launchd_restart_verification.py b/tests/hermes_cli/test_update_launchd_restart_verification.py
index d37c28cc43d..877bc34acc0 100644
--- a/tests/hermes_cli/test_update_launchd_restart_verification.py
+++ b/tests/hermes_cli/test_update_launchd_restart_verification.py
@@ -26,7 +26,6 @@ import pytest
import hermes_cli.gateway as gateway_cli
import hermes_cli.update_cmd as update_cmd
-from hermes_cli.update_cmd import _warn_incomplete_gateway_fleet_restart
LABEL = "ai.hermes.gateway"
@@ -132,8 +131,6 @@ class TestWaitForLaunchdGatewaySupervision:
is False
)
assert sum(clock.slept) <= 20.0
- # The deadline is enforced by wall clock, not by a probe count.
- assert len(probe.calls) == 41
def test_detached_fallback_is_not_a_failure(self, monkeypatch, clock):
"""On a host where launchd cannot manage the domain, no pid is correct.
@@ -349,22 +346,3 @@ class TestInvokingProfileIsVerifiedLikeItsSiblings:
assert calls["verify"] == 1
-class TestIncompleteFleetWarningIsPlatformCorrect:
- def test_macos_recovery_instructions_are_launchctl(self, monkeypatch, capsys):
- """A launchd label must not be handed systemctl commands."""
- monkeypatch.setattr(gateway_cli, "is_macos", lambda: True)
-
- _warn_incomplete_gateway_fleet_restart([LABEL])
-
- out = capsys.readouterr().out
- assert "launchctl bootstrap" in out
- assert "systemctl" not in out
-
- def test_linux_recovery_instructions_are_unchanged(self, monkeypatch, capsys):
- monkeypatch.setattr(gateway_cli, "is_macos", lambda: False)
-
- _warn_incomplete_gateway_fleet_restart(["hermes-gateway.service"])
-
- out = capsys.readouterr().out
- assert "systemctl --user restart <unit>" in out
- assert "launchctl" not in out
diff --git a/tests/hermes_cli/test_update_launchd_unloaded_gateway.py b/tests/hermes_cli/test_update_launchd_unloaded_gateway.py
index 315fa724422..e55dc7b9564 100644
--- a/tests/hermes_cli/test_update_launchd_unloaded_gateway.py
+++ b/tests/hermes_cli/test_update_launchd_unloaded_gateway.py
@@ -88,7 +88,6 @@ class TestLaunchdRestartAfterUpdate:
assert update_cmd._restart_launchd_gateway_after_update(supervision_verify=False) == ([], ["ai.hermes.gateway"])
out = capsys.readouterr().out
- assert "Gateway restart failed" in out
assert "kickstart refused" in out
assert "hermes gateway restart" in out
@@ -107,7 +106,6 @@ class TestLaunchdRestartAfterUpdate:
assert update_cmd._restart_launchd_gateway_after_update(supervision_verify=False) == ([], ["ai.hermes.gateway"])
assert calls == []
out = capsys.readouterr().out
- assert "Could not restart the gateway" in out
assert "hermes gateway restart" in out
def test_no_plist_is_not_a_launchd_install(self, launchd, capsys):
@@ -133,6 +131,7 @@ ai.hermes.gateway = {
"""
class TestServicePidSweepExclusion:
"""Regression for the PR #75021 review: `_get_service_pids()` must not
rely on `launchctl list` alone.
@@ -150,7 +149,6 @@ class TestServicePidSweepExclusion:
state = {"list_rc": 1, "print_rc": 0, "print_out": _PRINT_OUTPUT_RUNNING}
monkeypatch.setattr(gateway_mod, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(gateway_mod, "is_macos", lambda: True)
monkeypatch.setattr(gateway_mod, "get_launchd_label", lambda: "ai.hermes.gateway")
monkeypatch.setattr(gateway_mod, "_launchd_domain", lambda: "gui/501")
diff --git a/tests/hermes_cli/test_update_lock.py b/tests/hermes_cli/test_update_lock.py
index 912d217d898..a71fac318f0 100644
--- a/tests/hermes_cli/test_update_lock.py
+++ b/tests/hermes_cli/test_update_lock.py
@@ -162,7 +162,6 @@ def test_describe_holder_names_the_pid_and_elapsed_time(marker):
message = describe_holder(holder)
assert str(os.getpid()) in message, "the user needs the pid to find the other update"
- assert "already running" in message
def test_unwritable_marker_location_does_not_block_the_update(tmp_path):
diff --git a/tests/hermes_cli/test_update_messages.py b/tests/hermes_cli/test_update_messages.py
index babf24a6350..7a1a34d34d7 100644
--- a/tests/hermes_cli/test_update_messages.py
+++ b/tests/hermes_cli/test_update_messages.py
@@ -25,18 +25,11 @@ class TestFleetMatrixVerdict:
]
assert ur.print_fleet_version_matrix(fleet) is True
out = capsys.readouterr().out
- verdict = [line for line in out.splitlines() if "Update not complete" in line]
- assert len(verdict) == 1
- assert verdict[0].startswith("✗")
- assert "2 gateway" in out
assert "hermes gateway restart" in out
- assert "hermes -p <profile> gateway restart" in out
- assert "hermes gateway status" in out
def test_unknown_rows_print_no_verdict(self, capsys):
fleet = [{"profile": "default", "pid": 1, "code_sha": None, "state": "unknown"}]
assert ur.print_fleet_version_matrix(fleet) is False
- assert "Update not complete" not in capsys.readouterr().out
class TestCalledProcessErrorMessage:
@@ -54,22 +47,5 @@ class TestCalledProcessErrorMessage:
update_cmd._handle_update_called_process_error(exc, object(), False, False)
assert info.value.code == 1
out = capsys.readouterr().out
- lines = [line for line in out.splitlines() if line.strip()]
- assert lines[0].startswith("✗ Python dependency install failed")
- assert "code update itself succeeded" in lines[0]
- assert "returned non-zero exit status" not in lines[0]
assert "disk full" in out
- assert "hermes update" in out
- assert "Re-downloading" not in out
- def test_non_dep_failure_moves_repr_to_details_line(self, capsys, no_exit, monkeypatch):
- monkeypatch.setattr(update_cmd._m(), "_is_windows", lambda: False)
- exc = subprocess.CalledProcessError(128, ["git", "pull"], stderr="fatal: not a git repository")
- with pytest.raises(SystemExit):
- update_cmd._handle_update_called_process_error(exc, object(), False, False)
- out = capsys.readouterr().out
- lines = [line for line in out.splitlines() if line.strip()]
- assert lines[0].startswith("✗ Git update failed")
- assert "returned non-zero exit status" not in lines[0]
- assert any(line.strip().startswith("Details:") and "returned non-zero exit status 128" in line
- for line in lines)
diff --git a/tests/hermes_cli/test_update_missing_configured_deps.py b/tests/hermes_cli/test_update_missing_configured_deps.py
index a38f035cb2e..11decd63cb8 100644
--- a/tests/hermes_cli/test_update_missing_configured_deps.py
+++ b/tests/hermes_cli/test_update_missing_configured_deps.py
@@ -29,12 +29,10 @@ def test_fallback_names_configured_platform_whose_extra_failed(monkeypatch, caps
out = _run_fallback_with_failed_extra(
monkeypatch, capsys, extra_fails="feishu",
missing_features=[("Feishu / Lark", "Run `hermes setup` to install Feishu support.")])
- assert "fail to load them on restart" in out
assert "Feishu / Lark" in out and "hermes setup" in out
- # Unconfigured features that failed stay a plain "skipped" line, no scary warning.
+ # Unconfigured features that failed are still reported by extra name, never silently dropped.
quiet = _run_fallback_with_failed_extra(monkeypatch, capsys, extra_fails="feishu", missing_features=[])
- assert "Skipped optional extras that still failed: feishu" in quiet
- assert "fail to load them on restart" not in quiet
+ assert "feishu" in quiet
def test_configured_features_probe_reads_the_fresh_target_interpreter(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_update_modified_notice.py b/tests/hermes_cli/test_update_modified_notice.py
deleted file mode 100644
index 1dfd2272d46..00000000000
--- a/tests/hermes_cli/test_update_modified_notice.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""Guard: every `hermes update` path that reports user-modified skills must
-also tell the user how to find them.
-
-`hermes update` keeps (does not overwrite) bundled skills the user edited and
-prints a ``~ N user-modified (kept)`` count. There are two independent update
-code paths in ``hermes_cli/main.py`` that print this notice (the git-pull path
-in ``_cmd_update_impl`` and the unpack/install path). Both must point the user
-at ``hermes skills list-modified`` so the count is actionable — otherwise,
-depending on which path a user hits, they may never learn the discovery command
-exists.
-
-This is an *invariant* test (the two sibling notices must agree), not a literal
-snapshot: it asserts the relationship "count line ⇒ discovery hint", so it
-keeps holding if the wording is reworded, as long as both sites stay in sync.
-"""
-
-import re
-from pathlib import Path
-
-import hermes_cli.main as main_mod
-import hermes_cli.update_cmd as update_mod
-import hermes_cli.update_cmd_maint as update_maint_mod
-import hermes_cli.update_cmd_zip as update_zip_mod
-
-
-_COUNT_RE = re.compile(r"user-modified \(kept\)")
-_HINT_RE = re.compile(r"hermes skills list-modified")
-
-
-def _source_lines() -> list[str]:
- # The update pipeline was extracted to hermes_cli/update_cmd.py and then
- # split into update_cmd_*.py; scan every home of the notice.
- return [
- line
- for mod in (main_mod, update_mod, update_maint_mod, update_zip_mod)
- for line in Path(mod.__file__).read_text(encoding="utf-8").splitlines()
- ]
-
-
-def test_every_user_modified_notice_points_at_list_modified():
- lines = _source_lines()
- count_sites = [i for i, ln in enumerate(lines) if _COUNT_RE.search(ln)]
-
- # The notice must exist somewhere (guard against it being deleted outright),
- # but we deliberately do NOT assert a fixed *count* of sites: consolidating
- # the duplicated print paths into a shared helper is a welcome refactor and
- # must not fail this test. The invariant is per-site, not how many sites.
- assert count_sites, (
- "no 'user-modified (kept)' notice found in main.py — the update "
- "summary that surfaces kept user edits appears to have been removed"
- )
-
- for idx in count_sites:
- # The count print and its discovery hint sit on adjacent lines; allow a
- # small window so wording/formatting tweaks don't break the check.
- window = "\n".join(lines[idx : idx + 5])
- assert _HINT_RE.search(window), (
- "a 'user-modified (kept)' notice near line "
- f"{idx + 1} of main.py does not point users at "
- "`hermes skills list-modified` within the following lines — the "
- "update paths have drifted apart again:\n" + window
- )
diff --git a/tests/hermes_cli/test_update_multiplex_migration_hook.py b/tests/hermes_cli/test_update_multiplex_migration_hook.py
deleted file mode 100644
index 5e77a6a370a..00000000000
--- a/tests/hermes_cli/test_update_multiplex_migration_hook.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""``hermes update`` runs the multiplex auto-migration hook only after a verified-healthy fleet restart.
-
-Reuses the mocked-git ``cmd_update`` harness from ``test_update_fleet_restart_pending`` (network and
-restart stubbed). The hook itself is faked to a recorder: what is under test is its placement — it
-runs on the success path and is skipped when the fleet verification exits 1.
-"""
-
-from __future__ import annotations
-
-import pytest
-
-from hermes_cli import main as hermes_main
-from hermes_cli import gateway_migrate
-
-from tests.hermes_cli.test_update_fleet_restart_pending import (
- _make_head_moved_side_effect, _patch_update_deps, _update_args,
-)
-
-
-def hook_calls(monkeypatch):
- calls: list[str] = []
- monkeypatch.setattr(gateway_migrate, "maybe_auto_migrate_after_update", lambda: calls.append("hook"))
- return calls
-
-
-def test_successful_update_runs_multiplex_hook_once(monkeypatch, tmp_path, hook_calls):
- _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())
- hermes_main.cmd_update(_update_args())
- assert hook_calls == ["hook"]
-
-
-def test_incomplete_fleet_verification_skips_multiplex_hook(monkeypatch, tmp_path, hook_calls):
- """A fleet that may still run stale code is never migrated on top of the failure."""
- _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect())
- monkeypatch.setattr("hermes_cli.update_receipt.print_fleet_version_matrix", lambda rows: True)
- with pytest.raises(SystemExit) as exc:
- hermes_main.cmd_update(_update_args())
- assert exc.value.code == 1
- assert hook_calls == []
diff --git a/tests/hermes_cli/test_update_no_gateway_restart.py b/tests/hermes_cli/test_update_no_gateway_restart.py
index 2b732ab67de..2426d296fc0 100644
--- a/tests/hermes_cli/test_update_no_gateway_restart.py
+++ b/tests/hermes_cli/test_update_no_gateway_restart.py
@@ -6,7 +6,7 @@ itself). The flag runs the full update pipeline but defers the restart;
the pending-restart marker is kept so a later normal update catches up.
"""
from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
from hermes_cli import update_cmd as uc
from hermes_cli import update_cmd_fleet as fleet
@@ -23,37 +23,6 @@ def _opts(**overrides):
return SimpleNamespace(**base)
-def test_pulled_update_defers_restart_and_keeps_marker_under_flag():
- with (
- patch.object(uc, "_invalidate_update_cache"),
- patch.object(uc, "_verify_head_after_pull", return_value="newsha"),
- patch.object(uc, "_write_fleet_restart_pending_marker") as mock_marker,
- patch.object(uc, "_clear_fleet_restart_pending_marker") as mock_clear,
- patch.object(uc, "_sweep_bytecode_after_update"),
- patch.object(uc, "_sync_python_dependencies_after_pull"),
- patch.object(uc, "_update_node_dependencies", return_value=[]),
- patch.object(uc, "_rebuild_desktop_after_update", return_value=True),
- patch.object(uc, "_run_post_update_maintenance", return_value=True),
- patch.object(uc, "_branch_head_suffix", return_value=""),
- patch.object(uc, "_m", return_value=MagicMock()),
- patch.object(uc, "_restart_gateway_fleet_after_update") as mock_restart,
- patch.object(uc, "_resume_windows_gateways_and_merge_outcome") as mock_resume,
- patch.object(uc, "_verify_fleet_after_update") as mock_verify,
- patch.object(uc, "_defer_fleet_restart_after_update") as mock_defer,
- ):
- uc._apply_pulled_update(
- "git", "main", "oldsha", SimpleNamespace(in_place_update=False),
- _opts(no_gateway_restart=True), gateway_mode=False,
- is_fork=False, desktop_dir="/tmp", had_desktop_app_before_update=False,
- pre_update_snapshot_id=None, _pre_update_plan=None,
- _windows_gateway_resume=None, args=SimpleNamespace(no_gateway_restart=True, yes=True),
- )
- mock_restart.assert_not_called()
- mock_verify.assert_not_called()
- mock_defer.assert_called_once_with(update_complete=True, resume_incomplete=False)
- mock_resume.assert_called_once() # Windows pause/resume still runs
- mock_marker.assert_called_once() # pending marker kept for catch-up
- mock_clear.assert_not_called() # deferred stale fleet alone is not partial
def test_already_current_catchup_is_deferred_under_flag():
diff --git a/tests/hermes_cli/test_update_orphan_backend_reap.py b/tests/hermes_cli/test_update_orphan_backend_reap.py
index c121d0fb0d6..0fed9dbbfaa 100644
--- a/tests/hermes_cli/test_update_orphan_backend_reap.py
+++ b/tests/hermes_cli/test_update_orphan_backend_reap.py
@@ -20,7 +20,6 @@ from __future__ import annotations
import sys
import types
-from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from hermes_cli import main as cli_main
@@ -204,7 +203,6 @@ def test_missing_psutil_keeps_refusal():
def test_stop_process_trees_kills_full_tree():
- from hermes_cli import update_cmd
with patch("gateway.status.get_process_start_time", return_value=123), patch(
"hermes_cli._subprocess_compat.pid_is_hermes", return_value=True
@@ -215,102 +213,3 @@ def test_stop_process_trees_kills_full_tree():
["taskkill", "/PID", "111", "/T", "/F"],
["taskkill", "/PID", "222", "/T", "/F"],
]
-
-
-def test_stop_process_trees_never_raises():
- from hermes_cli import update_cmd
-
- with patch.object(
- update_cmd.subprocess, "run", side_effect=OSError("no taskkill")
- ):
- cli_main._stop_process_trees([111]) # must not raise
-
-
-# ---------------------------------------------------------------------------
-# Guard integration: orphan reap clears the dead-end
-# ---------------------------------------------------------------------------
-
-
-def _update_args(**overrides):
- defaults = dict(
- gateway=False,
- check=False,
- no_backup=True,
- backup=False,
- yes=True,
- branch=None,
- force=False,
- force_venv=False,
- )
- defaults.update(overrides)
- return SimpleNamespace(**defaults)
-
-
-def _run_guard(detect_side_effect, orphan_return):
- """Drive _cmd_update_impl to the venv-holder guard (harness mirrors
- test_update_venv_health.py)."""
-
- class _PastGuard(Exception):
- pass
-
- class _RootSentinel:
- def __truediv__(self, _other):
- raise _PastGuard
-
- killed: list[list[int]] = []
-
- with patch.object(cli_main, "_is_windows", return_value=True), patch.object(
- cli_main, "_venv_scripts_dir", return_value=None
- ), patch.object(cli_main, "_run_pre_update_backup"), patch.object(
- cli_main, "_pause_windows_gateways_for_update", return_value=None
- ), patch.object(
- cli_main, "_resume_windows_gateways_after_update"
- ), patch.object(
- cli_main, "_detect_venv_python_processes", side_effect=detect_side_effect
- ), patch.object(
- cli_main, "_leftover_pausable_gateway_pids", return_value=None
- ), patch.object(
- cli_main, "_orphaned_desktop_backend_pids", return_value=orphan_return
- ), patch.object(
- cli_main, "_stop_process_trees", side_effect=killed.append
- ), patch.object(
- cli_main, "PROJECT_ROOT", _RootSentinel()
- ), patch(
- "time.sleep"
- ):
- try:
- update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)
- except _PastGuard:
- return "past_guard", killed
- except SystemExit as exc:
- return f"exit_{exc.code}", killed
- return "returned", killed
-
-
-def test_guard_reaps_orphan_backend_and_proceeds():
- holders = _holders()
- # 1st scan: backend present; 2nd (post-reap) scan: clear.
- result, killed = _run_guard(
- detect_side_effect=[holders, []], orphan_return=[200]
- )
- assert result == "past_guard"
- assert killed == [[200]]
-
-
-def test_guard_still_refuses_when_not_orphaned():
- holders = _holders()
- result, killed = _run_guard(
- detect_side_effect=[holders, holders], orphan_return=None
- )
- assert result == "exit_2"
- assert killed == []
-
-
-def test_guard_refuses_when_reap_does_not_clear_holders():
- holders = _holders()
- # Reap runs but a holder survives (unkillable child) → refuse.
- result, killed = _run_guard(
- detect_side_effect=[holders, holders], orphan_return=[200]
- )
- assert result == "exit_2"
- assert killed == [[200]]
diff --git a/tests/hermes_cli/test_update_parked_branch_guard.py b/tests/hermes_cli/test_update_parked_branch_guard.py
index 84b2f2e8174..acdf6139086 100644
--- a/tests/hermes_cli/test_update_parked_branch_guard.py
+++ b/tests/hermes_cli/test_update_parked_branch_guard.py
@@ -179,51 +179,11 @@ def test_missing_origin_ref_is_unverifiable(repo_pair):
# Skip warning content
# ---------------------------------------------------------------------------
-def test_skip_warning_names_branch_behind_count_and_commands(repo_pair, capsys):
- update_cmd._print_parked_branch_skip_warning(
- GIT, repo_pair, "old-feature", "main", "dirty"
- )
- out = capsys.readouterr().out
- assert "CODE UPDATE SKIPPED" in out
- assert "old-feature" in out
- assert "2 commit(s) BEHIND" in out
- assert f"git -C {repo_pair} checkout main && hermes update" in out
-
-
-def test_skip_warning_dirty_reason(repo_pair, capsys):
- update_cmd._print_parked_branch_skip_warning(
- GIT, repo_pair, "old-feature", "main", "dirty"
- )
- out = capsys.readouterr().out
- assert "uncommitted changes" in out
-
-
-def test_kept_notice_names_branch_count_and_recovery(capsys):
- update_cmd._print_parked_branch_kept_notice("old-feature", "main", "3")
- out = capsys.readouterr().out
- assert "parked on 'old-feature'" in out
- assert "3 commit(s) not merged into origin/main" in out
- assert "safe on 'old-feature'" in out
- assert "git checkout old-feature" in out
- assert "CODE UPDATE SKIPPED" not in out
-
# ---------------------------------------------------------------------------
# Summary branch/HEAD visibility
# ---------------------------------------------------------------------------
-def test_branch_head_label_reflects_real_checkout(repo_pair):
- label = update_cmd._branch_head_label(GIT, repo_pair)
- short = _git(repo_pair, "rev-parse", "--short", "HEAD").stdout.strip()
- assert label == f"old-feature @ {short}"
-
-
-def test_branch_head_label_detached(repo_pair):
- _git(repo_pair, "checkout", "-q", "--detach")
- label = update_cmd._branch_head_label(GIT, repo_pair)
- assert label is not None
- assert label.startswith("detached @ ")
-
def test_branch_head_suffix_empty_on_non_repo(tmp_path):
assert update_cmd._branch_head_suffix(GIT, tmp_path / "not-a-repo") == ""
@@ -236,7 +196,8 @@ def test_print_update_completion_carries_branch_and_sha(
update_cmd._print_update_completion("✓ Update complete!")
out = capsys.readouterr().out
short = _git(repo_pair, "rev-parse", "--short", "HEAD").stdout.strip()
- assert f"✓ Update complete! [old-feature @ {short}]" in out
+ completion = next(line for line in out.splitlines() if "Update complete" in line)
+ assert "old-feature" in completion and short in completion
# ---------------------------------------------------------------------------
@@ -289,9 +250,7 @@ def test_update_skips_and_warns_on_dirty_parked_branch(
assert exc_info.value.code == 1
out = capsys.readouterr().out
- assert "CODE UPDATE SKIPPED" in out
assert "old-feature" in out
- assert "code update SKIPPED" in out
assert "✓ Code updated!" not in out
assert "✓ Update complete!" not in out
# Branch untouched.
@@ -330,10 +289,7 @@ def test_update_switches_unmerged_parked_branch_with_kept_notice(
hermes_main.cmd_update(args)
out = capsys.readouterr().out
- assert "1 commit(s) not merged into origin/main" in out
- assert "safe on 'old-feature'" in out
assert "CODE UPDATE SKIPPED" not in out
- assert "updating it in place" not in out
# Ends on main, fast-forwarded.
assert (
_git(repo_pair, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
@@ -384,7 +340,6 @@ def test_update_updates_unmerged_branch_in_place_when_configured(
hermes_main.cmd_update(args)
out = capsys.readouterr().out
- assert "updating it in place" in out
assert "CODE UPDATE SKIPPED" not in out
# The checkout never moved.
assert (
@@ -442,8 +397,6 @@ def test_switch_branch_flag_overrides_in_place_strategy(
hermes_main.cmd_update(args)
out = capsys.readouterr().out
- assert "1 commit(s) not merged into origin/main" in out
- assert "updating it in place" not in out
assert "CODE UPDATE SKIPPED" not in out
# Checkout moved to the target and picked up its code...
assert (
@@ -458,48 +411,6 @@ def test_switch_branch_flag_overrides_in_place_strategy(
)
-def test_unmerged_branch_still_updates_in_place_without_the_flag(
- repo_pair, monkeypatch, capsys
-):
- """--switch-branch is opt-in: with the in-place strategy configured and
- no flag, the update stays in place."""
- import hermes_cli.config as hermes_config
-
- monkeypatch.setattr(
- hermes_config,
- "load_config",
- lambda: {"updates": {"parked_branch_strategy": "update_in_place"}},
- )
- (repo_pair / "feature.txt").write_text("unmerged work\n")
- _git(repo_pair, "add", "feature.txt")
- _git(repo_pair, "commit", "-qm", "feature work")
- _patch_update_flow(monkeypatch, repo_pair)
-
- class _StopFlow(Exception):
- pass
-
- monkeypatch.setattr(
- hermes_main,
- "_abort_dependency_sync_if_self_locked",
- lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),
- )
- args = SimpleNamespace(
- branch=None, yes=False, force=False, force_venv=False,
- switch_branch=False,
- )
-
- with pytest.raises(_StopFlow):
- hermes_main.cmd_update(args)
-
- out = capsys.readouterr().out
- assert "updating it in place" in out
- assert "--switch-branch" not in out
- assert (
- _git(repo_pair, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
- == "old-feature"
- )
-
-
def test_update_auto_switches_clean_merged_parked_branch(
repo_pair, monkeypatch, capsys
):
@@ -523,9 +434,6 @@ def test_update_auto_switches_clean_merged_parked_branch(
hermes_main.cmd_update(args)
out = capsys.readouterr().out
- assert "parked on 'old-feature'" in out
- assert "fully merged" in out
- assert "switching back to main" in out
assert "CODE UPDATE SKIPPED" not in out
# The checkout ends up ON main, fast-forwarded to origin/main.
assert (
@@ -537,9 +445,7 @@ def test_update_auto_switches_clean_merged_parked_branch(
assert head == remote
-def test_update_up_to_date_path_does_not_repark_merged_branch(
- tmp_path, monkeypatch, capsys
-):
+def test_update_up_to_date_path_does_not_repark_merged_branch(tmp_path, monkeypatch):
"""commit_count == 0 path: before this fix, the updater switched BACK to
the parked feature branch after checking main ("Restore stash and switch
back to original branch") — silently re-parking the checkout so every
@@ -578,8 +484,6 @@ def test_update_up_to_date_path_does_not_repark_merged_branch(
with pytest.raises(_StopFlow):
hermes_main.cmd_update(args)
- out = capsys.readouterr().out
- assert "switched back to main" in out
# The regression: old code ran `git checkout old-feature` here.
assert (
_git(clone, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() == "main"
diff --git a/tests/hermes_cli/test_update_post_pull_syntax_guard.py b/tests/hermes_cli/test_update_post_pull_syntax_guard.py
index a430abc9158..e6ae5fa0433 100644
--- a/tests/hermes_cli/test_update_post_pull_syntax_guard.py
+++ b/tests/hermes_cli/test_update_post_pull_syntax_guard.py
@@ -14,58 +14,13 @@ command afterward.
from __future__ import annotations
-from pathlib import Path
-from types import SimpleNamespace
-
-from hermes_cli import main as hermes_main
from hermes_cli import update_cmd
-# ---------------------------------------------------------------------------
-# _capture_head_sha
-# ---------------------------------------------------------------------------
-
-def test_capture_head_sha_returns_stripped_sha(monkeypatch, tmp_path):
- def fake_run(cmd, **kwargs):
- assert cmd[-2:] == ["rev-parse", "HEAD"]
- return SimpleNamespace(stdout="deadbeefcafe\n", returncode=0)
-
- monkeypatch.setattr(hermes_main.subprocess, "run", fake_run)
-
- assert update_cmd._capture_head_sha(["git"], tmp_path) == "deadbeefcafe"
-
-
# ---------------------------------------------------------------------------
# _validate_critical_files_syntax
# ---------------------------------------------------------------------------
-def _populate_critical_tree(root: Path, *, broken_file: str | None = None) -> None:
- """Create stub files for every entry in ``_UPDATE_CRITICAL_FILES``.
-
- If ``broken_file`` is given, that file gets orphan merge-conflict markers
- (the exact failure mode from PR #28452).
- """
- broken_payload = (
- "x = {\n"
- ' "a": 1,\n'
- "<<<<<<< HEAD\n"
- ' "b": 2,\n'
- "=======\n"
- ' "c": 0b6d673e7,\n' # invalid binary literal — the actual error users saw
- ">>>>>>> 0b6d673e7\n"
- "}\n"
- )
- for relpath in update_cmd._UPDATE_CRITICAL_FILES:
- path = root / relpath
- path.parent.mkdir(parents=True, exist_ok=True)
- if relpath == broken_file:
- path.write_text(broken_payload)
- else:
- path.write_text("# stub\n")
-
-
-
-
def test_validate_critical_files_syntax_tolerates_missing_files(tmp_path):
"""A refactor may legitimately remove one of the critical files — the
guard should skip missing files, not falsely flag the install as broken."""
@@ -82,12 +37,3 @@ def test_validate_critical_files_syntax_tolerates_missing_files(tmp_path):
assert ok is True
assert failing_path is None
assert error is None
-
-
-# ---------------------------------------------------------------------------
-# Repo invariant — the production tree itself must always pass the guard.
-# This catches the case where ``main`` ships a syntax error before the next
-# release; if a future ``hermes update`` would brick users, this test fails
-# in CI first.
-# ---------------------------------------------------------------------------
-
diff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.py
index 664341c9408..3c2835b64f3 100644
--- a/tests/hermes_cli/test_update_receipt.py
+++ b/tests/hermes_cli/test_update_receipt.py
@@ -12,7 +12,6 @@ Covers:
import json
import os
import sys
-from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -113,18 +112,6 @@ class TestReceiptLifecycle:
assert latest is not None
assert latest["outcome"] == "partial"
- def test_phase_error_shape(self, receipt_home):
- ur.begin_update_receipt()
- ur.record_gateway_restart(
- restarted_services=[],
- incomplete=True,
- phase_error="boom: module vanished mid-pull",
- )
- path = _finalize("partial")
- payload = json.loads(path.read_text(encoding="utf-8"))
- gr = payload["gateway_restart"]
- assert gr["incomplete"] is True
- assert "boom" in gr["phase_error"]
def test_record_without_begin_is_noop(self, receipt_home):
# No begin — nothing should raise, nothing should be written.
@@ -133,11 +120,6 @@ class TestReceiptLifecycle:
ur.record_gateway_restart(restarted_services=[])
assert _finalize("success") is None
- def test_finalize_clears_current(self, receipt_home):
- ur.begin_update_receipt()
- assert ur._current is not None
- _finalize("success")
- assert ur._current is None
def test_pruning_keeps_recent(self, receipt_home, monkeypatch):
monkeypatch.setattr(ur, "_RECEIPT_KEEP", 3)
@@ -157,9 +139,6 @@ class TestReceiptLifecycle:
"update_20260105_000000_1.json",
]
- def test_read_latest_receipt_missing(self, receipt_home):
- assert ur.read_latest_receipt() is None
-
class TestCommandBoundaryFinalization:
"""Receipt lifetime is owned by the update-command boundary (#91283 review).
@@ -420,7 +399,7 @@ class TestFleetClassification:
assert fleet[0]["code_sha"] is None
assert fleet[0]["code_version"] is None
- def test_matrix_returns_true_only_on_stale(self, capsys):
+ def test_matrix_returns_true_only_on_stale(self):
assert ur.print_fleet_version_matrix([]) is False
ok = ur.print_fleet_version_matrix(
[{"profile": "default", "pid": 1, "code_sha": "a" * 40, "state": "current"}]
@@ -433,27 +412,12 @@ class TestFleetClassification:
]
)
assert stale is True
- out = capsys.readouterr().out
- assert "STALE" in out
- assert "hermes -p <profile> gateway restart" in out
- def test_unknown_does_not_fail_update(self, capsys):
+ def test_unknown_does_not_fail_update(self):
ok = ur.print_fleet_version_matrix(
[{"profile": "default", "pid": 1, "code_sha": None, "state": "unknown"}]
)
assert ok is False
- assert "version unknown" in capsys.readouterr().out
-
- def test_identity_pending_row_gets_restart_aware_copy(self, capsys):
- """#112634: a gateway this update relaunched that has not stamped yet must not be told to
- restart — it was just restarted on the new code. Still non-fatal."""
- ok = ur.print_fleet_version_matrix(
- [{"profile": "default", "pid": 34516, "code_sha": None, "state": "unknown", "identity_pending": True}]
- )
- assert ok is False
- out = capsys.readouterr().out
- assert "code identity not published yet" in out and "hermes gateway status" in out
- assert "predates version stamping" not in out
class TestGatewayStatusStamping:
@@ -483,15 +447,6 @@ class TestGatewayStatusStamping:
class TestCodeIdentity:
- def test_get_code_identity_shape(self):
- from hermes_cli.build_info import get_code_identity
-
- identity = get_code_identity(refresh=True)
- assert set(identity) == {"sha", "short_sha", "version", "source"}
- # Running from a git checkout in CI/dev: sha resolves via git.
- if identity["sha"]:
- assert identity["short_sha"] == identity["sha"][:8]
- assert identity["source"] in ("git", "build-file")
def test_get_code_identity_cached(self):
from hermes_cli.build_info import get_code_identity
diff --git a/tests/hermes_cli/test_update_restart_recovery.py b/tests/hermes_cli/test_update_restart_recovery.py
index 19a6c9f2319..e32f4b66b7b 100644
--- a/tests/hermes_cli/test_update_restart_recovery.py
+++ b/tests/hermes_cli/test_update_restart_recovery.py
@@ -92,9 +92,6 @@ def test_abort_recovery_hands_managed_profiles_to_a_fresh_process(monkeypatch):
# Serve units travel in the same payload so one fresh child covers both
# runtime families (#92145).
assert set(payload["serve_units"]) == {"recover", "skip"}
- assert kwargs["text"] is True
- assert kwargs["capture_output"] is True
- assert kwargs["check"] is False
assert kwargs["env"]["HERMES_UPDATE_RESTART_RECOVERY"] == "1"
@@ -384,23 +381,6 @@ def test_recovery_payload_rejects_malformed_supervisors_map():
raise AssertionError("malformed supervisors map must be rejected")
-def test_recovery_module_empty_payload_is_a_real_clean_process():
- result = subprocess.run(
- [sys.executable, "-m", "hermes_cli.update_restart_recovery", "--stdin"],
- input=json.dumps({"profiles": []}),
- capture_output=True,
- text=True,
- check=False,
- )
-
- assert result.returncode == 0
- assert json.loads(result.stdout) == {
- "failed": [],
- "relaunch_attempted": [],
- "verified": [],
- "covered": {},
- "serve_units": {"verified": [], "failed": []},
- }
def test_recovery_module_end_to_end_in_a_real_fresh_process(tmp_path):
diff --git a/tests/hermes_cli/test_update_secret_import_lock.py b/tests/hermes_cli/test_update_secret_import_lock.py
index 5bcf976b123..d6875c45566 100644
--- a/tests/hermes_cli/test_update_secret_import_lock.py
+++ b/tests/hermes_cli/test_update_secret_import_lock.py
@@ -65,13 +65,6 @@ secrets:
return set(json.loads(line.removeprefix("LOADED_MODULES=")))
-def test_update_startup_does_not_import_bitwarden_or_cryptography(tmp_path):
- loaded = _probe_startup_modules(tmp_path, ["hermes", "update", "--check"])
-
- assert "agent.secret_sources.bitwarden" not in loaded
- assert not any(
- name == "cryptography" or name.startswith("cryptography.") for name in loaded
- )
def test_complete_update_dispatch_does_not_import_cryptography(tmp_path):
@@ -82,6 +75,7 @@ def test_complete_update_dispatch_does_not_import_cryptography(tmp_path):
run_main=True,
)
+ assert "agent.secret_sources.bitwarden" not in loaded
assert not any(
name == "cryptography" or name.startswith("cryptography.") for name in loaded
)
diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.py
index 82be3d45cf6..95f0e18a740 100644
--- a/tests/hermes_cli/test_update_self_lock.py
+++ b/tests/hermes_cli/test_update_self_lock.py
@@ -32,7 +32,6 @@ from unittest.mock import MagicMock, patch
import pytest
import hermes_cli.main as cli_main
-import hermes_cli.update_cmd as update_cmd
from hermes_cli import _early_recovery
ROOT = Path(__file__).resolve().parents[2]
@@ -109,22 +108,22 @@ class TestDependencySyncWouldRewrite:
# ---------------------------------------------------------------------------
[email protected](cli_main, "_is_windows", return_value=False)
-def test_self_lock_detection_is_noop_off_windows(_winp):
+def test_self_lock_detection_is_noop_off_windows():
with patch.dict(sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}):
assert cli_main._detect_self_loaded_native_modules() == []
[email protected](cli_main, "_is_windows", return_value=True)
-def test_loaded_module_with_pending_version_change_is_flagged(_winp):
+def test_loaded_module_with_pending_version_change_is_flagged():
with patch.dict(
sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}
), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):
assert "cryptography (_rust.pyd)" in cli_main._detect_self_loaded_native_modules()
[email protected](cli_main, "_is_windows", return_value=True)
-def test_loaded_module_already_at_target_version_is_not_flagged(_winp):
+def test_loaded_module_already_at_target_version_is_not_flagged():
"""#86735 core fix: loaded-but-not-changing must NOT trip the deferral.
Installed cryptography already satisfies the on-disk pins → the sync
@@ -136,8 +135,8 @@ def test_loaded_module_already_at_target_version_is_not_flagged(_winp):
assert cli_main._detect_self_loaded_native_modules() == []
[email protected](cli_main, "_is_windows", return_value=True)
-def test_unknown_rewrite_risk_fails_open(_winp):
+def test_unknown_rewrite_risk_fails_open():
"""Uncertain rewrite risk must NOT defer (None → proceed).
PyYAML is loaded by every CLI process; deferring on an unparseable
@@ -151,16 +150,6 @@ def test_unknown_rewrite_risk_fails_open(_winp):
assert cli_main._detect_self_loaded_native_modules() == []
[email protected](cli_main, "_is_windows", return_value=True)
-def test_self_lock_detection_clean_when_rust_not_loaded(_winp):
- sys.modules.pop("cryptography.hazmat.bindings._rust", None)
- with patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):
- assert (
- "cryptography (_rust.pyd)"
- not in cli_main._detect_self_loaded_native_modules()
- )
-
-
def test_recovered_update_retry_builds_parser_without_native_secret_modules(
monkeypatch,
):
@@ -206,9 +195,7 @@ def test_abort_helper_defers_and_exits_2(capsys):
# Deferral contract: marker dropped so the next fresh launch completes
# the dependency install (the code swap has already happened by now).
assert marker_writes == ["written"]
- out = capsys.readouterr().out
- assert "cryptography (_rust.pyd)" in out
- assert "deferred" in out
+ assert "cryptography (_rust.pyd)" in capsys.readouterr().out
def test_abort_helper_resumes_paused_gateways_before_exit():
@@ -232,39 +219,6 @@ def test_abort_helper_resumes_paused_gateways_before_exit():
# ---------------------------------------------------------------------------
-def test_pre_fetch_flow_has_no_self_lock_preflight():
- """#86780 regression: a loaded native module must not block the git fetch.
-
- The old preflight sat between the venv-holder sweep and the fetch, so a
- universally-loaded module (bitwarden's module-level cryptography import)
- deferred every update before any code was pulled — the Windows infinite
- update loop. The deferral now lives at the dependency-sync boundaries
- only; the stretch of _cmd_update_impl between the venv-holder sweep and
- the fetch must not consult the detector at all.
- """
- import inspect
-
- src = inspect.getsource(update_cmd._cmd_update_impl)
- fetch_idx = src.index("Fetching updates")
- pre_fetch = src[:fetch_idx]
- assert "_detect_self_loaded_native_modules()" not in pre_fetch
- assert "_m()._abort_dependency_sync_if_self_locked" not in pre_fetch
- # ... and it must still guard the dependency sync after the code swap
- # (the sync itself lives in _sync_python_dependencies_after_pull).
- post_fetch = src[fetch_idx:] + inspect.getsource(update_cmd._finish_pulled_update)
- assert "_sync_python_dependencies_after_pull(" in post_fetch
- sync_src = inspect.getsource(update_cmd._sync_python_dependencies_after_pull)
- assert "_m()._abort_dependency_sync_if_self_locked" in sync_src
-
-
-def test_zip_update_guards_dependency_sync():
- import inspect
-
- src = inspect.getsource(update_cmd._finish_zip_update)
- swap_idx = src.index("Updating Python dependencies")
- assert "_abort_dependency_sync_if_self_locked" in src[:swap_idx]
-
-
# ---------------------------------------------------------------------------
# Import hygiene: the update entrypoint must not load cryptography at all
# ---------------------------------------------------------------------------
@@ -311,25 +265,3 @@ class TestUpdateEntrypointImportHygiene:
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_serve_generation_recovery.py b/tests/hermes_cli/test_update_serve_generation_recovery.py
index f7f242d5f6d..4cea3b1d0bf 100644
--- a/tests/hermes_cli/test_update_serve_generation_recovery.py
+++ b/tests/hermes_cli/test_update_serve_generation_recovery.py
@@ -238,18 +238,6 @@ def test_restarted_serve_leaves_no_survivor(monkeypatch):
)
-def test_gateway_runtimes_are_not_counted_as_serve_survivors(monkeypatch):
- monkeypatch.setattr(
- _identity_module(),
- "ledger_entries",
- lambda *a, **k: [{"pid": 4242, "purpose": "gateway"}],
- )
- assert (
- update_cmd._surviving_pre_update_serve_runtimes(
- _plan(_runtime("gateway", "default", "systemd", 4242))
- )
- == []
- )
def test_dashboard_survivors_count_too(monkeypatch):
@@ -495,17 +483,6 @@ def test_no_systemctl_means_no_serve_pass(monkeypatch):
}
-def test_non_linux_hosts_do_not_run_the_serve_pass(monkeypatch):
- monkeypatch.setattr(recovery.sys, "platform", "win32")
- monkeypatch.setattr(recovery.shutil, "which", lambda name: "systemctl")
-
- def unreachable(*a, **k):
- raise AssertionError("serve unit pass ran off Linux")
-
- assert recovery.restart_serve_units(run=unreachable) == {
- "verified": [],
- "failed": [],
- }
def test_active_unit_with_no_readable_main_pid_is_failed(linux_systemctl):
@@ -674,57 +651,8 @@ def test_serve_only_fleet_still_spawns_the_recovery_child(monkeypatch):
assert result["serve_units"] == {"verified": ["hermes-serve"], "failed": []}
-def test_child_timeout_budget_covers_the_serve_pass(monkeypatch):
- """A serve-only recovery must not be killed before its settle window."""
- monkeypatch.setattr(abort_recovery, "_serve_unit_recovery_available", lambda: True)
- captured = {}
- def fake_run(argv, **kwargs):
- captured["timeout"] = kwargs["timeout"]
- return _Completed(
- 0,
- stdout=json.dumps(
- {
- "verified": [],
- "relaunch_attempted": [],
- "failed": [],
- "serve_units": {"verified": [], "failed": []},
- }
- ),
- )
-
- monkeypatch.setattr(abort_recovery.subprocess, "run", fake_run)
- update_cmd._recover_gateway_restart_after_abort(
- _plan(_runtime("serve", "default", "manual-serve", 4242)),
- gateway_mode=False,
- )
- assert captured["timeout"] >= 180
-
-
-def test_verified_serve_units_do_not_enter_gateway_restart_vocabulary(monkeypatch):
- """Serve coverage must not silently widen the gateway fleet-probe gate."""
- monkeypatch.setattr(abort_recovery, "_serve_unit_recovery_available", lambda: True)
-
- def fake_run(argv, **kwargs):
- return _Completed(
- 0,
- stdout=json.dumps(
- {
- "verified": ["default"],
- "relaunch_attempted": [],
- "failed": [],
- "serve_units": {"verified": ["hermes-serve"], "failed": []},
- }
- ),
- )
- monkeypatch.setattr(abort_recovery.subprocess, "run", fake_run)
- result = update_cmd._recover_gateway_restart_after_abort(
- _plan(_runtime("gateway", "default", "systemd", 111)),
- gateway_mode=False,
- )
- assert result["verified"] == ["default"]
- assert "hermes-serve" not in result["verified"]
def test_no_serve_authority_and_no_gateway_profile_spawns_nothing(monkeypatch):
@@ -906,21 +834,6 @@ def test_serve_coverage_reaches_the_persisted_receipt(tmp_path, monkeypatch):
# ---------------------------------------------------------------------------
-def test_stale_serve_warning_names_the_process_and_the_fix(capsys):
- update_cmd._warn_stale_serve_runtimes(
- [
- {
- "pid": 4242,
- "kind": "serve",
- "profile": "default",
- "supervisor": "manual-serve",
- }
- ]
- )
- out = capsys.readouterr().out
- assert "4242" in out
- assert "serve" in out
- assert "systemctl --user restart hermes-serve.service" not in out
def test_no_survivors_prints_nothing(capsys):
@@ -963,33 +876,6 @@ def _stub_dashboard_helpers(monkeypatch, **helpers):
monkeypatch.setattr(main_dashboard, name, value)
-def _dashboard_main_stub(scan_calls, *, restart_result=True):
- return dict(
- _DASHBOARD_SYSTEMD_UNIT="hermes-dashboard.service",
- _restart_managed_dashboard_service=lambda reason, *a, **k: restart_result,
- _find_stale_dashboard_pids=lambda **kwargs: scan_calls.append(kwargs) or [],
- )
-
-
-def test_managed_dashboard_restart_still_scans_for_serve_backends(monkeypatch):
- """A restarted dashboard unit may not end the pass (#92145).
-
- The reporter's host runs ``hermes-dashboard.service`` AND
- ``hermes-serve.service``. Returning as soon as the dashboard unit was
- restarted meant the serve backend hosting ``tui_gateway`` was never even
- looked for, so it kept serving the pre-update generation.
- """
- from hermes_cli import dashboard_procs
-
- scan_calls: list[dict] = []
- _stub_dashboard_helpers(monkeypatch, **_dashboard_main_stub(scan_calls))
- monkeypatch.setattr(dashboard_procs, "_lock_owned_serve_pids", lambda: set())
-
- dashboard_procs._kill_stale_dashboard_processes(restart_managed=True)
-
- assert scan_calls, "serve/dashboard scan never ran after the dashboard restart"
-
-
def test_restarted_dashboard_unit_is_not_killed_by_the_continued_scan(monkeypatch):
"""Continuing the scan must not undo the restart it just performed."""
from hermes_cli import dashboard_procs
@@ -1114,31 +1000,8 @@ def test_settled_system_scope_does_not_suppress_the_stale_user_scope(
assert out == {"verified": ["user/hermes-serve"], "failed": []}
-def test_one_authorized_scope_never_mutates_the_same_name_in_the_other(
- linux_systemctl,
-):
- """Name equality is not identity: no systemctl verb at all may reach the
- scope that was already settled."""
- run, calls = _dual_scope_systemctl()
- recovery.restart_serve_units(
- skip_units=[{"scope": "user", "unit": "hermes-serve.service"}],
- run=run,
- sleep=lambda _: None,
- )
- user_verbs = [
- argv for scope, argv in calls if scope == "user" and "list-units" not in argv
- ]
- assert user_verbs == [], user_verbs
-def test_each_scope_reports_its_own_outcome(linux_systemctl):
- """One scope failing must not be reported as the other's failure."""
- run, _ = _dual_scope_systemctl(settle=("user",))
- out = recovery.restart_serve_units(run=run, sleep=lambda _: None)
- assert out == {
- "verified": ["user/hermes-serve"],
- "failed": ["system/hermes-serve"],
- }
def test_legacy_unqualified_skip_is_honoured_in_both_scopes(linux_systemctl):
diff --git a/tests/hermes_cli/test_update_shim_fail_closed.py b/tests/hermes_cli/test_update_shim_fail_closed.py
index 5f376820d50..ad88119ed0a 100644
--- a/tests/hermes_cli/test_update_shim_fail_closed.py
+++ b/tests/hermes_cli/test_update_shim_fail_closed.py
@@ -17,7 +17,6 @@ Contract pinned here:
"""
import os
-import sys
from pathlib import Path
from unittest import mock
@@ -38,17 +37,12 @@ def _make_shims(scripts_dir: Path, names=("hermes", "hermes-gateway")) -> list[P
return shims
-def windows(monkeypatch):
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(ir, "_is_windows", lambda: True)
-
-
# ---------------------------------------------------------------------------
# main.py: _run_quarantined_install strict mode
# ---------------------------------------------------------------------------
-def test_strict_quarantine_refuses_before_install(windows, tmp_path, monkeypatch):
+def test_strict_quarantine_refuses_before_install(tmp_path, monkeypatch):
scripts = tmp_path / "venv" / "Scripts"
shims = _make_shims(scripts)
# hermes.exe cannot be renamed; hermes-gateway.exe can
@@ -83,7 +77,8 @@ def test_strict_quarantine_refuses_before_install(windows, tmp_path, monkeypatch
assert not list(scripts.glob("hermes-gateway.exe.old.*"))
-def test_non_strict_keeps_warn_and_try(windows, tmp_path, monkeypatch):
+def test_non_strict_keeps_warn_and_try(tmp_path, monkeypatch):
scripts = tmp_path / "venv" / "Scripts"
shims = _make_shims(scripts, names=("hermes",))
monkeypatch.setattr(
@@ -104,7 +99,8 @@ def test_non_strict_keeps_warn_and_try(windows, tmp_path, monkeypatch):
assert install_ran == [["fake"]]
-def test_strict_all_renames_ok_runs_install(windows, tmp_path, monkeypatch):
+def test_strict_all_renames_ok_runs_install(tmp_path, monkeypatch):
scripts = tmp_path / "venv" / "Scripts"
shims = _make_shims(scripts)
monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: shims)
@@ -120,33 +116,14 @@ def test_strict_all_renames_ok_runs_install(windows, tmp_path, monkeypatch):
assert install_ran == [["fake"]]
-def test_update_sync_installs_are_strict(windows, tmp_path, monkeypatch):
- """_install_python_dependencies_with_optional_fallback must pass
- strict_quarantine=True — the #87331 site."""
- seen = {}
-
- def spy(cmd, *, env=None, scripts_dir=None, strict_quarantine=False):
- seen["strict"] = strict_quarantine
-
- monkeypatch.setattr(main_install_repair, "_run_quarantined_install", spy)
- monkeypatch.setattr(main_install_repair, "_venv_scripts_dir", lambda: tmp_path)
- monkeypatch.setattr(
- main_install_repair, "_verify_console_scripts_installed",
- lambda prefix, env=None: None,
- )
- monkeypatch.setattr(
- main_install_repair, "_verify_core_dependencies_installed",
- lambda prefix, env=None, group="all": None,
- )
- main_install_repair._install_python_dependencies_with_optional_fallback(["uv", "pip"])
- assert seen["strict"] is True
# ---------------------------------------------------------------------------
# _install_repair.py: recovery installer is strict unconditionally
# ---------------------------------------------------------------------------
-def test_recovery_install_cmd_fail_closed(windows, tmp_path, monkeypatch):
+def test_recovery_install_cmd_fail_closed(tmp_path, monkeypatch):
root = tmp_path
scripts = root / "venv" / "Scripts"
_make_shims(scripts, names=("hermes",))
@@ -167,7 +144,8 @@ def test_recovery_install_cmd_fail_closed(windows, tmp_path, monkeypatch):
assert run_calls == [] # contended venv never mutated
-def test_recovery_install_cmd_ok_when_uncontended(windows, tmp_path, monkeypatch):
+def test_recovery_install_cmd_ok_when_uncontended(tmp_path, monkeypatch):
root = tmp_path
scripts = root / "venv" / "Scripts"
_make_shims(scripts, names=("hermes",))
@@ -196,9 +174,7 @@ def test_refusal_writes_marker_and_exits_2(monkeypatch, capsys):
update_cmd._refuse_update_for_contended_shims(exc)
assert exit_info.value.code == 2
assert wrote == [1]
- out = capsys.readouterr().out
- assert "hermes.exe" in out
- assert "deferred" in out
+ assert "hermes.exe" in capsys.readouterr().out
def test_shim_error_type_resolves_real_class():
diff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.py
index 19ed523f911..c0ad4ac44fe 100644
--- a/tests/hermes_cli/test_update_shim_self_lock.py
+++ b/tests/hermes_cli/test_update_shim_self_lock.py
@@ -1,287 +1,15 @@
-"""The Windows console-shim update self-lock (#88838, #89599, #86093).
+"""Pending-rename filter for the Windows console-shim update self-lock (#88838, #89599, #86093).
-``venv\\Scripts\\hermes.exe`` is a launcher that runs the interpreter with the
-shim itself as its script, keeping the file open without FILE_SHARE_DELETE for
-the whole command. An update started that way must therefore replace a file it
-is holding, which Windows refuses — so the DEPENDENCY SYNC re-runs itself under
-``venv\\Scripts\\python.exe``.
-
-The hand-off sits at the sync boundary, not at the top of ``hermes update``:
-everything before it (the fetch, the stash question, the branch switch) runs
-in the user's own console, and an up-to-date run that never syncs never hands
-off at all.
-
-``_is_windows`` is patched so these paths are exercised on any host.
+``_filter_pending_shim_renames`` is a pure function over registry
+``PendingFileRenameOperations`` entries, so it runs on any host.
"""
from __future__ import annotations
-import os
-import sys
-import types
from pathlib import Path
-import pytest
-
-from hermes_cli import main as cli_main
-from hermes_cli import update_cmd
from hermes_cli import main_install_repair
-SHIM_NAMES = ["hermes.exe", "hermes-agent.exe", "hermes-acp.exe", "hermes-gateway.exe"]
-
-
-def venv(tmp_path, monkeypatch):
- """A Windows-shaped project venv with a python.exe, wired into main."""
- scripts = tmp_path / "venv" / "Scripts"
- scripts.mkdir(parents=True)
- (scripts / "python.exe").write_bytes(b"")
- # update_cmd reads these off hermes_cli.main (frozen ``_m()`` surface); the
- # install-repair helpers read their own module globals — patch both.
- for target in (cli_main, main_install_repair):
- monkeypatch.setattr(target, "_is_windows", lambda: True)
- monkeypatch.setattr(target, "_venv_scripts_dir", lambda: scripts)
- monkeypatch.setattr(sys, "argv", ["hermes", "update"])
- monkeypatch.delenv(cli_main._UPDATE_REEXEC_ENV, raising=False)
- _fake_psutil(monkeypatch, [])
- return scripts
-
-
-def _fake_psutil(monkeypatch, ancestor_exes: list[str]):
- """Stand in for psutil with a fixed self+ancestor executable chain."""
-
- class _Proc:
- def __init__(self, exe=None, pid=os.getpid()):
- self._exe, self.pid = exe, pid
-
- def exe(self):
- if self._exe is None:
- raise OSError("exe unavailable")
- return self._exe
-
- def parents(self):
- return [_Proc(exe, 1000 + i) for i, exe in enumerate(ancestor_exes)]
-
- monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(Process=_Proc))
-
-
-def _capture_popen(monkeypatch, raises: Exception | None = None):
- calls = []
-
- def fake_popen(cmd, env=None, **kwargs):
- if raises is not None:
- raise raises
- calls.append((list(cmd), dict(env or {}), kwargs))
- return object()
-
- monkeypatch.setattr(cli_main.subprocess, "Popen", fake_popen)
- return calls
-
-
-# ---------------------------------------------------------------------------
-# Shim detection
-# ---------------------------------------------------------------------------
-
-
[email protected]("shim_name", SHIM_NAMES)
-def test_detects_shim_as_argv0(venv, monkeypatch, shim_name):
- monkeypatch.setattr(sys, "argv", [str(venv / shim_name), "update"])
- assert main_install_repair._windows_shim_in_process_chain() == venv / shim_name
-
-
-def test_detects_shim_from_zipapp_main_py(venv, monkeypatch):
- """runpy/zipapp launches put ``<shim>\\__main__.py`` in argv[0]."""
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe" / "__main__.py")])
- assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"
-
-
-def test_detects_shim_from_main_module_spec_origin(venv, monkeypatch):
- fake_main = types.SimpleNamespace(
- __file__=None,
- __spec__=types.SimpleNamespace(origin=str(venv / "hermes.exe")),
- )
- monkeypatch.setitem(sys.modules, "__main__", fake_main)
- assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"
-
-
-def test_detects_shim_in_ancestor_chain(venv, monkeypatch):
- """The launcher is usually a separate parent process, not argv[0]."""
- _fake_psutil(monkeypatch, [str(venv / "hermes.exe")])
- assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"
- # ...and it is that launcher's pid, not ours, a detached child must outwait (#101600).
- assert main_install_repair._windows_shim_holder_pid() == 1000
-
-
-def test_ignores_hermes_exe_outside_the_project_venv(venv, monkeypatch, tmp_path):
- """A shim from some other install must never trigger a re-exec."""
- other = tmp_path / "other" / "Scripts"
- other.mkdir(parents=True)
- monkeypatch.setattr(sys, "argv", [str(other / "hermes.exe"), "update"])
- _fake_psutil(monkeypatch, [str(other / "hermes.exe")])
- assert main_install_repair._windows_shim_in_process_chain() is None
-
-
-def test_no_shim_off_windows(venv, monkeypatch):
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: False)
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- assert main_install_repair._windows_shim_in_process_chain() is None
-
-
-def test_no_shim_without_a_venv(venv, monkeypatch):
- monkeypatch.setattr(main_install_repair, "_venv_scripts_dir", lambda: None)
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- assert main_install_repair._windows_shim_in_process_chain() is None
-
-
-# ---------------------------------------------------------------------------
-# Re-exec hand-off
-# ---------------------------------------------------------------------------
-
-
-def test_reexec_runs_same_args_under_venv_python(venv, monkeypatch, capsys):
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update", "--yes"])
- calls = _capture_popen(monkeypatch)
- token = {"resume_needed": True, "profiles": {"default": 4}, "unmapped": []}
-
- assert cli_main._reexec_dependency_sync_off_windows_shim(token) is True
- cmd, env, kwargs = calls[0]
- assert cmd == [
- str(venv / "python.exe"), "-m", "hermes_cli.main", "update", "--yes",
- ]
- assert env[cli_main._UPDATE_REEXEC_ENV] == "1"
- assert "under the venv Python" in capsys.readouterr().out
- # #101600: the child waits for THIS pid and resumes exactly the paused fleet; the parent's
- # copy is disarmed so it exits instead of relaunching gateways while it still holds the shim.
- from hermes_cli import update_handoff
- assert env[update_handoff.SHIM_PARENT_PID_ENV] == str(os.getpid())
- assert token["resume_needed"] is False
- monkeypatch.setenv(update_handoff.GATEWAY_RESUME_ENV, env[update_handoff.GATEWAY_RESUME_ENV])
- assert update_handoff.adopt_handed_off_gateway_resume() == {
- "resume_needed": True, "profiles": {"default": 4}, "unmapped": []}
- assert update_handoff.GATEWAY_RESUME_ENV not in os.environ
-
-
-def test_reexec_child_runs_unattended(venv, monkeypatch):
- """The parent exits, so a prompt in the child could never be answered."""
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- calls = _capture_popen(monkeypatch)
-
- assert cli_main._reexec_dependency_sync_off_windows_shim() is True
- assert calls[0][2]["stdin"] is cli_main.subprocess.DEVNULL
-
-
-def test_reexec_does_not_recurse(venv, monkeypatch):
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- monkeypatch.setenv(cli_main._UPDATE_REEXEC_ENV, "1")
- calls = _capture_popen(monkeypatch)
-
- assert cli_main._reexec_dependency_sync_off_windows_shim() is False
- assert calls == []
-
-
-def test_reexec_skipped_when_not_launched_from_a_shim(venv, monkeypatch):
- calls = _capture_popen(monkeypatch)
- assert cli_main._reexec_dependency_sync_off_windows_shim() is False
- assert calls == []
-
-
-def test_reexec_falls_through_when_venv_python_is_missing(venv, monkeypatch, capsys):
- (venv / "python.exe").unlink()
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
-
- assert cli_main._reexec_dependency_sync_off_windows_shim() is False
- assert "-m hermes_cli.main update" not in capsys.readouterr().out
-
-
-def test_reexec_falls_through_when_spawn_fails(venv, monkeypatch, capsys):
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- _capture_popen(monkeypatch, raises=OSError("no exec"))
-
- assert cli_main._reexec_dependency_sync_off_windows_shim() is False
- assert "-m hermes_cli.main update" in capsys.readouterr().out
-
-
-# ---------------------------------------------------------------------------
-# Hand-off placement: the sync boundary, not the top of the command
-# ---------------------------------------------------------------------------
-
-
-def test_up_to_date_run_never_hands_off(venv, monkeypatch, capsys):
- """The regression that started this: a no-op update must not detach.
-
- The hand-off used to run before the fetch, so every ``hermes update`` —
- including the ``Already up to date!`` case that never touches the venv —
- spawned a child and returned to the shell, leaving the child printing
- into a console it no longer owned. ``--check`` is the cheapest real run
- that reaches ``cmd_update`` and exits without syncing; nothing may be
- spawned along the way.
- """
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update", "--check"])
- calls = _capture_popen(monkeypatch)
- monkeypatch.setattr(update_cmd, "_cmd_update_check", lambda **kwargs: None)
-
- cli_main.cmd_update(types.SimpleNamespace(check=True, branch=None))
-
- assert calls == [], "an up-to-date run must not spawn a detached child"
-
-
-def test_sync_guard_hands_off_when_only_the_shim_is_held(venv, monkeypatch):
- """No native module mapped, but we ARE the shim: hand off and exit 0 WITHOUT resuming the
- paused fleet here — the child owns the token (#101600)."""
- from hermes_cli import update_cmd
-
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])
- resumed = []
- monkeypatch.setattr(cli_main, "_resume_windows_gateways_after_update", resumed.append)
- calls = _capture_popen(monkeypatch)
-
- with pytest.raises(SystemExit) as excinfo:
- update_cmd._abort_dependency_sync_if_self_locked({"resume_needed": True, "profiles": {}})
-
- assert excinfo.value.code == 0
- assert calls, "expected the dependency sync to be handed to the venv python"
- assert resumed == [], "the shim parent must exit at once, not relaunch gateways"
-
-
-def test_sync_guard_defers_native_lock_before_considering_the_shim(venv, monkeypatch):
- """A mapped .pyd still exits 2 — the marker recovery owns that case."""
- from hermes_cli import update_cmd
-
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- monkeypatch.setattr(
- cli_main, "_detect_self_loaded_native_modules", lambda: ["PyYAML (_yaml.pyd)"]
- )
- monkeypatch.setattr(cli_main, "_defer_update_for_self_lock", lambda loaded: None)
- calls = _capture_popen(monkeypatch)
-
- with pytest.raises(SystemExit) as excinfo:
- update_cmd._abort_dependency_sync_if_self_locked()
-
- assert excinfo.value.code == 2
- assert calls == [], "a native-module deferral must not also spawn a child"
-
-
-def test_sync_guard_is_a_noop_when_nothing_is_held(venv, monkeypatch):
- """Off the shim with nothing mapped, the sync just proceeds in-process."""
- from hermes_cli import update_cmd
-
- monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])
- calls = _capture_popen(monkeypatch)
-
- update_cmd._abort_dependency_sync_if_self_locked()
- assert calls == []
-
-
-# ---------------------------------------------------------------------------
-# Reboot-deferred renames
-# ---------------------------------------------------------------------------
-
-
-def test_reboot_deferred_rename_fallback_is_gone():
- """MOVEFILE_DELAY_UNTIL_REBOOT needed elevation and freed nothing."""
- assert not hasattr(cli_main, "_schedule_replace_on_reboot")
-
def test_pending_rename_filter_drops_only_our_shim_pairs():
shims = [Path(r"C:\hermes\venv\Scripts\hermes.exe")]
@@ -318,11 +46,3 @@ def test_pending_rename_filter_preserves_a_trailing_delete_entry():
# ---------------------------------------------------------------------------
[email protected]("venv_name", ["venv", ".venv"])
-def test_venv_scripts_dir_finds_both_layouts(tmp_path, monkeypatch, venv_name):
- """uv writes .venv; our installers write venv. Both must resolve (#79542)."""
- scripts = tmp_path / venv_name / "Scripts"
- scripts.mkdir(parents=True)
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- 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 4efc2f501cf..fda83bf52bf 100644
--- a/tests/hermes_cli/test_update_sqlite_remediation.py
+++ b/tests/hermes_cli/test_update_sqlite_remediation.py
@@ -5,7 +5,6 @@ from types import SimpleNamespace
from hermes_cli import update_cmd
import hermes_cli.update_cmd_maint as update_cmd_maint
-import hermes_cli.update_cmd_deps as update_cmd_deps
def test_runtime_status_probes_running_venv_outside_checkout(tmp_path, monkeypatch):
@@ -59,35 +58,8 @@ def test_summary_withholds_success_when_sqlite_remediation_failed(capsys, monkey
out = capsys.readouterr().out
assert complete is False
assert "Update complete" not in out
- assert "SQLite (3.46.1)" in out
- assert "WAL" not in out
- assert "venv" not in out
- assert "install.sh | bash" in out
- assert "hermes doctor" in out
-
-
-def test_sqlite_partial_message_is_shared_and_names_windows_installer(capsys, monkeypatch):
- """Both partial-completion paths print the same fix, and Windows gets the PowerShell one-liner."""
- for module in (update_cmd, update_cmd_maint):
- monkeypatch.setattr(
- module,
- "_post_update_sqlite_runtime_status",
- lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
- )
- monkeypatch.setattr(update_cmd._m(), "_is_windows", lambda: True)
-
- update_cmd._print_verified_update_completion("✓ Update complete!")
- verified_out = capsys.readouterr().out
- update_cmd._print_update_summary(node_failures=[], desktop_build_ok=True, pre_update_version=None)
- summary_out = capsys.readouterr().out
-
- for out in (verified_out, summary_out):
- assert "known corruption bug" in out
- assert "install.ps1" in out
- assert "install.sh" not in out
- assert "hermes doctor" in out
- fix_line = next(line for line in verified_out.splitlines() if "install.ps1" in line)
- assert fix_line in summary_out.splitlines()
+
+
def test_current_checkout_completion_is_verified_before_success(capsys, monkeypatch):
@@ -107,27 +79,5 @@ def test_current_checkout_completion_is_verified_before_success(capsys, monkeypa
out = capsys.readouterr().out
assert complete is False
assert "Already up to date" not in out
- assert "SQLite (3.46.1)" in out
- assert "hermes doctor" in out
-def test_current_checkout_repair_returns_verified_completion_result(monkeypatch):
- monkeypatch.setattr(update_cmd, "_update_node_dependencies", lambda: [])
- monkeypatch.setattr(update_cmd_deps, "_update_node_dependencies", lambda: [])
- monkeypatch.setattr(update_cmd._m(), "_build_web_ui", lambda _path: None)
- monkeypatch.setattr(
- update_cmd,
- "_rebuild_desktop_after_update",
- lambda _dir, **_kwargs: True,
- )
- monkeypatch.setattr(
- update_cmd_deps,
- "_rebuild_desktop_after_update",
- lambda _dir, **_kwargs: True,
- )
-
- complete = update_cmd._repair_node_deps_on_current_checkout(
- lambda _message: False
- )
-
- assert complete is False
diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.py
index 902c9452609..5246a37df61 100644
--- a/tests/hermes_cli/test_update_stale_dashboard.py
+++ b/tests/hermes_cli/test_update_stale_dashboard.py
@@ -13,10 +13,8 @@ History:
from __future__ import annotations
-import importlib
import json
import os
-import subprocess
import sys
from unittest.mock import patch, MagicMock
@@ -28,8 +26,6 @@ from hermes_cli import dashboard_procs
from hermes_cli import main_dashboard
from hermes_cli import update_cmd
from hermes_cli.update_cmd import _finish_dashboard_update_cleanup
-from hermes_cli.main_dashboard import _restart_managed_dashboard_service
-from hermes_cli.dashboard_procs import _kill_stale_dashboard_processes as _warn_stale_dashboard_processes
@pytest.fixture(autouse=True)
@@ -46,24 +42,20 @@ def _refresh_bindings_against_live_module():
global _find_stale_dashboard_pids
global _kill_stale_dashboard_processes
global _restart_managed_dashboard_service
- global _warn_stale_dashboard_processes
_finish_dashboard_update_cleanup = update_cmd._finish_dashboard_update_cleanup
_find_stale_dashboard_pids = main_dashboard._find_stale_dashboard_pids
_kill_stale_dashboard_processes = dashboard_procs._kill_stale_dashboard_processes
_restart_managed_dashboard_service = main_dashboard._restart_managed_dashboard_service
- _warn_stale_dashboard_processes = dashboard_procs._kill_stale_dashboard_processes
yield
@pytest.fixture(autouse=True)
def _no_real_launchd_jobs():
"""The kill path now scans the host's launchd jobs on macOS; a developer's own LaunchAgents
- must never leak into these tests. Tests that need jobs patch the scan themselves; the one
- test that exercises the real scan takes this fixture explicitly to get the original back."""
- original = main_dashboard._loaded_launchd_backend_jobs
+ must never leak into these tests. Tests that need jobs patch the scan themselves."""
with patch.object(main_dashboard, "_loaded_launchd_backend_jobs", return_value=[]):
- yield original
+ yield
def _ps_line(pid: int, cmd: str) -> str:
@@ -219,12 +211,6 @@ class TestKillStaleDashboardPosix:
assert result["killed"] == [12345, 12346]
assert result["failed"] == []
- out = capsys.readouterr().out
- assert "Stopping 2 dashboard" in out
- assert "✓ stopped PID 12345" in out
- assert "✓ stopped PID 12346" in out
- assert "Restart the dashboard" in out
-
@@ -254,22 +240,13 @@ class TestKillStaleDashboardPosix:
raise AssertionError(f"unexpected subprocess.run call: {args}")
with patch("subprocess.run", side_effect=fake_run), \
- patch("hermes_cli.main_dashboard._find_stale_dashboard_pids", return_value=[]) as find_pids, \
+ patch("hermes_cli.main_dashboard._find_stale_dashboard_pids", return_value=[]), \
patch("os.kill") as kill:
_kill_stale_dashboard_processes(restart_managed=True)
- assert calls == [
- ["systemctl", "--user", "list-unit-files", "hermes-dashboard.service", "--no-legend", "--no-pager"],
- ["systemctl", "--user", "is-active", "hermes-dashboard.service"],
- ["systemctl", "--user", "is-enabled", "hermes-dashboard.service"],
- ["systemctl", "--user", "restart", "hermes-dashboard.service"],
- ]
- assert all(call[:1] != ["sudo"] and call[:2] != ["systemctl"] for call in calls)
- # The pass keeps scanning for serve backends the dashboard unit does
- # not own (#92145) — but with nothing stale, nothing is killed.
- find_pids.assert_called_once()
+ assert ["systemctl", "--user", "restart", "hermes-dashboard.service"] in calls
+ assert all(call[:1] != ["sudo"] and call[:2] == ["systemctl", "--user"] for call in calls)
kill.assert_not_called()
- assert "✓ restarted hermes-dashboard.service" in capsys.readouterr().out
@@ -304,17 +281,7 @@ class TestKillStaleDashboardWindows:
assert ["taskkill", "/PID", "12345", "/F"] in [c.args[0] for c in taskkill_calls]
assert ["taskkill", "/PID", "12346", "/F"] in [c.args[0] for c in taskkill_calls]
- out = capsys.readouterr().out
- assert "✓ stopped PID 12345" in out
- assert "✓ stopped PID 12346" in out
-
-
-class TestBackCompatAlias:
- """``_warn_stale_dashboard_processes`` is kept as an alias for the
- new kill function so old imports don't break."""
- def test_alias_is_the_kill_function(self):
- assert _warn_stale_dashboard_processes is _kill_stale_dashboard_processes
class TestDashboardUpdateCleanup:
@@ -335,56 +302,6 @@ class TestDashboardUpdateCleanup:
assert "stopped during update" not in capsys.readouterr().out
-class TestWindowsWmicEncoding:
- """Regression tests for #17049 — the Windows wmic branch must not crash
- `hermes update` on non-UTF-8 system locales (e.g. cp936 on zh-CN).
- """
-
- def test_wmic_routed_through_bounded_probe_run_with_ignore_errors(self):
- """The wmic scan must go through ``bounded_probe_run`` — which owns
- the deterministic UTF-8 decode (#17049) and the deadlock-safe
- post-timeout cleanup (#87134) — with errors='ignore' so undecodable
- bytes from a non-UTF-8 system code page (e.g. cp936 on zh-CN) don't
- take down the reader thread, and with a finite timeout.
-
- Cross-platform: nothing Windows-native executes once the probe is
- mocked, so ``sys.platform`` is patched rather than gating the test
- to the Windows-only CI job.
- """
- with patch("sys.platform", "win32"), \
- patch("hermes_cli._subprocess_compat.bounded_probe_run") as mock_probe:
- mock_probe.return_value = subprocess.CompletedProcess(
- args=["wmic"],
- returncode=0,
- stdout=(
- "CommandLine=python -m hermes_cli.main dashboard\n"
- "ProcessId=12345\n"
- ),
- stderr="",
- )
- pids = _find_stale_dashboard_pids()
-
- assert mock_probe.called, "bounded_probe_run was not invoked"
- wmic_call = mock_probe.call_args_list[0]
- assert wmic_call.args[0][0] == "wmic"
- kwargs = wmic_call.kwargs
- assert kwargs.get("errors") == "ignore", (
- "errors kwarg must be 'ignore' so undecodable bytes don't take "
- "down the reader thread (#17049)."
- )
- assert kwargs.get("timeout"), (
- "the scan must carry a finite timeout — bounded_probe_run "
- "guarantees the post-timeout cleanup is bounded too (#87134)."
- )
- assert pids == [12345]
-
- def test_probe_failure_fails_open_to_empty_list(self):
- """A spawn failure or timeout (bounded_probe_run → None) must yield
- an empty scan, not an AttributeError on result.stdout (#87134)."""
- with patch("sys.platform", "win32"), \
- patch("hermes_cli._subprocess_compat.bounded_probe_run",
- return_value=None):
- assert _find_stale_dashboard_pids() == []
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX kill + systemd restart")
@@ -418,10 +335,8 @@ class TestSupervisedBackendRestart:
restart.assert_called_once_with(
"hermes-serve.service", "/system.slice/hermes-serve.service"
)
- out = capsys.readouterr().out
- assert "✓ restarted systemd service hermes-serve.service" in out
# Supervised restart succeeded — no manual hint.
- assert "when you're ready" not in out
+ assert "when you're ready" not in capsys.readouterr().out
def test_already_restarted_unit_is_left_untouched(self):
"""Review on #83595: hermes update's systemd fleet-restart loop may
@@ -472,11 +387,10 @@ class TestManualBackendRespawn:
patch.object(live, "_respawn_dashboard_processes") as respawn, \
patch("os.kill", side_effect=fake_kill), \
patch("time.sleep"):
- _kill_stale_dashboard_processes(restart_managed=True)
+ result = _kill_stale_dashboard_processes(restart_managed=True)
respawn.assert_not_called()
- out = capsys.readouterr().out
- assert "Restart anything not auto-restarted" in out
+ assert result["unrecovered"] == [5555]
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")
def test_non_orphan_fixed_port_still_respawns(self, capsys):
@@ -533,29 +447,6 @@ class TestManualBackendRespawn:
assert result["unrecovered"] == []
assert "when you're ready" not in capsys.readouterr().out
- @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")
- def test_detached_fixed_port_still_respawns_after_prior_update(self, capsys):
- """PPID-1 fixed-port backends (prior start_new_session respawn) stay eligible."""
- live = self._live()
- argv = ["hermes", "dashboard", "--port", "8300"]
-
- def fake_kill(pid, sig):
- if sig == 0:
- raise ProcessLookupError
-
- with patch.object(main_dashboard, "_restart_managed_dashboard_service", return_value=False), \
- patch.object(live, "_find_stale_dashboard_pids", return_value=[8001]), \
- patch.object(main_dashboard, "_get_pid_cgroup_path", return_value=None), \
- patch.object(main_dashboard, "_get_systemd_service_for_pid", return_value=None), \
- patch.object(main_dashboard, "_dashboard_cmdline_for_pid", return_value=argv), \
- patch("hermes_cli.dashboard_procs._hermes_home_for_pid", return_value=None), \
- patch.object(live, "_respawn_dashboard_processes", return_value=[]) as respawn, \
- patch("os.kill", side_effect=fake_kill), \
- patch("time.sleep"):
- _kill_stale_dashboard_processes(restart_managed=True)
-
- respawn.assert_called_once_with([argv])
- assert "when you're ready" not in capsys.readouterr().out
def test_respawn_adds_no_open_to_dashboard_commands(self, tmp_path, monkeypatch):
"""Respawned `dashboard` argv gains --no-open; `serve` argv untouched."""
@@ -585,8 +476,6 @@ class TestManualBackendRespawn:
failed = live._respawn_dashboard_processes([["hermes", "serve"]])
assert failed == [["hermes", "serve"]]
- out = capsys.readouterr().out
- assert "✗ failed to restart" in out
class TestFilterDashboardRespawnCandidates:
@@ -619,12 +508,6 @@ class TestFilterDashboardRespawnCandidates:
argv = ["hermes", "serve", "--port=0"]
assert _filter_dashboard_respawn_candidates([(1, argv, None)]) == []
- def test_keeps_ppid1_fixed_port_for_repeat_update(self):
- """Detached prior-update respawns (PPID 1) must remain restartable (#40449)."""
- from hermes_cli.dashboard_procs import _filter_dashboard_respawn_candidates
-
- argv = ["hermes", "dashboard", "--port", "9119"]
- assert _filter_dashboard_respawn_candidates([(10, argv, None)]) == [argv]
def test_dedupes_identical_normalized_cmdlines(self):
from hermes_cli.dashboard_procs import _filter_dashboard_respawn_candidates
@@ -785,24 +668,7 @@ class TestFilterDashboardRespawnCandidates:
])
assert own == [argv]
- def test_keeps_fixed_port_serve(self):
- from hermes_cli.dashboard_procs import _filter_dashboard_respawn_candidates
-
- argv = ["hermes", "serve", "--host", "0.0.0.0", "--port", "9119"]
- assert _filter_dashboard_respawn_candidates([
- (9, argv, None),
- ]) == [argv]
- def test_seventeen_port_zero_orphans_collapse_to_zero(self):
- """The reported accumulation case: many identical serve --port 0 → none."""
- from hermes_cli.dashboard_procs import _filter_dashboard_respawn_candidates
-
- argv = [
- "python", "-m", "hermes_cli.main",
- "serve", "--host", "127.0.0.1", "--port", "0",
- ]
- candidates = [(i, argv, None) for i in range(17)]
- assert _filter_dashboard_respawn_candidates(candidates) == []
class TestCmdlineCapture:
@@ -857,7 +723,6 @@ class TestCmdlineCapture:
real Windows host" — asserting it against a faked platform only
restated the branch condition.
"""
- live = self._live()
assert main_dashboard._dashboard_cmdline_for_pid(123) is None
@@ -935,9 +800,7 @@ class TestLaunchdSupervisedBackends:
respawn.assert_not_called()
restart.assert_called_once_with("system", "ai.hermes.dashboard", None)
assert result["killed"] == [9102] and result["unrecovered"] == []
- out = capsys.readouterr().out
- assert "✓ restarted launchd job system/ai.hermes.dashboard" in out
- assert "when you're ready" not in out
+ assert "when you're ready" not in capsys.readouterr().out
result, restart, respawn = self._run(9103, [("gui/501", "ai.hermes.dashboard", list(self.ARGV), 9103)],
restart_ok=False)
@@ -956,54 +819,17 @@ class TestLaunchdSupervisedBackends:
respawn.assert_called_once_with([list(self.ARGV)])
assert result["unrecovered"] == []
- def test_loaded_backend_jobs_scans_plists_and_attributes_pids_host_independently(
- self, tmp_path, monkeypatch, _no_real_launchd_jobs):
- """Pure plist scan + attribution, runnable off macOS (platform forced): only LOADED jobs whose
- ProgramArguments are a dashboard/serve backend are returned (gateway plists are never probed,
- unloaded backends dropped, unreadable plists skipped, LaunchDaemons resolve to the system
- domain); a PID is attributed by launchd's live PID, by a live-PID ancestor (exec-less
- ``/bin/sh -c`` wrapper plist) or by exact argv (the detached copy), never otherwise."""
- import plistlib
-
- agents, daemons = tmp_path / "LaunchAgents", tmp_path / "LaunchDaemons"
- agents.mkdir()
- daemons.mkdir()
+ def test_launchd_job_attribution_is_by_live_pid_ancestor_or_exact_argv(self):
+ """A PID is attributed to a loaded launchd backend job by launchd's live PID, by a live-PID
+ ancestor (exec-less ``/bin/sh -c`` wrapper plist) or by exact argv (the detached copy),
+ never otherwise."""
+ uid = 501
backend_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "dashboard", "--port", "9119"]
serve_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "serve", "--port", "8642"]
- gateway_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "gateway", "run"]
- for path, label, argv in (
- (agents / "ai.hermes.dashboard.plist", "ai.hermes.dashboard", backend_argv),
- (agents / "ai.hermes.gateway.plist", "ai.hermes.gateway", gateway_argv),
- (agents / "ai.hermes.serve-old.plist", "ai.hermes.serve-old", serve_argv),
- (daemons / "ai.hermes.serve.plist", "ai.hermes.serve", serve_argv),
- ):
- with open(path, "wb") as f:
- plistlib.dump({"Label": label, "ProgramArguments": argv}, f)
- (agents / "broken.plist").write_bytes(b"not a plist")
-
- uid = 501
- probed: list[tuple[str, str]] = []
-
- def fake_print(domain, label):
- probed.append((domain, label))
- if (domain, label) == (f"user/{uid}", "ai.hermes.dashboard"):
- return (True, 4242)
- if (domain, label) == ("system", "ai.hermes.serve"):
- return (True, None)
- return (False, None)
-
- monkeypatch.setattr(main_dashboard.sys, "platform", "darwin")
- monkeypatch.setattr(main_dashboard.os, "getuid", lambda: uid, raising=False)
- with patch("hermes_cli.gateway._launchd_print_service_pid", side_effect=fake_print):
- jobs = _no_real_launchd_jobs([("agent", agents), ("daemon", daemons)])
-
- assert jobs == [
+ jobs = [
(f"user/{uid}", "ai.hermes.dashboard", backend_argv, 4242),
("system", "ai.hermes.serve", serve_argv, None),
]
- assert not any(label == "ai.hermes.gateway" for _domain, label in probed)
- assert probed[:2] == [(f"gui/{uid}", "ai.hermes.dashboard"), (f"user/{uid}", "ai.hermes.dashboard")]
- assert not any(domain == "system" and label != "ai.hermes.serve" for domain, label in probed)
owning = main_dashboard._launchd_job_owning_backend
assert owning(4242, ["something", "else"], jobs) == (f"user/{uid}", "ai.hermes.dashboard", 4242)
diff --git a/tests/hermes_cli/test_update_stale_gateway_yield.py b/tests/hermes_cli/test_update_stale_gateway_yield.py
index 59f01c459b2..196f1340e6a 100644
--- a/tests/hermes_cli/test_update_stale_gateway_yield.py
+++ b/tests/hermes_cli/test_update_stale_gateway_yield.py
@@ -49,9 +49,7 @@ def test_cron_status_reports_stale_code_yield_as_unhealthy(cron_home, had_succes
out = _status_block([4242])
assert "cron jobs will fire automatically" not in out
- assert "STALE code" in out
assert "5eb99eb284" in out and "2ed6387d87" in out
- assert "hermes gateway restart" in out
def test_cron_status_still_green_after_a_clean_tick(cron_home):
diff --git a/tests/hermes_cli/test_update_stale_virtualenv.py b/tests/hermes_cli/test_update_stale_virtualenv.py
index d333c9afa6a..ac9eca3825d 100644
--- a/tests/hermes_cli/test_update_stale_virtualenv.py
+++ b/tests/hermes_cli/test_update_stale_virtualenv.py
@@ -3,7 +3,6 @@
Simulates the real crash: a pip/system-Python install where PROJECT_ROOT is
site-packages and VIRTUAL_ENV=PROJECT_ROOT/venv does not exist.
"""
-import os
import sys
import unittest
from pathlib import Path
@@ -82,32 +81,11 @@ class StaleVirtualEnvTest(unittest.TestCase):
def test_existing_python_flag_wins(self):
"""A caller-supplied --python is not duplicated by the pin."""
- captured = self._call(
- uv_cmd=[Path("/fake/uv"), "pip"],
- venv_path=Path("/fake/project/venv"),
- fake_executable="/fake/python311/python.exe",
- )
- # Force the caller path through a manual pin with a pre-existing flag.
args = ["install", "--python", "/caller/choice/python.exe", "hermes"]
pinned = main_install_repair._insert_python_pin(args)
self.assertEqual(pinned, args, "existing --python must win")
self.assertEqual(pinned.count("--python"), 1)
- def test_windows_pins_quarantine_to_interpreter_scripts_dir(self):
- """On Windows with a missing project venv, quarantine must target the
- interpreter's Scripts dir (where the shims actually live), not None."""
- fake_scripts = Path("/fake/python311/Scripts")
- with mock.patch.object(main_install_repair, "_interpreter_scripts_dir", return_value=fake_scripts
- ):
- captured = self._call(
- uv_cmd=[Path("/fake/uv"), "pip"],
- venv_path=Path("/fake/project/venv"),
- fake_executable="/fake/python311/python.exe",
- is_windows=True,
- )
- self.assertTrue(captured, "no subprocess call captured")
- _, _, scripts_dir = captured[0]
- self.assertEqual(scripts_dir, fake_scripts)
if __name__ == "__main__":
diff --git a/tests/hermes_cli/test_update_upstream_prompt_noninteractive.py b/tests/hermes_cli/test_update_upstream_prompt_noninteractive.py
index f737c3398f1..00b4bd36e84 100644
--- a/tests/hermes_cli/test_update_upstream_prompt_noninteractive.py
+++ b/tests/hermes_cli/test_update_upstream_prompt_noninteractive.py
@@ -57,7 +57,6 @@ class TestUpstreamPromptNonInteractive:
fork_without_upstream.stdin_input.assert_not_called()
fork_without_upstream.add_remote.assert_not_called()
fork_without_upstream.mark_skip.assert_not_called()
- assert "Skipping upstream setup" in capsys.readouterr().out
@pytest.mark.parametrize(
"stdin_tty,stdout_tty", [(False, False), (False, True), (True, False)]
@@ -75,7 +74,6 @@ class TestUpstreamPromptNonInteractive:
fork_without_upstream.stdin_input.assert_not_called()
fork_without_upstream.add_remote.assert_not_called()
fork_without_upstream.mark_skip.assert_not_called()
- assert "Skipping upstream setup" in capsys.readouterr().out
def test_gateway_prompt_routes_through_input_fn(self, fork_without_upstream):
prompts = []
@@ -90,7 +88,7 @@ class TestUpstreamPromptNonInteractive:
["git"], fork_without_upstream.cwd, input_fn=gw_input
)
- assert prompts == [("Add official repo as 'upstream' remote? [y/N]", "n")]
+ assert len(prompts) == 1 and prompts[0][1] == "n"
fork_without_upstream.stdin_input.assert_not_called()
fork_without_upstream.add_remote.assert_not_called()
fork_without_upstream.mark_skip.assert_called_once_with()
diff --git a/tests/hermes_cli/test_update_venv_health.py b/tests/hermes_cli/test_update_venv_health.py
index 1c7c7dd5933..b0216fad1b5 100644
--- a/tests/hermes_cli/test_update_venv_health.py
+++ b/tests/hermes_cli/test_update_venv_health.py
@@ -1,27 +1,14 @@
"""Tests for the Windows half-updated-venv hardening (July 2026 incident).
-Covers three additions to ``hermes update``:
-
-1. ``_venv_core_imports_healthy`` — the venv health probe that lets an
- "Already up to date" checkout still repair a broken dependency install.
-2. ``_detect_venv_python_processes`` — the venv-interpreter process guard
- that refuses to mutate the venv while a desktop backend / stray python
- holds .pyd files mapped.
-3. The commit_count == 0 repair branch wiring in ``_cmd_update_impl``.
-
-All Windows-specific paths are exercised via ``_is_windows`` patching so
-they run on any host (same approach as test_update_concurrent_quarantine).
+Covers the commit_count == 0 repair branch: an "Already up to date" checkout
+must still re-sync a venv whose installed distribution lags the checkout.
"""
from __future__ import annotations
-import subprocess
-import sys
-import types
from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
-import pytest
from hermes_cli import main as cli_main
from hermes_cli import update_cmd
@@ -44,205 +31,6 @@ def _fake_venv_python(tmp_path, *, windows: bool = False):
-# ---------------------------------------------------------------------------
-# _detect_venv_python_processes
-# ---------------------------------------------------------------------------
-
-
-def _proc(pid: int, exe: str, name: str, cmdline: list[str] | None = None, cwd: str = ""):
- proc = MagicMock()
- proc.info = {
- "pid": pid,
- "exe": exe,
- "name": name,
- }
- proc.cmdline.return_value = cmdline or []
- proc.cwd.return_value = cwd
- return proc
-
-
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_detect_venv_python_excludes_self_and_ancestors(_winp, tmp_path):
- import os as _os
-
- venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe")
- parent = MagicMock()
- parent.pid = 555
- me = MagicMock()
- me.parents.return_value = [parent]
- fake_psutil = types.SimpleNamespace(
- process_iter=lambda attrs: iter(
- [
- _proc(_os.getpid(), venv_py, "python.exe"),
- _proc(555, venv_py, "hermes.exe"),
- ]
- ),
- Process=lambda *a, **k: me,
- )
- with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(
- sys.modules, {"psutil": fake_psutil}
- ):
- assert cli_main._detect_venv_python_processes() == []
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_detect_venv_python_prefetches_only_cheap_process_fields(_winp, tmp_path):
- venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe")
- holder = _proc(101, venv_py, "python.exe", [venv_py, "-m", "hermes_cli.main", "serve"])
- unrelated = _proc(102, r"C:\Program Files\Browser\browser.exe", "browser.exe")
- unrelated.cmdline.side_effect = AssertionError("unrelated cmdline must stay lazy")
- unrelated.cwd.side_effect = AssertionError("unrelated cwd must stay lazy")
- attrs_seen = []
- me = MagicMock()
- me.parents.return_value = []
-
- def process_iter(attrs):
- attrs_seen.append(attrs)
- return iter([unrelated, holder])
-
- fake_psutil = types.SimpleNamespace(
- process_iter=process_iter,
- Process=lambda *a, **k: me,
- )
- with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(
- sys.modules, {"psutil": fake_psutil}
- ):
- matches = cli_main._detect_venv_python_processes()
-
- assert attrs_seen == [["pid", "exe", "name"]]
- assert [match[0] for match in matches] == [101]
- holder.cmdline.assert_called_once_with()
- holder.cwd.assert_not_called()
- unrelated.cmdline.assert_not_called()
- unrelated.cwd.assert_not_called()
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_detect_venv_python_matches_uv_default_dotvenv(_winp, tmp_path):
- """#112958: the venv-prefix arm must see a uv-default ``.venv`` interpreter. A kernel-runner child has
- no ``hermes_cli.main`` in its cmdline, so only that arm can match it — the guard was blind to it."""
- venv_py = str(tmp_path / ".venv" / "Scripts" / "python.exe")
- holder = _proc(104, venv_py, "python.exe", [venv_py, str(tmp_path / "tools" / "hermes_kernel_runner.py")])
- me = MagicMock()
- me.parents.return_value = []
- fake_psutil = types.SimpleNamespace(
- process_iter=lambda attrs: iter([holder]),
- Process=lambda *a, **k: me,
- )
- (tmp_path / ".venv").mkdir()
-
- with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake_psutil}):
- matches = cli_main._detect_venv_python_processes()
-
- assert [match[0] for match in matches] == [104]
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_detect_venv_python_keeps_external_interpreter_fallback(_winp, tmp_path):
- external = _proc(
- 103,
- r"C:\Python311\python.exe",
- "python.exe",
- ["python.exe", "-m", "hermes_cli.main", "serve"],
- str(tmp_path),
- )
- me = MagicMock()
- me.parents.return_value = []
- fake_psutil = types.SimpleNamespace(
- process_iter=lambda attrs: iter([external]),
- Process=lambda *a, **k: me,
- )
- with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(
- sys.modules, {"psutil": fake_psutil}
- ):
- matches = cli_main._detect_venv_python_processes()
-
- assert [match[0] for match in matches] == [103]
- external.cmdline.assert_called_once_with()
- external.cwd.assert_called_once_with()
-
-
-
-
-# ---------------------------------------------------------------------------
-# --force vs --force-venv gating of the venv-holder guard
-# ---------------------------------------------------------------------------
-
-
-def _update_args(**overrides):
- defaults = dict(
- gateway=False,
- check=False,
- no_backup=True,
- backup=False,
- yes=True,
- branch=None,
- force=False,
- force_venv=False,
- )
- defaults.update(overrides)
- return SimpleNamespace(**defaults)
-
-
-def _run_update_until_guard(args):
- """Drive _cmd_update_impl just far enough to hit the venv-holder guard.
-
- Everything before the guard is stubbed; the guard firing is observed via
- SystemExit(2). The first statement AFTER the guard is
- ``git_dir = PROJECT_ROOT / ".git"`` — a PROJECT_ROOT sentinel whose
- ``__truediv__`` raises marks 'guard passed'."""
-
- class _PastGuard(Exception):
- pass
-
- class _RootSentinel:
- def __truediv__(self, _other):
- raise _PastGuard
-
- with patch.object(cli_main, "_is_windows", return_value=True), patch.object(
- cli_main, "_venv_scripts_dir", return_value=None
- ), patch.object(cli_main, "_run_pre_update_backup"), patch.object(
- cli_main, "_pause_windows_gateways_for_update", return_value=None
- ), patch.object(
- cli_main, "_resume_windows_gateways_after_update"
- ), patch.object(
- cli_main,
- "_detect_venv_python_processes",
- return_value=[(101, "python.exe", "python.exe -m hermes_cli.main serve")],
- ), patch.object(
- # Pin the orphan classifier: this test exercises --force/--force-venv
- # gating, not orphan detection (covered in
- # test_update_orphan_backend_reap.py). None = "not provably orphaned"
- # → the guard refuses exactly as before the orphan-reap addition.
- cli_main, "_orphaned_desktop_backend_pids", return_value=None
- ), patch.object(
- cli_main, "PROJECT_ROOT", _RootSentinel()
- ):
- try:
- update_cmd._cmd_update_impl(args, gateway_mode=False)
- except _PastGuard:
- return "past_guard"
- except SystemExit as exc:
- return f"exit_{exc.code}"
- return "returned"
-
-
- "force,force_venv,expected",
- [
- (False, False, "exit_2"), # guard fires
- (True, False, "exit_2"), # plain --force does NOT bypass the venv guard
- (False, True, "past_guard"), # --force-venv is the explicit escape hatch
- (True, True, "past_guard"),
- ],
-)
-def test_venv_holder_guard_force_semantics(force, force_venv, expected, capsys):
- result = _run_update_until_guard(_update_args(force=force, force_venv=force_venv))
- assert result == expected, capsys.readouterr().out
-
-
# ---------------------------------------------------------------------------
# "Already up to date" must not hide a venv the last pull never re-synced (#97208)
# ---------------------------------------------------------------------------
@@ -296,6 +84,5 @@ def test_current_checkout_with_stale_dependency_set_runs_the_sync(monkeypatch, c
assert run((True, "installed hermes-agent 0.20.6, checkout is 0.21.2")) is True
assert calls == ["sync"]
- assert "never synced after the last pull" in capsys.readouterr().out
assert run((False, "")) is True
assert calls == ["sync", "✓ Already up to date!"]
diff --git a/tests/hermes_cli/test_update_venv_ownership_preflight.py b/tests/hermes_cli/test_update_venv_ownership_preflight.py
index 9a7820c2e4d..baec3a217c6 100644
--- a/tests/hermes_cli/test_update_venv_ownership_preflight.py
+++ b/tests/hermes_cli/test_update_venv_ownership_preflight.py
@@ -84,9 +84,7 @@ def test_foreign_owned_refuses_with_chown_hint(tmp_path, monkeypatch, capsys):
assert exc.value.code == 1
out = capsys.readouterr().out
assert hermes_bin in out
- assert "owner uid 0" in out
assert f"sudo chown -R $(id -un): {tmp_path}" in out
- assert "Nothing in the venv was modified." in out
def test_limit_caps_reported_paths(tmp_path, monkeypatch):
@@ -109,18 +107,6 @@ def test_limit_caps_reported_paths(tmp_path, monkeypatch):
assert len(foreign) == 3
-def test_no_geteuid_returns_empty(tmp_path, monkeypatch):
- """Windows (no os.geteuid) skips the preflight entirely."""
- venv = _make_fake_venv(tmp_path)
-
- class _NoGeteuidOS:
- def __getattr__(self, name):
- if name == "geteuid":
- raise AttributeError(name)
- return getattr(os, name)
-
- monkeypatch.setattr(update_cmd, "os", _NoGeteuidOS())
- assert update_cmd._venv_foreign_owned_paths(venv) == []
def test_running_as_root_returns_empty(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_update_version_report.py b/tests/hermes_cli/test_update_version_report.py
index 00e3e309813..192bfd79055 100644
--- a/tests/hermes_cli/test_update_version_report.py
+++ b/tests/hermes_cli/test_update_version_report.py
@@ -44,24 +44,17 @@ class TestReadProjectVersion:
class TestUpdateCompleteMessage:
def test_reports_transition_when_version_changed(self, fake_root):
_write_pyproject(fake_root, "0.20.0")
- assert (
- update_cmd._update_complete_message("0.19.4")
- == "✓ Update complete! (v0.19.4 → v0.20.0)"
- )
+ msg = update_cmd._update_complete_message("0.19.4")
+ assert "v0.19.4" in msg and "v0.20.0" in msg
def test_same_version_reports_single_version(self, fake_root):
_write_pyproject(fake_root, "0.20.0")
- assert (
- update_cmd._update_complete_message("0.20.0")
- == "✓ Update complete! (v0.20.0)"
- )
+ assert update_cmd._update_complete_message("0.20.0").count("v0.20.0") == 1
def test_unknown_pre_version_still_shows_current(self, fake_root):
_write_pyproject(fake_root, "0.20.0")
- assert (
- update_cmd._update_complete_message(None)
- == "✓ Update complete! (v0.20.0)"
- )
+ assert "v0.20.0" in update_cmd._update_complete_message(None)
def test_unknown_post_version_falls_back_to_plain(self, fake_root):
- assert update_cmd._update_complete_message("0.19.4") == "✓ Update complete!"
+ msg = update_cmd._update_complete_message("0.19.4")
+ assert msg and "0.19.4" not in msg
diff --git a/tests/hermes_cli/test_update_wedged_gateway.py b/tests/hermes_cli/test_update_wedged_gateway.py
index f76d3203810..149e3ccdbd8 100644
--- a/tests/hermes_cli/test_update_wedged_gateway.py
+++ b/tests/hermes_cli/test_update_wedged_gateway.py
@@ -117,7 +117,8 @@ def _start_freezeable_producer(tmp_path, block_s, errors, write_stall_s=1.5):
write, so the file goes stale while the loop keeps dispatching.
"""
freeze_evt = asyncio.Event()
- state: dict = {"loop": None, "trigger": None, "thread": None}
+ stop_evt = asyncio.Event()
+ state: dict = {"loop": None, "trigger": None, "thread": None, "stop": lambda: None}
ready = threading.Event()
def stalling_write(**_kwargs):
@@ -137,6 +138,7 @@ def _start_freezeable_producer(tmp_path, block_s, errors, write_stall_s=1.5):
loop = asyncio.get_running_loop()
state["loop"] = loop
state["trigger"] = lambda: loop.call_soon_threadsafe(freeze_evt.set)
+ state["stop"] = lambda: loop.call_soon_threadsafe(stop_evt.set)
with patch("gateway.shutdown_watchdog.write_loop_heartbeat", stalling_write):
task = asyncio.create_task(
loop_heartbeat_forever(interval_s=1.0, home=tmp_path)
@@ -144,8 +146,7 @@ def _start_freezeable_producer(tmp_path, block_s, errors, write_stall_s=1.5):
gate = asyncio.create_task(freeze_gate())
try:
ready.set()
- while True:
- await asyncio.sleep(3600)
+ await stop_evt.wait()
finally:
task.cancel()
gate.cancel()
@@ -313,14 +314,6 @@ class TestProbeGatewayLoopLiveness:
== gateway_cli.GATEWAY_LOOP_UNKNOWN
)
- def test_invalid_stale_after_falls_back_to_default(self, tmp_path):
- _write_heartbeat(tmp_path, pid=4242, age_s=600.0)
- assert (
- gateway_cli.probe_gateway_loop_liveness(
- 4242, stale_after="bogus", home=tmp_path
- )
- == gateway_cli.GATEWAY_LOOP_WEDGED
- )
def test_probe_never_raises_on_unreadable_path(self, monkeypatch):
monkeypatch.setattr(
@@ -496,155 +489,6 @@ class TestLoopTickWitness:
witnesses agree the loop stopped scheduling.
"""
- @_NEEDS_UNIX_SOCKETS
- def test_stalled_heartbeat_write_never_escalates_a_running_loop(
- self, tmp_path, monkeypatch
- ):
- """Producer + consumer composition.
-
- While the heartbeat write is stalled longer than the stale budget, a
- loop that demonstrably keeps dispatching must probe ALIVE — and a
- restart path fed by the real probe must take the graceful drain,
- never the bounded escalation. This is the exact false-positive the
- review called out: the measured fsync stall (112.6s max) exceeds the
- 90s destructive-classifier threshold.
- """
- pid = os.getpid()
- block_s = 1.5
- stale_after = 1.0
-
- # First write lands immediately; every later write stalls like an
- # fsync on the incident filesystem, so the file ages past the budget
- # while the loop keeps running.
- def stalling_write(**_kwargs):
- if not get_loop_heartbeat_path(tmp_path).exists():
- return write_loop_heartbeat(**_kwargs)
- time.sleep(block_s)
- return write_loop_heartbeat(**_kwargs)
-
- errors = []
-
- async def producer() -> None:
- with patch(
- "gateway.shutdown_watchdog.write_loop_heartbeat", stalling_write
- ):
- task = asyncio.create_task(
- loop_heartbeat_forever(interval_s=1.0, home=tmp_path)
- )
- try:
- # One interval (1.0s) elapses, the second write starts and
- # stalls; 1.35s in the file is stale but the loop ticks.
- await asyncio.sleep(1.35)
- finally:
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- def run_producer() -> None:
- try:
- asyncio.run(producer())
- except Exception as exc: # surfaced via errors after join
- errors.append(exc)
-
- thread = threading.Thread(target=run_producer, daemon=True)
- thread.start()
- try:
- sock_path = get_loop_tick_socket_path(tmp_path, pid)
- deadline = time.monotonic() + 5.0
- while not sock_path.exists() and time.monotonic() < deadline:
- time.sleep(0.02)
- assert sock_path.exists(), "producer never armed the tick socket"
-
- hb_path = get_loop_heartbeat_path(tmp_path)
- deadline = time.monotonic() + 5.0
- while True:
- try:
- age = time.time() - hb_path.stat().st_mtime
- except FileNotFoundError:
- # The socket is armed before the first write lands; the
- # file appears a tick later.
- age = 0.0
- if age > stale_after:
- break
- assert time.monotonic() < deadline, "heartbeat never went stale"
- time.sleep(0.02)
-
- # The file is stale but the loop answers: ALIVE, not WEDGED.
- assert (
- gateway_cli.probe_gateway_loop_liveness(
- pid, home=tmp_path, stale_after=stale_after, tick_timeout=0.25
- )
- == gateway_cli.GATEWAY_LOOP_ALIVE
- )
-
- # The restart path fed by the REAL probe must drain, not escalate.
- events = []
- monkeypatch.setattr(
- gateway_cli, "get_launchd_label", lambda: "ai.hermes.gateway"
- )
- monkeypatch.setattr(gateway_cli, "_launchd_domain", lambda: "gui/501")
- monkeypatch.setattr(gateway_cli, "_get_restart_drain_timeout", lambda: 180.0)
- monkeypatch.setattr(
- "gateway.status.get_running_pid", lambda *a, **k: pid
- )
- monkeypatch.setattr(
- gateway_cli, "_request_gateway_self_restart", lambda pid: False
- )
- monkeypatch.setattr(
- gateway_cli,
- "_escalate_wedged_gateway",
- lambda pid, **kw: events.append("escalate") or True,
- )
- monkeypatch.setattr(
- gateway_cli,
- "terminate_pid",
- lambda pid, force=False, **kwargs: events.append(("kill" if force else "term", pid)),
- )
- # Never let a real SIGUSR1 escape to os.getpid() — the drain
- # path now goes through _graceful_restart_via_sigusr1 (in-place
- # restart) before any exit-wait, and this test feeds the REAL
- # launchd_restart our own live PID.
- monkeypatch.setattr(
- gateway_cli,
- "_graceful_restart_via_sigusr1",
- lambda pid, timeout, **_: events.append(("drain", pid, timeout)) or True,
- )
- monkeypatch.setattr(
- gateway_cli,
- "_wait_for_gateway_exit",
- lambda timeout, force_after=None: events.append(("drain", timeout))
- or True,
- )
- monkeypatch.setattr(
- gateway_cli,
- "_wait_for_launchd_service_pid",
- lambda label, old_pid, timeout=10.0, *, domain: events.append("observe")
- or True,
- )
- monkeypatch.setattr(
- gateway_cli.subprocess,
- "run",
- lambda *a, **k: events.append("kickstart")
- or __import__("types").SimpleNamespace(
- returncode=0, stdout="", stderr=""
- ),
- )
- monkeypatch.setattr(
- gateway_cli, "_clear_launchd_unsupported_marker", lambda: None
- )
- # The real probe resolves the state dir through this hook.
- monkeypatch.setattr(
- "gateway.shutdown_watchdog._process_hermes_home", lambda: tmp_path
- )
- gateway_cli.launchd_restart()
- assert "escalate" not in events
- drains = [e for e in events if isinstance(e, tuple) and e[0] == "drain"]
- assert drains, events
- finally:
- thread.join(timeout=5.0)
- assert not errors, errors
@_NEEDS_UNIX_SOCKETS
def test_off_loop_completion_cannot_manufacture_fresh_liveness(self, tmp_path):
@@ -722,36 +566,7 @@ class TestLoopTickWitness:
)
== gateway_cli.GATEWAY_LOOP_ALIVE
)
- # First probe (miss) + exactly one sustained-window follow-up.
- assert len(calls) == 2
- def test_sustained_silence_is_required_for_wedge(self, tmp_path, monkeypatch):
- """WEDGED only after the full bounded window of consecutive misses.
-
- With ``tick_strikes=2`` the probe must observe BOTH samples silent
- before granting the wedge verdict; a single silent sample alone
- would previously have escalated.
- """
- pid = 4242
- calls = []
- monkeypatch.setattr(
- gateway_cli,
- "_probe_loop_tick_socket",
- lambda _pid, _home, timeout=1.0: (calls.append(timeout), False)[1],
- )
- _write_heartbeat(tmp_path, pid, age_s=600.0)
- _mark_witness_flag(tmp_path, armed=True, age_s=600.0)
- assert (
- gateway_cli.probe_gateway_loop_liveness(
- pid,
- home=tmp_path,
- tick_timeout=0.2,
- tick_strikes=2,
- tick_gap_s=0.0,
- )
- == gateway_cli.GATEWAY_LOOP_WEDGED
- )
- assert len(calls) == 2 # miss #1 (initial probe) + miss #2 (window)
def test_witness_vanishing_mid_window_is_unknown(self, tmp_path, monkeypatch):
"""A witness that disappears mid-window is ambiguity, not a wedge.
@@ -936,6 +751,7 @@ class TestLoopTickWitness:
drains = [e for e in events if isinstance(e, tuple) and e[0] == "drain"]
assert drains, events
finally:
+ state["stop"]()
state["thread"].join(timeout=5.0)
assert not errors, errors
@@ -982,6 +798,7 @@ class TestLoopTickWitness:
)
assert verdict == gateway_cli.GATEWAY_LOOP_WEDGED, verdict
finally:
+ state["stop"]()
state["thread"].join(timeout=5.0)
assert not errors, errors
@@ -1093,26 +910,3 @@ class TestLoopTickTcpWitness:
)
-def test_default_probe_budget_stays_inside_query_tier():
- """The module doc pins the worst-case wedge-suspected probe at ~3.4s,
- 'far inside the 10s query tier'. Assert the strike-count math so
- retuning tick_timeout / tick_strikes / tick_gap_s can't silently blow
- past that tier (reviewer ask on #92315).
-
- Worst case: the first probe misses (tick_timeout), then the sustained
- window runs (tick_strikes - 1) more probes, each up to tick_timeout,
- with tick_gap_s sleeps between attempts.
- """
- import inspect
-
- sig = inspect.signature(gateway_cli.probe_gateway_loop_liveness)
- tick_timeout = sig.parameters["tick_timeout"].default
- tick_strikes = sig.parameters["tick_strikes"].default
- tick_gap_s = sig.parameters["tick_gap_s"].default
-
- worst_case = tick_strikes * tick_timeout + (tick_strikes - 1) * tick_gap_s
- assert worst_case <= 5.0, (
- f"default probe budget {worst_case:.1f}s exceeds half the 10s query "
- "tier — retune tick_timeout/tick_strikes/tick_gap_s or update the "
- "subprocess-timeout doc reference in hermes_cli/gateway.py"
- )
diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.py
index 858ce17e016..edd799509bb 100644
--- a/tests/hermes_cli/test_update_yes_flag.py
+++ b/tests/hermes_cli/test_update_yes_flag.py
@@ -20,8 +20,12 @@ from hermes_cli.main import cmd_update
@pytest.fixture(autouse=True)
def _isolate_update(isolated_update_runtime, monkeypatch):
import shutil
- from hermes_cli import managed_uv, update_cmd
+ from hermes_cli import managed_uv, update_cmd, update_cmd_deps, update_cmd_fleet
+ # The post-restart survivor sweep real-sleeps 3s; no gateways exist here.
+ monkeypatch.setattr(update_cmd_fleet, "_force_kill_stuck_gateways", lambda *a, **k: None)
+ # The post-pull import probe spawns a real interpreter (~2.5s); the tree is unchanged here.
+ monkeypatch.setattr(update_cmd_deps, "_critical_module_import_failures", lambda *a, **k: {})
monkeypatch.setattr(managed_uv, "resolve_uv", lambda **kw: shutil.which("uv"))
monkeypatch.setattr(managed_uv, "ensure_uv", lambda **kw: shutil.which("uv"))
monkeypatch.setattr(managed_uv, "update_managed_uv", lambda **kw: None)
@@ -97,11 +101,6 @@ class TestUpdateYesConfigMigration:
_, 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._run_migrate_config_fresh")
@patch("hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2))
@patch("hermes_cli.config.get_missing_config_fields", return_value=[])
@@ -145,11 +144,6 @@ class TestUpdateYesConfigMigration:
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
@@ -208,9 +202,7 @@ class TestUnicodeDecodeErrorInUpdatePrompts:
) # 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
+ assert "git stash apply stash@{0}" in capsys.readouterr().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,
diff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.py
index a623a0b2bfe..eb2c59038bb 100644
--- a/tests/hermes_cli/test_update_zip_fallback_guards.py
+++ b/tests/hermes_cli/test_update_zip_fallback_guards.py
@@ -74,18 +74,8 @@ def test_unknown_command_gets_generic_stage():
assert update_cmd._format_update_failure_stage(exc) == "Update step failed"
-def test_windows_dep_failure_does_not_zip_fallback(monkeypatch):
- monkeypatch.setattr(hermes_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- exc = _cpe([r"C:\venv\Scripts\uv.exe", "pip", "install", "-e", "."])
- assert update_cmd._should_zip_fallback_on_update_error(exc) is False
-def test_windows_git_failure_still_zips(monkeypatch):
- monkeypatch.setattr(hermes_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- exc = _cpe(["git", "pull"], returncode=1)
- assert update_cmd._should_zip_fallback_on_update_error(exc) is True
def test_posix_git_failure_does_not_zip(monkeypatch):
@@ -95,16 +85,6 @@ def test_posix_git_failure_does_not_zip(monkeypatch):
assert update_cmd._should_zip_fallback_on_update_error(exc) is False
-def test_error_tail_prints_last_lines(capsys):
- stderr = "\n".join(f"line-{i}" for i in range(20))
- exc = _cpe(["uv", "pip", "install"], stderr=stderr)
- update_cmd._print_called_process_error_tail(exc)
- out = capsys.readouterr().out
- assert "Last output:" in out
- assert "line-19" in out
- assert "line-0" not in out
- assert "line-7" not in out
- assert "line-8" in out
# ---------------------------------------------------------------------------
@@ -192,9 +172,6 @@ def test_update_via_zip_aborts_before_download_when_dirty(
download.assert_not_called()
assert local.read_text(encoding="utf-8") == "local work\n"
assert (untracked_dir / "wip.py").read_text(encoding="utf-8") == "print('wip')\n"
- out = capsys.readouterr().out
- assert "ZIP fallback refused" in out
- assert "Downloading latest version" not in out
# ---------------------------------------------------------------------------
@@ -314,21 +291,6 @@ def test_zip_overlay_flag_is_valid_against_real_git(tmp_path):
assert update_cmd._zip_overlay_block_reason(tmp_path) is None, status
-def test_zip_overlay_requests_ignored_files_from_git(tmp_path, monkeypatch):
- """The status invocation itself must carry a (valid) ignored mode."""
- seen = {}
-
- def capture_run(cmd, **kwargs):
- joined = " ".join(str(c) for c in cmd)
- if "status" in joined and "--porcelain" in joined:
- seen["cmd"] = cmd
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
-
- (tmp_path / ".git").mkdir()
- monkeypatch.setattr(update_cmd.subprocess, "run", capture_run)
- update_cmd._zip_overlay_block_reason(tmp_path)
- assert "--ignored=matching" in [str(c) for c in seen["cmd"]]
def test_preserved_filter_does_not_split_non_rename_lines():
@@ -351,16 +313,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):
diff --git a/tests/hermes_cli/test_update_zip_release_preserve.py b/tests/hermes_cli/test_update_zip_release_preserve.py
index b6488076ce6..8fe1033f4de 100644
--- a/tests/hermes_cli/test_update_zip_release_preserve.py
+++ b/tests/hermes_cli/test_update_zip_release_preserve.py
@@ -10,53 +10,10 @@ fallback refuses every install that has them.
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", encoding="utf-8")
-
- # 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", encoding="utf-8")
-
- 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(encoding="utf-8") == (
- "new source"
- )
- exe = root / "apps" / "desktop" / "release" / "win-unpacked" / "Hermes.exe"
- assert exe.exists() and exe.read_bytes() == b"MZbuilt"
def test_zip_swap_keeps_every_nested_build_output_and_the_guard_admits_them(tmp_path):
diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.py
index c0750a15532..eb646a4bb26 100644
--- a/tests/hermes_cli/test_update_zip_two_phase.py
+++ b/tests/hermes_cli/test_update_zip_two_phase.py
@@ -19,7 +19,6 @@ 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
# ---------------------------------------------------------------------------
@@ -134,64 +133,16 @@ def test_staging_clears_leftovers_from_an_interrupted_run(tmp_path):
# 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_managed_uv_helper_delegates_to_the_shared_one():
- from hermes_cli.managed_uv import _venv_python
- v = Path("/opt/proj/venv")
- assert _venv_python(v) == venv_python_path(v)
-def test_no_open_coded_venv_layout_remains_in_hermes_cli():
- """Fails if a new call site hand-rolls Scripts/bin again (#76105).
-
- Uses AST rather than substring matching: an earlier `"if" in line` version
- matched any word containing "if" (mod*if*y, ver*if*y) and still missed
- `os.path.join(venv, "Scripts")`.
-
- ``stdio.py`` is exempt: it builds a list of literal *Windows-only* PATH
- candidates, not a cross-platform layout derivation, so ``venv_bin_dir()``
- (which branches on the host platform) would be the wrong tool there.
- """
- import ast
- import hermes_cli
-
- exempt = {"stdio.py"}
- pkg = Path(hermes_cli.__file__).parent
- offenders = []
- for py in pkg.rglob("*.py"):
- if py.name in exempt:
- continue
- try:
- tree = ast.parse(py.read_text(encoding="utf-8", errors="replace"))
- except SyntaxError:
- continue
- for node in ast.walk(tree):
- # Any *code* string literal "Scripts" is a hand-rolled layout;
- # docstrings and comments never reach ast.Constant in an expr
- # position we care about here.
- if isinstance(node, ast.Constant) and node.value == "Scripts":
- offenders.append(f"{py.relative_to(pkg)}:{node.lineno}")
- assert not offenders, (
- "open-coded venv layout found (use hermes_constants.venv_bin_dir):\n"
- + "\n".join(offenders)
- )
# ---------------------------------------------------------------------------
@@ -298,16 +249,6 @@ def test_failed_staging_leaves_no_orphaned_copies(tmp_path, monkeypatch):
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():
@@ -332,23 +273,6 @@ def test_venv_helpers_honour_an_explicit_platform_verdict():
)
-def test_patched_is_windows_reaches_the_venv_path_derivation():
- """End-to-end: patching the module predicate must change the derived path."""
- from unittest.mock import patch
-
- from hermes_cli import main as hermes_main
-
- with patch.object(hermes_main, "_is_windows", return_value=True):
- got = hermes_main._resolve_install_target_python(
- ["uv", "pip"], env={"VIRTUAL_ENV": "/nope/venv"}
- )
- # The path doesn't exist so we get None, but the *derivation* must have
- # used the Windows layout -- assert that directly.
- assert got is None
- assert (
- venv_python_path("/nope/venv", windows=True).as_posix()
- == "/nope/venv/Scripts/python.exe"
- )
# ---------------------------------------------------------------------------
@@ -431,44 +355,3 @@ def test_commit_failure_plus_discard_leaves_no_staging_litter(tmp_path, monkeypa
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_upstage_provider.py b/tests/hermes_cli/test_upstage_provider.py
index 074f9abe82c..1a08f15e491 100644
--- a/tests/hermes_cli/test_upstage_provider.py
+++ b/tests/hermes_cli/test_upstage_provider.py
@@ -35,66 +35,7 @@ class TestUpstageResolver:
assert "UPSTAGE_API_KEY" in pdef.api_key_env_vars
-class TestUpstageOverlay:
- def test_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
- assert "upstage" in HERMES_OVERLAYS
- overlay = HERMES_OVERLAYS["upstage"]
- assert overlay.transport == "openai_chat"
- assert overlay.extra_env_vars == ("UPSTAGE_API_KEY",)
- assert overlay.base_url_override == "https://api.upstage.ai/v1"
- assert overlay.base_url_env_var == "UPSTAGE_BASE_URL"
- assert not overlay.is_aggregator
- def test_provider_label(self):
- from hermes_cli.providers import get_label
- assert get_label("upstage") == "Upstage Solar"
-
-class TestUpstageEnvCatalog:
- """The dashboard/desktop Providers page lists only OPTIONAL_ENV_VARS keys
- whose category is "provider". Without these entries UPSTAGE_API_KEY /
- UPSTAGE_BASE_URL never reach the frontend and Upstage stays invisible even
- though EnvPage.tsx has a matching PROVIDER_GROUPS prefix.
- """
-
- def test_optional_env_vars_include_upstage(self):
- from hermes_cli.config import OPTIONAL_ENV_VARS
-
- assert "UPSTAGE_API_KEY" in OPTIONAL_ENV_VARS
- assert OPTIONAL_ENV_VARS["UPSTAGE_API_KEY"]["category"] == "provider"
- assert OPTIONAL_ENV_VARS["UPSTAGE_API_KEY"]["password"] is True
- assert OPTIONAL_ENV_VARS["UPSTAGE_API_KEY"]["url"]
-
- assert "UPSTAGE_BASE_URL" in OPTIONAL_ENV_VARS
- assert OPTIONAL_ENV_VARS["UPSTAGE_BASE_URL"]["category"] == "provider"
- assert OPTIONAL_ENV_VARS["UPSTAGE_BASE_URL"]["password"] is False
-
-
-class TestUpstageConfigProviderWins:
- """End-to-end: an explicit config provider must beat env auto-detect.
-
- Mirrors the display logic in `hermes_cli/main.py` (cmd_model): read
- `model.provider`, resolve it, and only fall back to auto-detect when that
- resolution fails. With a stray DEEPSEEK_API_KEY present (the user's case),
- upstage must still win because it is configured explicitly.
- """
-
- def test_explicit_upstage_beats_stray_deepseek_key(self, monkeypatch):
- from hermes_cli.providers import resolve_provider_full
-
- monkeypatch.setenv("DEEPSEEK_API_KEY", "junk")
- monkeypatch.setenv("UPSTAGE_API_KEY", "up-test-key")
-
- config_provider = "upstage" # from config model.provider
- active = ""
- if config_provider and config_provider != "auto":
- adef = resolve_provider_full(config_provider, {}, [])
- active = adef.id if adef is not None else ""
-
- assert active == "upstage", (
- "explicit config provider should resolve to upstage, not fall "
- "through to deepseek auto-detect"
- )
diff --git a/tests/hermes_cli/test_urllib_security.py b/tests/hermes_cli/test_urllib_security.py
index bc84c86286a..04d609672d4 100644
--- a/tests/hermes_cli/test_urllib_security.py
+++ b/tests/hermes_cli/test_urllib_security.py
@@ -16,7 +16,6 @@ import pytest
from hermes_cli.urllib_security import (
SafeCredentialRedirectHandler,
open_credentialed_url,
- url_origin,
)
@@ -443,6 +442,7 @@ def test_resolved_https_context_prefers_configured_ca_bundle(monkeypatch, tmp_pa
assert seen == [str(ca_bundle)]
def test_resolved_https_context_uses_certifi_on_macos(monkeypatch):
import certifi
import hermes_cli.urllib_security as urllib_security
@@ -455,7 +455,6 @@ def test_resolved_https_context_uses_certifi_on_macos(monkeypatch):
seen.append(cafile)
return expected_context
- monkeypatch.setattr(urllib_security.sys, "platform", "darwin")
monkeypatch.setattr(certifi, "where", lambda: "/certifi/cacert.pem")
monkeypatch.setattr(ssl, "create_default_context", create_default_context)
@@ -463,6 +462,7 @@ def test_resolved_https_context_uses_certifi_on_macos(monkeypatch):
assert seen == ["/certifi/cacert.pem"]
def test_invalid_ca_bundle_falls_back_to_certifi_on_macos(monkeypatch, tmp_path):
import certifi
import hermes_cli.urllib_security as urllib_security
@@ -477,7 +477,6 @@ def test_invalid_ca_bundle_falls_back_to_certifi_on_macos(monkeypatch, tmp_path)
return expected_context
monkeypatch.setenv("HERMES_CA_BUNDLE", str(missing_bundle))
- monkeypatch.setattr(urllib_security.sys, "platform", "darwin")
monkeypatch.setattr(certifi, "where", lambda: "/certifi/cacert.pem")
monkeypatch.setattr(ssl, "create_default_context", create_default_context)
@@ -485,11 +484,11 @@ def test_invalid_ca_bundle_falls_back_to_certifi_on_macos(monkeypatch, tmp_path)
assert seen == ["/certifi/cacert.pem"]
def test_resolved_https_context_keeps_stdlib_default_off_macos(monkeypatch):
import hermes_cli.urllib_security as urllib_security
_clear_ca_bundle_env(monkeypatch)
- monkeypatch.setattr(urllib_security.sys, "platform", "linux")
assert urllib_security._resolved_https_context() is None
diff --git a/tests/hermes_cli/test_ux_messages_auth_config.py b/tests/hermes_cli/test_ux_messages_auth_config.py
deleted file mode 100644
index fea9795827f..00000000000
--- a/tests/hermes_cli/test_ux_messages_auth_config.py
+++ /dev/null
@@ -1,330 +0,0 @@
-"""Message contracts for the config-parse and sign-in failure copy (CLI startup UX campaign).
-
-Every test asserts the contract (plain lead sentence + the exact command pointer, raw exception
-kept out of the lead) rather than the whole string.
-"""
-
-from __future__ import annotations
-
-import logging
-from types import SimpleNamespace
-
-import httpx
-import pytest
-import yaml
-
-
-def _yaml_error(text: str = "model:\n default: x\n bad: [unterminated\n") -> Exception:
- try:
- yaml.safe_load(text)
- except yaml.YAMLError as exc:
- return exc
- raise AssertionError("expected a YAML error")
-
-
-# ── cli-03: config.yaml parse failure at startup ─────────────────────────────────────────────
-
-
-class TestConfigParseWarning:
- @pytest.mark.parametrize("fallback", ["defaults", "last-known-good-backup", "refuse-write"])
- def test_warning_names_repair_commands_and_line(self, tmp_path, monkeypatch, capsys, fallback):
- from hermes_cli import config as config_mod
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- config_mod._CONFIG_PARSE_WARNED.clear()
- config_path = tmp_path / "config.yaml"
- config_path.write_text("model:\n default: x\n bad: [unterminated\n", encoding="utf-8")
-
- config_mod._warn_config_parse_failure(config_path, _yaml_error(), fallback=fallback)
-
- err = capsys.readouterr().err
- assert "formatting error" in err
- assert "line " in err
- assert "`hermes config edit`" in err and "`hermes config check`" in err
- assert "IGNORED" not in err and "LAST KNOWN GOOD" not in err
- # The raw PyYAML text is demoted to a Details line, never the lead sentence.
- lead = err.strip().splitlines()[0]
- assert "expected <block end>" not in lead.split("Details:")[0]
-
-
-# ── cli-33: refuse-to-write and non-interactive startup guard ────────────────────────────────
-
-
-class TestConfigGuardCopy:
- def test_require_parseable_user_config_says_what_happened_and_how_to_fix(self, tmp_path, monkeypatch):
- from hermes_cli import config as config_mod
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / "config.yaml").write_text("model: [unterminated\n", encoding="utf-8")
-
- with pytest.raises(config_mod.InvalidUserConfigError) as excinfo:
- config_mod.require_parseable_user_config()
-
- msg = str(excinfo.value)
- assert msg.startswith("Hermes stopped because your settings file")
- assert "`hermes config edit`" in msg and "--ignore-user-config" in msg
- assert "non-interactive" not in msg and "built-in defaults" not in msg
- assert "Details:" in msg
-
- def test_refuse_write_names_repair_commands_and_absolute_backup_dir(self, tmp_path, monkeypatch):
- from hermes_cli import config as config_mod
- from hermes_constants import display_hermes_home
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- config_mod._CONFIG_PARSE_WARNED.clear()
- (tmp_path / "config.yaml").write_text("model: [unterminated\n", encoding="utf-8")
-
- with pytest.raises(RuntimeError) as excinfo:
- config_mod.require_readable_config_before_write()
-
- msg = str(excinfo.value)
- assert "this change was not saved" in msg
- assert "`hermes config edit`" in msg and "`hermes config check`" in msg
- assert f"{display_hermes_home()}/backups/config/" in msg
- assert not msg.startswith("Refusing")
-
-
-# ── cli-04: no provider configured ───────────────────────────────────────────────────────────
-
-
-def test_no_provider_configured_points_at_model_login_and_auth_add(monkeypatch, tmp_path):
- from hermes_cli.auth import AuthError, resolve_provider
- from hermes_constants import display_hermes_home
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda env=None: False)
-
- with pytest.raises(AuthError) as excinfo:
- resolve_provider("auto")
-
- msg = str(excinfo.value)
- assert excinfo.value.code == "no_provider_configured"
- assert "`hermes model`" in msg and "`/login`" in msg and "`hermes auth add <provider>`" in msg
- assert "~/.hermes/.env" not in msg or display_hermes_home() == "~/.hermes"
- assert f"{display_hermes_home()}/.env" in msg
- assert "inference provider" not in msg
-
-
-# ── cli-07: Nous device-code sign-in failures ────────────────────────────────────────────────
-
-
-class TestSignInFailureCopy:
- @pytest.mark.parametrize("code, pointer", [
- ("expired_token", "`hermes portal`"),
- ("access_denied", "`hermes model`"),
- ])
- def test_poll_error_codes_map_to_plain_copy(self, code, pointer):
- from hermes_cli import auth_device_flow
-
- class _Client:
- def post(self, url, data=None):
- request = httpx.Request("POST", url)
- return httpx.Response(400, json={"error": code, "error_description": "server text"}, request=request)
-
- with pytest.raises(RuntimeError) as excinfo:
- auth_device_flow._poll_for_token(
- client=_Client(), portal_base_url="https://portal.nousresearch.com", client_id="hermes-cli",
- device_code="device", expires_in=5, poll_interval=1)
-
- msg = str(excinfo.value)
- assert not msg.startswith(code)
- assert "`hermes portal`" in msg and pointer in msg
-
- def test_network_failure_names_host_and_retry_command(self):
- from hermes_cli.auth_error_copy import sign_in_failure_lines
-
- lines = sign_in_failure_lines(httpx.ConnectError("[Errno -2] Name or service not known"),
- service_host="portal.nousresearch.com")
-
- assert lines[0].startswith("Could not sign in")
- assert "portal.nousresearch.com" in lines[0] and "`hermes portal`" in lines[0]
- assert "Errno" not in lines[0]
- assert any(line.strip().startswith("Details:") for line in lines[1:])
-
- def test_run_login_prints_plain_copy_not_raw_exception(self, capsys):
- from hermes_cli.model_setup_flows_common import _run_login
-
- def _boom(*_a, **_k):
- raise httpx.ConnectError("[Errno -2] Name or service not known")
-
- assert _run_login(_boom) is False
- out = capsys.readouterr().out
- assert "Could not sign in" in out
- assert not out.lstrip().startswith("Login failed:")
-
- def test_login_nous_prints_plain_copy(self, monkeypatch, capsys):
- from hermes_cli import auth_nous
-
- def _boom(**_k):
- raise httpx.ConnectError("[Errno -2] Name or service not known")
-
- monkeypatch.setattr(auth_nous, "_offer_shared_nous_import", lambda *_a, **_k: None, raising=False)
- monkeypatch.setattr("hermes_cli.auth._nous_device_code_login", _boom)
- args = SimpleNamespace(timeout=1.0, portal_url=None, inference_url=None, client_id=None, scope=None,
- no_browser=True, insecure=False, ca_bundle=None)
- from hermes_cli.auth import PROVIDER_REGISTRY
-
- with pytest.raises(SystemExit) as excinfo:
- auth_nous._login_nous(args, PROVIDER_REGISTRY["nous"])
-
- assert excinfo.value.code == 1
- out = capsys.readouterr().out
- assert "Could not sign in" in out and "`hermes portal`" in out
- assert "Login failed:" not in out
-
-
-# ── cli-25: auth refresh / unknown provider ──────────────────────────────────────────────────
-
-
-class TestAuthCommandsCopy:
- def test_unknown_provider_offers_did_you_mean_and_pointers(self, monkeypatch):
- from hermes_cli import auth_commands
-
- monkeypatch.setattr(auth_commands, "_configured_provider_entry", lambda _p: None)
- with pytest.raises(SystemExit) as excinfo:
- auth_commands.auth_add_command(SimpleNamespace(provider="openai"))
-
- msg = str(excinfo.value)
- assert "Unknown provider 'openai'" in msg
- assert "Did you mean" in msg and "openai-codex" in msg
- assert "`hermes auth`" in msg and "`hermes model`" in msg
-
- def test_refresh_failure_names_relogin_command(self, monkeypatch):
- from hermes_cli import auth_commands
-
- from agent.credential_pool import AUTH_TYPE_OAUTH
-
- matched = SimpleNamespace(id="abc", label="device-code", source="device_code", provider="nous",
- auth_type=AUTH_TYPE_OAUTH, refresh_token="rt", last_status="ok")
-
- class _Pool:
- def entries(self):
- return [matched]
-
- def try_refresh_matching(self, credential_id=None):
- matched.last_status = "refresh_failed"
- return None
-
- monkeypatch.setattr(auth_commands, "load_pool", lambda _provider: _Pool())
- with pytest.raises(SystemExit) as excinfo:
- auth_commands.auth_refresh_command(SimpleNamespace(provider="nous", target=None))
-
- msg = str(excinfo.value)
- assert "refresh_failed" not in msg and "status now" not in msg
- assert "`hermes auth add nous --type oauth`" in msg
-
-
-# ── cli-24: /model onto a provider without credentials ───────────────────────────────────────
-
-
-def test_creds_for_target_provider_names_auth_add_and_model(monkeypatch):
- from hermes_cli import model_switch
-
- st = model_switch._Switch(
- raw_input="kimi-coding:x", current_provider="openrouter", current_model="m", current_base_url="",
- current_api_key="", is_global=False, explicit_provider="", user_providers=None, custom_providers=None,
- target_provider="kimi-coding", provider_label="Kimi")
-
- def _fail(**_k):
- raise RuntimeError("KIMI_API_KEY missing (raw resolver text)")
-
- monkeypatch.setattr(st, "resolve_runtime", _fail, raising=False)
- result = model_switch._creds_for_switched_provider(st)
-
- assert result is not None and result.success is False
- msg = result.error_message
- assert msg.startswith("Kimi is not connected")
- assert "`hermes auth add kimi-coding`" in msg and "/model" in msg
- assert "Could not resolve credentials" not in msg
- assert "Details:" in msg
-
-
-# ── cli-16: setup wizard provider step failure ───────────────────────────────────────────────
-
-
-class TestProviderSetupFailureCopy:
- def test_setup_provider_step_reports_reason_and_that_nothing_changed(self, monkeypatch, capsys, tmp_path):
- from hermes_cli import setup as setup_mod
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
-
- def _boom(*_a, **_k):
- raise httpx.ConnectError("[Errno -2] Name or service not known")
-
- monkeypatch.setattr("hermes_cli.main.select_provider_and_model", _boom)
- monkeypatch.setattr(setup_mod, "print_header", lambda *_a, **_k: None)
- monkeypatch.setattr(setup_mod, "_info", lambda *_a, **_k: None)
- monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
- setup_mod.setup_model_provider({}, quick=True)
-
- out = capsys.readouterr().out
- assert "Could not finish connecting a provider" in out
- assert "internet" in out
- assert "not changed" in out or "Nothing was saved" in out
- assert "hermes model" in out
- assert "encountered an error" not in out and "Errno" not in out.split("Details:")[0]
-
- def test_quick_setup_error_hook_uses_same_copy(self, capsys):
- from hermes_cli.auth_error_copy import provider_setup_failure_lines
-
- lines = provider_setup_failure_lines(RuntimeError("keyring locked"), retry_command="hermes portal")
- assert lines[0].startswith("Could not finish connecting a provider")
- assert "hermes portal" in " ".join(lines)
- assert any(line.strip().startswith("Details:") for line in lines)
-
-
-class TestRunLoginProviderAwareCopy:
- def test_minimax_failure_names_minimax_retry_not_portal(self, capsys):
- from hermes_cli.auth import PROVIDER_REGISTRY
- from hermes_cli.model_setup_flows_common import _run_login
-
- def _boom(*_a, **_k):
- raise httpx.ConnectError("[Errno -2] Name or service not known")
-
- assert _run_login(_boom, SimpleNamespace(), PROVIDER_REGISTRY["minimax-oauth"]) is False
- out = capsys.readouterr().out
- assert "hermes auth add minimax-oauth" in out
- assert "hermes portal" not in out and "portal.nousresearch.com" not in out
- assert "hermes login" not in out
-
- def test_nous_failure_keeps_portal_retry(self, capsys):
- from hermes_cli.auth import PROVIDER_REGISTRY
- from hermes_cli.model_setup_flows_common import _run_login
-
- def _boom(*_a, **_k):
- raise httpx.ConnectError("boom")
-
- assert _run_login(_boom, SimpleNamespace(), PROVIDER_REGISTRY["nous"]) is False
- out = capsys.readouterr().out
- assert "hermes portal" in out and "portal.nousresearch.com" in out
-
- def test_silent_nonzero_system_exit_still_tells_user_how_to_retry(self, capsys):
- from hermes_cli.auth import PROVIDER_REGISTRY
- from hermes_cli.model_setup_flows_common import _run_login
-
- def _quiet_exit(*_a, **_k):
- raise SystemExit(1)
-
- assert _run_login(_quiet_exit, SimpleNamespace(), PROVIDER_REGISTRY["openai-codex"]) is False
- out = capsys.readouterr().out
- assert "Sign-in did not complete" in out and "hermes auth add openai-codex" in out
-
- def test_system_exit_with_message_surfaces_the_message(self, capsys):
- from hermes_cli.model_setup_flows_common import _run_login
-
- def _exit_msg(*_a, **_k):
- raise SystemExit("token endpoint returned 400")
-
- assert _run_login(_exit_msg) is False
- out = capsys.readouterr().out
- assert "token endpoint returned 400" in out and "hermes model" in out
-
- def test_cancel_codes_stay_a_single_cancel_line(self, capsys):
- from hermes_cli.model_setup_flows_common import _run_login
-
- def _cancel(*_a, **_k):
- raise SystemExit(130)
-
- assert _run_login(_cancel) is False
- out = capsys.readouterr().out
- assert "cancelled" in out.lower() and "did not complete" not in out
diff --git a/tests/hermes_cli/test_ux_messages_chat_sessions.py b/tests/hermes_cli/test_ux_messages_chat_sessions.py
index 2f1f4311680..5bee4576a25 100644
--- a/tests/hermes_cli/test_ux_messages_chat_sessions.py
+++ b/tests/hermes_cli/test_ux_messages_chat_sessions.py
@@ -6,8 +6,7 @@ Each test asserts the CONTRACT (what happened + the exact command pointer, raw d
import pytest
-from hermes_cli.active_sessions import session_already_owned_message
-from hermes_cli.cli_chat_error_copy import agent_init_failure_message, chat_error_response
+from hermes_cli.cli_chat_error_copy import chat_error_response
from hermes_cli.cli_unknown_command import unknown_command_lines
@@ -35,10 +34,6 @@ def test_chat_error_response_leads_with_plain_copy_and_pointer(exc, pointer, abs
assert "Details: " in text and str(exc) in text
-def test_chat_error_response_names_provider_and_model():
- text = chat_error_response(Exception("HTTP 404: model not found"), provider="openrouter", model="foo/bar")
- assert "foo/bar" in text.splitlines()[0]
- assert "openrouter" in text.splitlines()[0]
def test_chat_error_response_accepts_plain_string_summary():
@@ -62,39 +57,14 @@ def test_chat_error_response_returns_site_copy_verbatim_instead_of_double_wrappi
# ── cli-06: agent could not be built on first message ──────────────────────
-def test_agent_init_failure_message_says_message_not_sent_and_points_to_doctor():
- exc = RuntimeError("Unsupported api_mode 'weird' for provider x\nsecond line of traceback noise " + "x" * 300)
- text = agent_init_failure_message(exc)
- assert "not sent" in text
- assert "hermes doctor" in text and "/model" in text
- assert not text.startswith("Failed to initialize agent")
- assert "second line" not in text, "only the first line of the exception is shown"
- assert len(text) < 400, "the exception summary is truncated"
# ── cli-11: session held by another window ─────────────────────────────────
-def test_owned_message_first_line_is_plain_and_details_follow():
- message = session_already_owned_message("session-1", {
- "surface": "desktop", "pid": 123, "started_at": 1,
- })
- first, *rest = message.splitlines()
- assert first == ("This chat is open in another Hermes window/terminal. "
- "Use it there, or start a new chat here.")
- for jargon in ("lease", "pid", "owner", "takeover"):
- assert jargon not in first.lower()
- assert rest and rest[0].startswith("Details: ")
- assert "desktop" in rest[0]
# ── cli-30: hermes sessions with a bad id / unopenable DB ──────────────────
-def test_sessions_not_found_points_to_list(capsys):
- from hermes_cli.sessions_cmd import _not_found
- assert _not_found("abc") == 1
- out = capsys.readouterr().out
- assert "No session 'abc'" in out
- assert "hermes sessions list" in out
def test_sessions_db_open_failure_points_to_repair(monkeypatch, capsys):
@@ -118,8 +88,6 @@ def test_sessions_db_open_failure_points_to_repair(monkeypatch, capsys):
out = capsys.readouterr().out
assert code == 1
assert "hermes sessions repair" in out
- assert out.splitlines()[0].startswith("Could not open your session history database")
- assert "Details: database disk image is malformed" in out
# ── cli-31: unknown slash command ──────────────────────────────────────────
diff --git a/tests/hermes_cli/test_ux_messages_gateway_profiles.py b/tests/hermes_cli/test_ux_messages_gateway_profiles.py
deleted file mode 100644
index b0892c5da38..00000000000
--- a/tests/hermes_cli/test_ux_messages_gateway_profiles.py
+++ /dev/null
@@ -1,120 +0,0 @@
-"""Invariant tests for the user-facing copy of gateway/profile/update-lock failures.
-
-Contract, not snapshots: each message leads with plain words (never a raw exception), names the
-next command, and every ``hermes <sub> <cmd>`` it cites is a registered subcommand.
-"""
-
-import subprocess
-from types import SimpleNamespace
-
-import pytest
-
-from hermes_cli import gateway as gateway_cli
-from hermes_cli import profiles
-from hermes_cli.update_lock import UpdateHolder, describe_holder
-
-
-# --- cli-05: gateway start/stop/restart failures leave gateway_command() as guidance ------------
-
-
-def _run_gateway_command_raising(monkeypatch, capsys, exc):
- monkeypatch.setattr(gateway_cli, "_gateway_command_inner", lambda args: (_ for _ in ()).throw(exc))
- with pytest.raises(SystemExit) as info:
- gateway_cli.gateway_command(SimpleNamespace(gateway_command="start"))
- assert info.value.code == 1
- return capsys.readouterr().out
-
-
-def test_systemctl_failure_is_explained_not_tracebacked(monkeypatch, capsys):
- exc = subprocess.CalledProcessError(1, ["systemctl", "--user", "start", "hermes-gateway"])
- out = _run_gateway_command_raising(monkeypatch, capsys, exc)
- assert not out.lstrip().startswith("Command '")
- assert "hermes gateway status --deep" in out
- assert "hermes gateway install --force" in out
- assert "journalctl" in out
- # The raw detail survives as a secondary line, not the lead sentence.
- assert "Details:" in out
-
-
-def test_missing_systemctl_points_at_foreground_run(monkeypatch, capsys):
- def fake_run(cmd, **kwargs):
- raise FileNotFoundError("systemctl")
-
- monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
- with pytest.raises(RuntimeError) as info:
- gateway_cli._run_systemctl(["start", "hermes-gateway"])
- out = _run_gateway_command_raising(monkeypatch, capsys, info.value)
- assert "hermes gateway run" in out
- assert "systemd" in out
- assert not out.lstrip().startswith("systemctl is not available")
-
-
-# --- cli-15: already-running guard and no-backend copy ---------------------------------------
-
-
-def test_existing_gateway_guard_says_bots_are_online_and_names_status(monkeypatch, capsys):
- import gateway.status as status_mod
-
- monkeypatch.setattr(gateway_cli, "_running_under_gateway_supervisor", lambda: False)
- monkeypatch.setattr(status_mod, "get_running_pid", lambda: 12345)
- with pytest.raises(SystemExit):
- gateway_cli._guard_existing_gateway_process_conflict()
- out = capsys.readouterr().out
- assert "12345" in out
- assert "online" in out
- for cmd in ("hermes gateway status", "hermes gateway restart", "hermes gateway stop"):
- assert cmd in out
- assert "Another gateway instance" not in out
-
-
[email protected]("subcommand", ["start", "uninstall"])
-def test_unsupported_platform_copy_says_what_is_unsupported(subcommand):
- _code, *lines = gateway_cli._NO_BACKEND_MESSAGES[(subcommand, "unsupported")]
- text = "\n".join(lines)
- assert text != "Not supported on this platform."
- assert "background service" in text
- assert "hermes gateway run" in text or subcommand == "uninstall"
-
-
-# --- cli-13 / cli-14: profile name errors -----------------------------------------------------
-
-
-def test_invalid_profile_name_explains_rule_in_words_with_example():
- with pytest.raises(ValueError) as info:
- profiles.validate_profile_name("My Work")
- msg = str(info.value)
- assert "Must match" not in msg and "[a-z0-9]" not in msg
- assert "lowercase" in msg
- assert "my-work" in msg
- assert "hermes profile create my-work" in msg
-
-
-def test_existing_profile_error_offers_use_and_list(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- profiles.create_profile("work", no_alias=True, no_skills=True)
- with pytest.raises(FileExistsError) as info:
- profiles.create_profile("work", no_alias=True, no_skills=True)
- msg = str(info.value)
- assert "already exists at" not in msg
- assert "hermes profile use work" in msg
- assert "hermes profile list" in msg
-
-
-def test_missing_profile_error_points_at_list(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- with pytest.raises(FileNotFoundError) as info:
- profiles.delete_profile("wrk")
- msg = str(info.value)
- assert "No profile named 'wrk'" in msg
- assert "hermes profile list" in msg
-
-
-# --- cli-28: concurrent update refusal ---------------------------------------------------------
-
-
-def test_describe_holder_avoids_jargon_and_names_next_steps():
- message = describe_holder(UpdateHolder(pid=4242, age_seconds=190))
- assert "4242" in message and "3m 10s" in message
- assert "PID" not in message and "checkout" not in message
- assert "hermes logs" in message
- assert "hermes update" in message
diff --git a/tests/hermes_cli/test_ux_messages_startup.py b/tests/hermes_cli/test_ux_messages_startup.py
index 27cd984aed6..f0ef606fd07 100644
--- a/tests/hermes_cli/test_ux_messages_startup.py
+++ b/tests/hermes_cli/test_ux_messages_startup.py
@@ -7,8 +7,7 @@ profile name explains the rule; missing optional dependencies point at ``hermes
import io
import sys
-from contextlib import redirect_stderr, redirect_stdout
-from types import SimpleNamespace
+from contextlib import redirect_stderr
import pytest
@@ -38,11 +37,6 @@ def test_unknown_subcommand_names_typo_suggests_closest_and_hides_choice_list():
assert "invalid choice" not in text
-def test_unknown_subcommand_without_close_match_still_points_at_help():
- text = _parse_error(["zzqx"])
- assert "'zzqx' is not a `hermes` command" in text
- assert "Did you mean" not in text
- assert "hermes --help" in text
def test_nested_group_typo_names_the_group_and_suggests():
@@ -51,16 +45,8 @@ def test_nested_group_typo_names_the_group_and_suggests():
assert "Did you mean:" in text and "status" in text
-def test_non_choice_errors_keep_argparse_usage_line():
- text = _parse_error(["--no-such-flag"])
- assert text.startswith("usage: hermes")
- assert "--no-such-flag" in text
-def test_top_level_usage_hides_subcommand_brace_list():
- parser, _sub, _chat = build_top_level_parser()
- assert "{chat" not in parser.format_usage()
- assert "<command>" in parser.format_usage()
def test_invalid_profile_flag_value_explains_rule_and_exits(monkeypatch):
@@ -71,10 +57,6 @@ def test_invalid_profile_flag_value_explains_rule_and_exits(monkeypatch):
with redirect_stderr(err), pytest.raises(SystemExit) as exc:
_main._apply_profile_override()
assert exc.value.code == 2
- text = err.getvalue()
- assert "'Work Bot' is not a valid profile name" in text
- assert "hermes profile list" in text
- assert "Must match" not in text
def test_pytest_style_dash_p_is_still_ignored(monkeypatch):
@@ -109,55 +91,9 @@ def test_invalid_dash_p_after_a_subcommand_is_left_to_that_subcommand(monkeypatc
assert _main._scan_profile_flag(sys.argv[1:]) == (None, 0, None)
-def test_bare_continue_with_no_session_names_the_next_step(monkeypatch):
- from hermes_cli import main as _main
-
- monkeypatch.setattr(_main, "_latest_session_id", lambda _tui: None)
- monkeypatch.setattr(
- "hermes_cli.terminal_breadcrumbs.resolve_breadcrumb_session", lambda: None, raising=False
- )
- out = io.StringIO()
- args = SimpleNamespace(continue_last=True, resume=None, create_if_missing=False)
- with redirect_stdout(out), redirect_stderr(out), pytest.raises(SystemExit):
- _main._resolve_continue_arg(args, use_tui=False)
- text = out.getvalue()
- assert "hermes sessions list" in text
- assert "No previous CLI session" in text
-
-
-def test_model_picker_does_not_warn_about_missing_provider(monkeypatch, capsys):
- from hermes_cli import main as _main
- from hermes_cli.auth import AuthError
-
- def _raise(_slug):
- raise AuthError("nothing configured", code="no_provider_configured")
-
- monkeypatch.setattr("hermes_cli.auth.resolve_provider", _raise)
- active = _main._resolve_active_provider({}, {}, "auto", {})
- out = capsys.readouterr().out
- assert active is None
- assert "Warning" not in out
- assert "Falling back to auto provider detection" not in out
- assert "pick one below" in out
-def test_missing_dashboard_deps_point_at_hermes_update():
- from hermes_cli.main_dep_hints import missing_optional_deps_message
- text = missing_optional_deps_message("dashboard", "its web-server packages", "all")
- assert "hermes update" in text
- assert "-m pip install -e '.[all]'" in text
- assert "metadata" not in text
-def test_missing_node_message_names_cli_fallback(monkeypatch, capsys):
- from hermes_cli import main_tui_launch as _tui
- monkeypatch.setattr("hermes_constants.find_node_executable", lambda _b: None)
- monkeypatch.setattr("hermes_cli.dep_ensure.ensure_dependency", lambda _n: False, raising=False)
- monkeypatch.delenv("HERMES_NODE", raising=False)
- with pytest.raises(SystemExit):
- _tui._tui_node_bin("node")
- text = capsys.readouterr().out
- assert "hermes --cli" in text
- assert "Node.js" in text
diff --git a/tests/hermes_cli/test_venv_holder_classifier.py b/tests/hermes_cli/test_venv_holder_classifier.py
index ebba2f4d8c1..64ffcedb9da 100644
--- a/tests/hermes_cli/test_venv_holder_classifier.py
+++ b/tests/hermes_cli/test_venv_holder_classifier.py
@@ -3,7 +3,6 @@
import pytest
from hermes_cli.update_cmd import (
- _format_venv_python_holders_message,
_hermes_holder_subcommand,
)
@@ -41,30 +40,3 @@ class TestHolderSubcommand:
assert _hermes_holder_subcommand(cmdline) == expected
-class TestHolderMessage:
- def _msg(self, cmdline):
- return _format_venv_python_holders_message([(4242, "python.exe", cmdline)])
-
- def test_dashboard_not_labeled_desktop_backend(self):
- message = self._msg(r"C:\v\Scripts\python.exe -m hermes_cli.main dashboard")
- assert "close the desktop app" not in message.lower()
- assert "hermes dashboard" in message
-
- def test_preserve_cache_not_labeled_serve(self):
- message = self._msg(r"python -m hermes_cli.main kanban --preserve-cache")
- holder_line = next(l for l in message.splitlines() if "PID 4242" in l)
- # the holder LINE gets no serve/desktop hint (generic footer text
- # legitimately mentions the desktop app)
- assert "←" not in holder_line
-
- def test_serve_gets_backend_hint(self):
- message = self._msg(r"python -m hermes_cli.main serve --host 127.0.0.1 --port 0")
- assert "Hermes backend" in message
-
- def test_gateway_hint(self):
- message = self._msg(r"python -m hermes_cli.main gateway run")
- assert "← gateway" in message
-
- def test_unknown_argv_gets_no_hint(self):
- message = self._msg(r"python -c import this")
- assert "←" not in message
diff --git a/tests/hermes_cli/test_verify_console_scripts.py b/tests/hermes_cli/test_verify_console_scripts.py
deleted file mode 100644
index f7106d10c55..00000000000
--- a/tests/hermes_cli/test_verify_console_scripts.py
+++ /dev/null
@@ -1,69 +0,0 @@
-"""Tests for _verify_console_scripts_installed (issue #52931)."""
-
-from __future__ import annotations
-
-import textwrap
-from pathlib import Path
-from unittest.mock import patch
-
-import pytest
-from hermes_cli import main_install_repair
-
-
-def temp_pyproject(tmp_path, monkeypatch):
- pyproject = tmp_path / "pyproject.toml"
- pyproject.write_text(
- textwrap.dedent(
- """\
- [project]
- name = "fake"
- version = "0.0.0"
-
- [project.scripts]
- hermes = "hermes_cli.main:main"
- hermes-agent = "run_agent:main"
- hermes-acp = "acp_adapter.entry:main"
- """
- )
- )
- import hermes_cli.main as main_mod
-
- monkeypatch.setattr(main_mod, "PROJECT_ROOT", tmp_path)
- return tmp_path
-
-
-def fake_scripts_dir(tmp_path):
- scripts = tmp_path / "venv" / "Scripts"
- scripts.mkdir(parents=True)
- return scripts
-
-
-class TestVerifyConsoleScriptsInstalled:
- def test_no_action_when_all_shims_present(self, temp_pyproject, fake_scripts_dir):
- for name in ("hermes", "hermes-agent", "hermes-acp"):
- (fake_scripts_dir / f"{name}.exe").write_bytes(b"fake")
-
- with patch("hermes_cli.main_install_repair._is_windows", return_value=True), \
- patch("hermes_cli.main_install_repair._venv_scripts_dir", return_value=fake_scripts_dir), \
- patch("hermes_cli.main_install_repair._run_quarantined_install") as mock_install:
- from hermes_cli.main_install_repair import _verify_console_scripts_installed
-
- _verify_console_scripts_installed(["uv", "pip"], env={})
-
- mock_install.assert_not_called()
-
-
-
-
- def test_quarantine_shims_include_declared_console_scripts(
- self, temp_pyproject, fake_scripts_dir
- ):
- import hermes_cli.main as main_mod
-
- with patch("hermes_cli.main_install_repair._is_windows", return_value=True):
- names = {path.name for path in main_install_repair._hermes_exe_shims(fake_scripts_dir)}
-
- assert {"hermes.exe", "hermes-agent.exe", "hermes-acp.exe"} <= names
- assert "hermes-gateway.exe" in names
diff --git a/tests/hermes_cli/test_verify_core_dependencies.py b/tests/hermes_cli/test_verify_core_dependencies.py
index 3c5c14f043e..8fe9c1ddecd 100644
--- a/tests/hermes_cli/test_verify_core_dependencies.py
+++ b/tests/hermes_cli/test_verify_core_dependencies.py
@@ -16,10 +16,8 @@ The verification step:
from __future__ import annotations
-import subprocess
import sys
import textwrap
-from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
@@ -125,32 +123,3 @@ class TestVerifyCoreDependencies:
-class TestResolveInstallTargetPython:
- def test_uses_virtual_env_from_environment(self, tmp_path):
- """When VIRTUAL_ENV is set, the verification step must probe THAT
- venv's interpreter — not the outer Python that drove `hermes update`.
- If we probed sys.executable instead, we'd false-positive every dep
- the outer interpreter happens to lack."""
- venv_root = tmp_path / "newvenv"
- scripts = venv_root / "Scripts"
- scripts.mkdir(parents=True)
- py = scripts / "python.exe"
- py.write_text("fake")
-
- with patch("hermes_cli.main_install_repair._is_windows", return_value=True):
- from hermes_cli.main_install_repair import _resolve_install_target_python
- result = _resolve_install_target_python(
- ["uv", "pip"], env={"VIRTUAL_ENV": str(venv_root)}
- )
- assert result == py
-
- def test_returns_none_when_venv_python_missing(self, tmp_path):
- """If the path we'd point at doesn't exist (uv install failed before
- the python shim landed), return None so the verification step
- cleanly short-circuits instead of crashing on FileNotFoundError."""
- with patch("hermes_cli.main_install_repair._is_windows", return_value=True):
- from hermes_cli.main_install_repair import _resolve_install_target_python
- result = _resolve_install_target_python(
- ["uv", "pip"], env={"VIRTUAL_ENV": str(tmp_path / "does_not_exist")}
- )
- assert result is None
diff --git a/tests/hermes_cli/test_version_command.py b/tests/hermes_cli/test_version_command.py
index c3facc85180..a11e8f800ee 100644
--- a/tests/hermes_cli/test_version_command.py
+++ b/tests/hermes_cli/test_version_command.py
@@ -3,20 +3,10 @@
from unittest.mock import patch
from cli import HermesCLI
-from hermes_cli.commands import GATEWAY_KNOWN_COMMANDS, resolve_command
-def test_version_command_is_registered():
- cmd = resolve_command("version")
- assert cmd is not None
- assert cmd.name == "version"
- assert cmd.category == "Info"
- assert resolve_command("v") is cmd
-def test_version_is_gateway_known():
- assert "version" in GATEWAY_KNOWN_COMMANDS
- assert "v" in GATEWAY_KNOWN_COMMANDS
def test_process_command_version_prints_version_info():
diff --git a/tests/hermes_cli/test_vertex_model_picker.py b/tests/hermes_cli/test_vertex_model_picker.py
index ccf17e6b4ed..810b5fcefe4 100644
--- a/tests/hermes_cli/test_vertex_model_picker.py
+++ b/tests/hermes_cli/test_vertex_model_picker.py
@@ -37,7 +37,7 @@ def test_vertex_appears_when_credentials_configured():
vertex = next((p for p in providers if p["slug"] == "vertex"), None)
assert vertex is not None, "vertex should appear when credentials are configured"
assert vertex["models"], "vertex row must carry the curated model list"
- assert "google/gemini-3-pro-preview" in vertex["models"]
+ assert set(vertex["models"]) <= set(_PROVIDER_MODELS["vertex"])
def test_vertex_hidden_without_credentials():
diff --git a/tests/hermes_cli/test_vertex_provider.py b/tests/hermes_cli/test_vertex_provider.py
index 129c44a8eb3..34feffcde1a 100644
--- a/tests/hermes_cli/test_vertex_provider.py
+++ b/tests/hermes_cli/test_vertex_provider.py
@@ -10,23 +10,14 @@ from __future__ import annotations
import pytest
-
-
-
-
-
-
def test_resolve_runtime_provider_raises_autherror_when_unresolved(monkeypatch):
import agent.vertex_adapter as va
from hermes_cli import runtime_provider as rp
from hermes_cli.auth import AuthError
monkeypatch.setattr(va, "get_vertex_config", lambda: (None, None))
- with pytest.raises(AuthError) as exc:
+ with pytest.raises(AuthError):
rp.resolve_runtime_provider(requested="vertex")
- msg = str(exc.value)
- assert "OAuth2" in msg
- assert "not a static API key" in msg
def test_vertex_registered_in_provider_registry():
diff --git a/tests/hermes_cli/test_vim_mode_command.py b/tests/hermes_cli/test_vim_mode_command.py
index 86190bd2732..9036123dbca 100644
--- a/tests/hermes_cli/test_vim_mode_command.py
+++ b/tests/hermes_cli/test_vim_mode_command.py
@@ -3,7 +3,6 @@
import unittest
from types import SimpleNamespace
-from prompt_toolkit.enums import EditingMode
def _import_cli():
@@ -33,13 +32,6 @@ class TestVimModeLabel(unittest.TestCase):
self.assertEqual(cli_mod.HermesCLI._vim_mode_label(stub), "REPLACE")
-class TestNoSlashCommand(unittest.TestCase):
- """vim_mode is a config key only: no /vim command is registered."""
-
- def test_vim_not_in_command_registry(self):
- from hermes_cli.commands import COMMAND_REGISTRY
-
- self.assertNotIn("vim", {c.name for c in COMMAND_REGISTRY})
if __name__ == "__main__":
diff --git a/tests/hermes_cli/test_voice_wrapper.py b/tests/hermes_cli/test_voice_wrapper.py
index d8f936c1713..c6d2264a96f 100644
--- a/tests/hermes_cli/test_voice_wrapper.py
+++ b/tests/hermes_cli/test_voice_wrapper.py
@@ -15,18 +15,6 @@ import json
import pytest
-class TestPublicAPI:
- def test_gateway_symbols_importable(self):
- """Match the exact import shape tui_gateway/server.py uses."""
- from hermes_cli.voice import (
- speak_text,
- start_recording,
- stop_and_transcribe,
- )
-
- assert callable(start_recording)
- assert callable(stop_and_transcribe)
- assert callable(speak_text)
class TestNormalizeVoiceRecordKeyForPromptToolkit:
diff --git a/tests/hermes_cli/test_web_analytics_corrupt_store.py b/tests/hermes_cli/test_web_analytics_corrupt_store.py
index d2214be81f7..0f3d02dc4e1 100644
--- a/tests/hermes_cli/test_web_analytics_corrupt_store.py
+++ b/tests/hermes_cli/test_web_analytics_corrupt_store.py
@@ -43,7 +43,6 @@ def test_corrupt_store_polls_return_status_and_warn_once_per_interval(tmp_path,
for resp in (first, second, third):
assert resp.status_code == 503
assert resp.json()["detail"]["error"] == "state_db_corrupt"
- assert "hermes doctor" in resp.json()["detail"]["message"]
# Only the dashboard's own warning counts: hermes_state logs an unrelated
# once-per-process SQLite-version advisory on some interpreters (CI's 3.50.4).
warnings = [
diff --git a/tests/hermes_cli/test_web_chat_ws_errors.py b/tests/hermes_cli/test_web_chat_ws_errors.py
deleted file mode 100644
index 1a79d035a0a..00000000000
--- a/tests/hermes_cli/test_web_chat_ws_errors.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Copy contract for dashboard chat start failures (``/api/pty`` close 1011).
-
-The terminal pane used to show the raw exception (``Chat unavailable: [Errno 2]
-No such file or directory: 'node'``, ``Chat unavailable: 1``, or an empty
-``Chat unavailable:`` for a full registry). Each failure must now say what
-happened and what to do, with no errno or exception class in the lead.
-"""
-
-from fastapi import HTTPException
-
-from hermes_cli.pty_session import RegistryFull
-from hermes_cli.web_routers.chat_ws_errors import chat_start_failure_message
-
-
-def test_registry_full_names_the_fix_and_carries_a_message():
- exc = RegistryFull()
- assert str(exc) # was empty before; the SPA printed "Chat unavailable:"
- msg = chat_start_failure_message(exc)
- assert "too many chat terminals" in msg
- assert "Start new session" in msg
-
-
-def test_missing_node_points_at_installing_node_not_errno():
- for exc in (FileNotFoundError(2, "No such file or directory", "node"), SystemExit(1)):
- msg = chat_start_failure_message(exc)
- assert "Node" in msg and "nodejs.org" in msg
- assert "Errno" not in msg and "SystemExit" not in msg
- assert not msg.endswith(": 1")
-
-
-def test_unknown_profile_keeps_detail_and_adds_next_step():
- msg = chat_start_failure_message(HTTPException(status_code=404, detail="Profile 'nope' not found"))
- assert msg.startswith("Chat could not start: Profile 'nope' not found.")
- assert "profile" in msg.lower()
diff --git a/tests/hermes_cli/test_web_oauth_dispatch.py b/tests/hermes_cli/test_web_oauth_dispatch.py
index 097acb7e034..36f800d5033 100644
--- a/tests/hermes_cli/test_web_oauth_dispatch.py
+++ b/tests/hermes_cli/test_web_oauth_dispatch.py
@@ -21,14 +21,11 @@ The fix:
These tests pin the corrected behavior.
"""
-import asyncio
import json
import time
-from datetime import datetime, timezone
from unittest.mock import patch
import httpx
-import pytest
from fastapi.testclient import TestClient
from hermes_cli.web_server import _SESSION_TOKEN, app
@@ -166,7 +163,6 @@ def test_minimax_start_route_honors_poller_mock_on_owning_module(tmp_path, monke
def test_oauth_provider_status_uses_profile_query(tmp_path, monkeypatch):
- from hermes_cli import web_server as ws
from hermes_constants import get_hermes_home
profile_home = _make_profile_home(tmp_path, monkeypatch)
@@ -193,7 +189,6 @@ def test_oauth_provider_status_uses_profile_query(tmp_path, monkeypatch):
def test_oauth_start_stores_profile_for_background_completion(tmp_path, monkeypatch):
- from hermes_cli import web_server as ws
_make_profile_home(tmp_path, monkeypatch)
fake_user_code_resp = {
@@ -230,7 +225,6 @@ def test_oauth_session_cannot_be_polled_or_cancelled_from_another_profile(
tmp_path, monkeypatch
):
"""A named-profile OAuth session must reject default-profile retargeting."""
- from hermes_cli import web_server as ws
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
(tmp_path / "profiles" / "worker").mkdir(parents=True)
@@ -271,54 +265,6 @@ def test_oauth_session_cannot_be_polled_or_cancelled_from_another_profile(
-def test_codex_dashboard_start_rewords_device_authorization_error(monkeypatch):
- from hermes_cli import web_server as ws
-
- before_sessions = set(_web_server_oauth._oauth_sessions)
-
- class _Resp:
- status_code = 400
- text = "Enable device code authorization"
-
- def json(self):
- return {
- "error": {
- "message": "Enable device code authorization",
- "code": "device_authorization_not_enabled",
- }
- }
-
- class _Client:
- def __init__(self, *args, **kwargs):
- pass
-
- def __enter__(self):
- return self
-
- def __exit__(self, *args):
- return False
-
- def post(self, url, **kwargs):
- assert url.endswith("/deviceauth/usercode")
- return _Resp()
-
- monkeypatch.setattr(httpx, "Client", _Client)
-
- try:
- resp = client.post(
- "/api/providers/oauth/openai-codex/start",
- headers=HEADERS,
- )
-
- assert resp.status_code == 500
- detail = resp.json()["detail"]
- assert "OpenAI rejected the device-code login request" in detail
- assert "Enable device-code authorization in OpenAI" in detail
- assert "click Login again" in detail
- assert "hermes auth" not in detail
- finally:
- for sid in set(_web_server_oauth._oauth_sessions) - before_sessions:
- _web_server_oauth._oauth_sessions.pop(sid, None)
def test_codex_dashboard_worker_stops_polling_after_cancel(tmp_path, monkeypatch):
@@ -500,42 +446,10 @@ def test_codex_worker_final_save_is_atomic_with_cancel_delete(tmp_path, monkeypa
assert sid not in _web_server_oauth._oauth_sessions
-def test_cancel_oauth_session_marks_dict_cancelled_before_popping(tmp_path, monkeypatch):
- """The DELETE endpoint must flag the session dict before removing it.
-
- A background worker holds its own reference to the same dict object;
- it can only observe cancellation if the flag is set on that shared
- object prior to (or instead of) removal from the global session map.
- """
- from hermes_cli import web_server as ws
-
- _make_profile_home(tmp_path, monkeypatch, profile="coder")
- session_id = "cancel-flag-test"
- _web_server_oauth._oauth_sessions[session_id] = {
- "session_id": session_id,
- "provider": "openai-codex",
- "flow": "device_code",
- "profile": "coder",
- "created_at": time.time(),
- "status": "pending",
- "error_message": None,
- }
- worker_ref = _web_server_oauth._oauth_sessions[session_id]
-
- resp = client.delete(
- f"/api/providers/oauth/sessions/{session_id}?profile=coder",
- headers=HEADERS,
- )
-
- assert resp.status_code == 200, resp.text
- assert resp.json() == {"ok": True, "session_id": session_id}
- assert session_id not in _web_server_oauth._oauth_sessions
- assert worker_ref["cancelled"] is True
def test_nous_dashboard_poller_preserves_effective_scope_when_token_omits_scope(monkeypatch):
from hermes_cli import auth as auth_mod
- from hermes_cli import web_server as ws
session_id = "nous-effective-scope-test"
_web_server_oauth._oauth_sessions[session_id] = {
@@ -585,25 +499,15 @@ def test_nous_dashboard_poller_preserves_effective_scope_when_token_omits_scope(
-def test_xai_oauth_listed_as_device_code_flow():
- """xAI Grok OAuth must surface in the catalog as a device-code flow."""
- resp = client.get("/api/providers/oauth", headers=HEADERS)
- assert resp.status_code == 200, resp.text
- providers = {p["id"]: p for p in resp.json()["providers"]}
- assert "xai-oauth" in providers
- assert providers["xai-oauth"]["flow"] == "device_code"
- assert "grok" in providers["xai-oauth"]["name"].lower()
def test_anthropic_dashboard_oauth_is_removed_and_external():
"""Anthropic subscription OAuth is not minted by the dashboard anymore."""
- from hermes_cli import web_server as ws
resp = client.get("/api/providers/oauth", headers=HEADERS)
assert resp.status_code == 200, resp.text
providers = {p["id"]: p for p in resp.json()["providers"]}
assert providers["anthropic"]["flow"] == "external"
- assert providers["anthropic"]["cli_command"] == "hermes auth add anthropic"
before_sessions = set(_web_server_oauth._oauth_sessions)
start_resp = client.post(
@@ -611,7 +515,6 @@ def test_anthropic_dashboard_oauth_is_removed_and_external():
headers=HEADERS,
)
assert start_resp.status_code == 400, start_resp.text
- assert "external CLI" in start_resp.text
assert "claude.ai" not in start_resp.text
submit_resp = client.post(
@@ -620,7 +523,6 @@ def test_anthropic_dashboard_oauth_is_removed_and_external():
json={"session_id": "unused", "code": "unused"},
)
assert submit_resp.status_code == 400, submit_resp.text
- assert "not supported" in submit_resp.text
assert set(_web_server_oauth._oauth_sessions) == before_sessions
@@ -645,27 +547,6 @@ def test_accounts_offers_every_oauth_provider_from_catalog():
-def test_oauth_catalog_marks_external_providers_not_disconnectable():
- """External CLI credentials are visible in Accounts but cannot be removed by Hermes."""
- resp = client.get("/api/providers/oauth", headers=HEADERS)
- assert resp.status_code == 200, resp.text
- providers = {p["id"]: p for p in resp.json()["providers"]}
-
- # Qwen: external and not auto-removable, and we don't know a clear command,
- # so it stays a manual hint with no runnable disconnect command.
- assert providers["qwen-oauth"]["flow"] == "external"
- assert providers["qwen-oauth"]["disconnectable"] is False
- assert "provider's CLI" in providers["qwen-oauth"]["disconnect_hint"]
- assert providers["qwen-oauth"]["disconnect_command"] is None
-
- # Claude Code: still not API-disconnectable, but we hand the GUI a runnable
- # command (clears the keychain entry / credentials file) so it can offer a
- # one-click "run in terminal" disconnect.
- assert providers["claude-code"]["flow"] == "external"
- assert providers["claude-code"]["disconnectable"] is False
- assert providers["claude-code"]["disconnect_hint"]
- cmd = providers["claude-code"]["disconnect_command"]
- assert cmd and ".claude/.credentials.json" in cmd
def test_external_oauth_disconnect_rejected_before_auth_mutation(monkeypatch):
@@ -679,8 +560,6 @@ def test_external_oauth_disconnect_rejected_before_auth_mutation(monkeypatch):
resp = client.delete("/api/providers/oauth/qwen-oauth", headers=HEADERS)
assert resp.status_code == 400, resp.text
- assert "cannot be disconnected automatically" in resp.text
- assert "provider's CLI" in resp.text
def test_env_sourced_oauth_status_is_not_disconnectable(monkeypatch):
@@ -693,11 +572,9 @@ def test_env_sourced_oauth_status_is_not_disconnectable(monkeypatch):
assert providers["anthropic"]["status"]["source"] == "env_var"
assert providers["anthropic"]["disconnectable"] is False
- assert providers["anthropic"]["disconnect_hint"] == "Remove the API key from Settings → Keys instead."
delete_resp = client.delete("/api/providers/oauth/anthropic", headers=HEADERS)
assert delete_resp.status_code == 400, delete_resp.text
- assert "Settings" in delete_resp.text
def test_xai_dashboard_poller_seeds_single_entry_and_clears_suppression(tmp_path, monkeypatch):
@@ -716,7 +593,6 @@ def test_xai_dashboard_poller_seeds_single_entry_and_clears_suppression(tmp_path
xai-oauth``.
"""
from hermes_cli import auth as auth_mod
- from hermes_cli import web_server as ws
from agent.credential_pool import load_pool
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -807,7 +683,6 @@ def test_status_falls_through_to_generic_dispatcher_for_catalog_only_provider():
logged-out; now they dispatch to hermes_cli.auth.get_auth_status (the
canonical slug dispatcher) so membership AND status both auto-extend.
"""
- import hermes_cli.web_server as ws
fake_status = {
"logged_in": True,
diff --git a/tests/hermes_cli/test_web_profile_delete_settlement.py b/tests/hermes_cli/test_web_profile_delete_settlement.py
index ffafca8e851..705a201fe13 100644
--- a/tests/hermes_cli/test_web_profile_delete_settlement.py
+++ b/tests/hermes_cli/test_web_profile_delete_settlement.py
@@ -76,4 +76,3 @@ def test_filesystem_remove_failure_still_reports_500(client, monkeypatch):
resp = client.delete("/api/profiles/gone")
assert resp.status_code == 500
- assert "Could not remove profile directory" in resp.json()["detail"]
diff --git a/tests/hermes_cli/test_web_profile_soul_writes.py b/tests/hermes_cli/test_web_profile_soul_writes.py
index 63b01586a68..596c0398bfc 100644
--- a/tests/hermes_cli/test_web_profile_soul_writes.py
+++ b/tests/hermes_cli/test_web_profile_soul_writes.py
@@ -12,7 +12,6 @@ small and focused on this one endpoint pair.
from __future__ import annotations
-import asyncio
import os
import stat
import sys
@@ -138,65 +137,7 @@ class TestSoulWriteDurability:
assert mode == 0o644, f"first save created SOUL.md as {oct(mode)}"
-class TestSoulIoIsOffTheEventLoop:
- """Neither half of the persona editor may run its I/O on the ASGI loop.
-
- The durability the tests above buy comes from ``atomic_write_text``, which
- fsyncs before replacing — so the save blocks for as long as the filesystem
- takes to commit. These handlers sit in the same router as the profile
- delete and describe-auto paths; the rest of that sweep is covered by
- ``tests/hermes_cli/test_web_profiles_off_loop.py``.
- """
-
- @staticmethod
- def _probe(seen, tag):
- """Record whether the caller's thread is running an event loop."""
- try:
- asyncio.get_running_loop()
- seen.append((tag, True))
- except RuntimeError:
- seen.append((tag, False))
-
- def test_get_soul_reads_off_loop(self, client, profile_dir: Path, monkeypatch):
- (profile_dir / "SOUL.md").write_text(SOUL, encoding="utf-8")
- seen: list[tuple[str, bool]] = []
- real_read_text = Path.read_text
-
- def probing_read_text(self, *args, **kwargs):
- if self.name == "SOUL.md":
- TestSoulIoIsOffTheEventLoop._probe(seen, "read")
- return real_read_text(self, *args, **kwargs)
-
- monkeypatch.setattr(Path, "read_text", probing_read_text)
-
- r = client.get("/api/profiles/demo/soul")
-
- assert r.status_code == 200, r.text
- assert r.json()["content"] == SOUL
- assert ("read", False) in seen, (
- f"SOUL.md must be read off the event loop; proof: {seen}"
- )
-
- def test_put_soul_writes_off_loop(self, client, profile_dir: Path, monkeypatch):
- seen: list[tuple[str, bool]] = []
- import utils
-
- real_write = utils.atomic_write_text
-
- def probing_write(*args, **kwargs):
- TestSoulIoIsOffTheEventLoop._probe(seen, "write")
- return real_write(*args, **kwargs)
-
- monkeypatch.setattr(utils, "atomic_write_text", probing_write)
-
- r = client.put("/api/profiles/demo/soul", json={"content": SOUL})
-
- assert r.status_code == 200, r.text
- assert (profile_dir / "SOUL.md").read_text(encoding="utf-8") == SOUL
- assert ("write", False) in seen, (
- f"SOUL.md must be written off the event loop; proof: {seen}"
- )
-
+class TestSoulReadReportsPresence:
def test_missing_soul_is_still_reported_absent(self, client, profile_dir: Path):
"""The offloaded reader must keep distinguishing "no file" from
"empty file" — the whole point of the durability tests above."""
diff --git a/tests/hermes_cli/test_web_profiles_off_loop.py b/tests/hermes_cli/test_web_profiles_off_loop.py
index 383f0ee13ba..623e1f3a308 100644
--- a/tests/hermes_cli/test_web_profiles_off_loop.py
+++ b/tests/hermes_cli/test_web_profiles_off_loop.py
@@ -9,13 +9,9 @@ provider round-trip with a 60 s ceiling. While the loop is parked, the process
serves nothing else — including the ``/api/ws`` probes the desktop app and the
dashboard's own Chat tab depend on.
-Two complementary assertions per site:
-
-* a **loop probe** — the stubbed callee records whether an event loop is
- running in its own thread, mirroring
- ``tests/hermes_cli/test_cron_dashboard_off_loop.py``; and
-* a **concurrency proof** — the stubbed callee blocks on a ``threading.Event``
- while an unrelated request is timed, which fails if the loop is parked.
+Each slow site gets a **concurrency proof**: the stubbed callee blocks on a
+``threading.Event`` while an unrelated request is timed, which fails if the
+loop is parked.
The block is bounded by a timeout so a regression costs the suite a few
seconds rather than hanging it.
@@ -23,7 +19,6 @@ seconds rather than hanging it.
from __future__ import annotations
-import asyncio
import threading
import time
from concurrent.futures import ThreadPoolExecutor
@@ -71,27 +66,6 @@ def client(profile_dir):
yield c
-def loop_probe():
- """Collect ``(tag, on_loop)`` proof from stubbed blocking callees."""
- seen: list[tuple[str, bool]] = []
-
- def probe(tag: str) -> None:
- try:
- asyncio.get_running_loop()
- seen.append((tag, True))
- except RuntimeError:
- seen.append((tag, False))
-
- return seen, probe
-
-
-def assert_off_loop(seen, tag: str) -> None:
- assert (tag, False) in seen, (
- f"{tag} must run off the event loop; proof: {seen}"
- )
-
-
class _Blocker:
"""A stand-in for a slow library call, released by the test."""
@@ -137,20 +111,6 @@ def assert_serves_concurrently(client, blocker: _Blocker, fire) -> None:
# ── DELETE /api/profiles/{name} — the 10 s gateway-stop sleep ────────────────
-def test_delete_profile_runs_off_loop(client, monkeypatch, loop_probe, tmp_path):
- seen, probe = loop_probe
- from hermes_cli import profiles as profiles_mod
-
- def fake_delete(name, yes=False):
- probe("delete_profile")
- return tmp_path / "profiles" / name
-
- monkeypatch.setattr(profiles_mod, "delete_profile", fake_delete)
-
- resp = client.delete("/api/profiles/demo")
-
- assert resp.status_code == 200, resp.text
- assert_off_loop(seen, "delete_profile")
def test_delete_profile_does_not_block_the_dashboard(client, monkeypatch, tmp_path):
@@ -178,21 +138,6 @@ def _outcome(ok=True, reason="described", description="a demo profile"):
return DescribeOutcome("demo", ok, reason, description=description)
-def test_describe_auto_runs_off_loop(client, monkeypatch, loop_probe):
- seen, probe = loop_probe
- from hermes_cli import profile_describer
-
- def fake_describe(name, overwrite=False, timeout=None):
- probe("describe_profile")
- return _outcome()
-
- monkeypatch.setattr(profile_describer, "describe_profile", fake_describe)
-
- resp = client.post("/api/profiles/demo/describe-auto", json={"overwrite": True})
-
- assert resp.status_code == 200, resp.text
- assert resp.json()["ok"] is True
- assert_off_loop(seen, "describe_profile")
def test_describe_auto_does_not_block_the_dashboard(client, monkeypatch):
@@ -215,20 +160,6 @@ def test_describe_auto_does_not_block_the_dashboard(client, monkeypatch):
# ── PATCH /api/profiles/{name} — rename walks and rewrites the profile tree ──
-def test_rename_profile_runs_off_loop(client, monkeypatch, loop_probe, tmp_path):
- seen, probe = loop_probe
- from hermes_cli import profiles as profiles_mod
-
- def fake_rename(old, new):
- probe("rename_profile")
- return tmp_path / "profiles" / new
-
- monkeypatch.setattr(profiles_mod, "rename_profile", fake_rename)
-
- resp = client.patch("/api/profiles/demo", json={"new_name": "renamed"})
-
- assert resp.status_code == 200, resp.text
- assert_off_loop(seen, "rename_profile")
def test_rename_profile_does_not_block_the_dashboard(client, monkeypatch, tmp_path):
@@ -247,87 +178,18 @@ def test_rename_profile_does_not_block_the_dashboard(client, monkeypatch, tmp_pa
# ── /api/profiles/active — sticky active-profile state file ──────────────────
-def test_get_active_profile_runs_off_loop(client, monkeypatch, loop_probe):
- seen, probe = loop_probe
- from hermes_cli import profiles as profiles_mod
-
- def fake_get_active():
- probe("get_active_profile")
- return "demo"
- def fake_get_current():
- probe("get_active_profile_name")
- return "default"
- monkeypatch.setattr(profiles_mod, "get_active_profile", fake_get_active)
- monkeypatch.setattr(profiles_mod, "get_active_profile_name", fake_get_current)
-
- resp = client.get("/api/profiles/active")
-
- assert resp.status_code == 200, resp.text
- assert resp.json() == {"active": "demo", "current": "default"}
- assert_off_loop(seen, "get_active_profile")
- assert_off_loop(seen, "get_active_profile_name")
-
-
-def test_set_active_profile_runs_off_loop(client, monkeypatch, loop_probe):
- seen, probe = loop_probe
- from hermes_cli import profiles as profiles_mod
-
- def fake_set_active(name):
- probe("set_active_profile")
-
- monkeypatch.setattr(profiles_mod, "set_active_profile", fake_set_active)
-
- resp = client.post("/api/profiles/active", json={"name": "demo"})
-
- assert resp.status_code == 200, resp.text
- assert resp.json()["active"] == "demo"
- assert_off_loop(seen, "set_active_profile")
# ── PUT /api/profiles/{name}/description — profile.yaml read/modify/write ────
-def test_update_description_runs_off_loop(client, monkeypatch, loop_probe):
- seen, probe = loop_probe
- from hermes_cli import profiles as profiles_mod
-
- def fake_write_meta(profile_dir, **kwargs):
- probe("write_profile_meta")
-
- monkeypatch.setattr(profiles_mod, "write_profile_meta", fake_write_meta)
-
- resp = client.put(
- "/api/profiles/demo/description", json={"description": "a demo profile"}
- )
-
- assert resp.status_code == 200, resp.text
- assert resp.json()["description_auto"] is False
- assert_off_loop(seen, "write_profile_meta")
# ── GET /api/profiles/{name}/desktop-overlay — reads desktop.json ────────────
-def test_desktop_overlay_read_runs_off_loop(client, monkeypatch, loop_probe, profile_dir):
- seen, probe = loop_probe
- (profile_dir / "desktop.json").write_text('{"theme": "dark"}', encoding="utf-8")
-
- real_read_text = Path.read_text
-
- def probing_read_text(self, *args, **kwargs):
- if self.name == "desktop.json":
- probe("desktop.json read")
- return real_read_text(self, *args, **kwargs)
-
- monkeypatch.setattr(Path, "read_text", probing_read_text)
-
- resp = client.get("/api/profiles/demo/desktop-overlay")
-
- assert resp.status_code == 200, resp.text
- assert resp.json() == {"exists": True, "desktop": {"theme": "dark"}}
- assert_off_loop(seen, "desktop.json read")
def test_desktop_overlay_absent_still_reports_missing(client):
@@ -406,18 +268,3 @@ def test_describe_auto_unknown_profile_is_still_404(client):
# ── PUT /api/profiles/{name}/model — config.yaml read-modify-write ───────────
-def test_update_profile_model_runs_off_loop(client, monkeypatch, loop_probe):
- seen, probe = loop_probe
- from hermes_cli.web_routers import profiles as router_mod
-
- def fake_write_model(profile_dir, provider, model):
- probe("write_profile_model")
-
- monkeypatch.setattr(router_mod, "_write_profile_model", fake_write_model)
-
- resp = client.put(
- "/api/profiles/demo/model", json={"provider": "openrouter", "model": "x/y"}
- )
-
- assert resp.status_code == 200, resp.text
- assert_off_loop(seen, "write_profile_model")
diff --git a/tests/hermes_cli/test_web_routers_endpoint_probe.py b/tests/hermes_cli/test_web_routers_endpoint_probe.py
index 783d3df17d0..86a4530d42b 100644
--- a/tests/hermes_cli/test_web_routers_endpoint_probe.py
+++ b/tests/hermes_cli/test_web_routers_endpoint_probe.py
@@ -137,9 +137,9 @@ def test_bare_root_probe_reports_the_v1_key_rejection_not_the_root_404(route, mo
if route == "/api/providers/validate":
body = EnvVarUpdate(key="OPENAI_BASE_URL", value="http://127.0.0.1:39080", api_key="k")
data = asyncio.run(mod.validate_provider_credential(body, request=None))
- assert data["message"] == "http://127.0.0.1:39080/v1/models answered HTTP 401."
+ assert "401" in data["message"]
else:
body = CustomEndpointUpdate(id="", name="local", base_url="http://127.0.0.1:39080", api_key="k", model="")
data = asyncio.run(mod.validate_custom_endpoint(body))
- assert data["message"] == "The endpoint rejected the API key."
assert data["ok"] is False and data["reachable"] is True
+ assert "404" not in data["message"]
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index a8cb9cd890f..6cd0f848b9e 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -9,7 +9,6 @@ import sys
import threading
import time
from pathlib import Path
-from types import SimpleNamespace
from unittest.mock import patch, MagicMock
import pytest
@@ -19,12 +18,10 @@ from hermes_cli.config import (
reload_env,
redact_key,
OPTIONAL_ENV_VARS,
- DEFAULT_CONFIG,
)
import gateway.status as _gw_status
import hermes_cli.config as _cfg_mod
import hermes_cli.web_routers.chat_ws as _rt_chat_ws
-import hermes_cli.web_routers.status as _rt_status
import hermes_cli.web_server_chat as _web_server_chat
import hermes_cli.web_server_config as _web_server_config
import hermes_cli.web_server_dashboard as _web_server_dashboard
@@ -193,10 +190,6 @@ class TestRedactKey:
def test_short_key_fully_masked(self):
assert redact_key("short") == "***"
- def test_empty_key(self):
- result = redact_key("")
- assert "not set" in result.lower() or result == "***" or "\x1b" in result
-
class TestSessionTokenInjection:
"""The desktop shell mints HERMES_DASHBOARD_SESSION_TOKEN and signs its
@@ -216,15 +209,6 @@ class TestSessionTokenInjection:
assert ws.app is original_app
assert ws._SESSION_TOKEN == original_token
- def test_falls_back_to_random_token(self, monkeypatch):
- import hermes_cli.web_server as ws
-
- monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)
- with patch.object(
- ws.secrets, "token_urlsafe", return_value="generated-token"
- ) as token_urlsafe:
- assert ws._resolve_session_token() == "generated-token"
- token_urlsafe.assert_called_once_with(32)
def test_session_token_resolution_preserves_loaded_app_auth(self, monkeypatch):
import hermes_cli.web_server as ws
@@ -277,7 +261,6 @@ class TestWebServerEndpoints:
"""Repeated GET-only polls must not checkpoint another writer's WAL."""
import sqlite3
- from hermes_cli import web_server
from hermes_constants import get_hermes_home
from hermes_state import SessionDB
@@ -336,7 +319,6 @@ class TestWebServerEndpoints:
"""Busy store, not a gone store: the desktop keeps the list it has."""
import sqlite3
- from hermes_cli import web_server
def boom(*_args, **_kwargs):
raise sqlite3.OperationalError("disk I/O error")
@@ -347,7 +329,6 @@ class TestWebServerEndpoints:
def test_get_sessions_non_transient_operational_error_is_500(self, monkeypatch):
import sqlite3
- from hermes_cli import web_server
def boom(*_args, **_kwargs):
raise sqlite3.OperationalError("no such table: sessions")
@@ -355,41 +336,8 @@ class TestWebServerEndpoints:
monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", boom)
assert self.client.get("/api/sessions?limit=1&offset=0").status_code == 500
- def test_get_status_loads_gateway_config_off_event_loop(self, monkeypatch):
- """Cold gateway config loading must not block the WebSocket loop.
-
- On Windows the first ``load_gateway_config()`` call imports and
- discovers platform adapters and can take longer than Desktop's 15s
- WebSocket timeout. Running it inline makes a concurrent /api/ws
- handshake time out before ``gateway.ready`` can be sent.
- """
- import gateway.config as gateway_config
- import hermes_cli.web_server as web_server
-
- seen = {}
-
- class _Config:
- @staticmethod
- def get_connected_platforms():
- return []
-
- def _load():
- seen["thread"] = threading.get_ident()
- return _Config()
-
- monkeypatch.setattr(gateway_config, "load_gateway_config", _load)
-
- async def _run():
- event_loop_thread = threading.get_ident()
- await _rt_status.get_status()
- return event_loop_thread
-
- event_loop_thread = asyncio.run(_run())
-
- assert seen["thread"] != event_loop_thread
def test_get_sessions_auto_archive_uses_maintenance_writer(self):
- from hermes_cli import web_server
from hermes_cli.config import load_config, save_config
from hermes_constants import get_hermes_home
from hermes_state import SessionDB
@@ -529,7 +477,6 @@ class TestWebServerEndpoints:
"""
import sqlite3
- from hermes_cli import web_server
from hermes_constants import get_hermes_home
from hermes_state import SessionDB
@@ -598,7 +545,6 @@ class TestWebServerEndpoints:
import hermes_state
- from hermes_cli import web_server
def boom(*args, **kwargs):
raise sqlite3_module.OperationalError("database is locked")
@@ -616,7 +562,6 @@ class TestWebServerEndpoints:
would hammer the DB for nothing: serve reads probe-less instead, warn
once, and never pay the writable open for that store again.
"""
- from hermes_cli import web_server
from hermes_constants import get_hermes_home
from hermes_state import SessionDB
@@ -677,7 +622,6 @@ class TestWebServerEndpoints:
import sqlite3
import hermes_state
- from hermes_cli import web_server
db_path = tmp_path / "state.db"
db_path.write_bytes(b"not-empty")
@@ -699,7 +643,6 @@ class TestWebServerEndpoints:
message over corrupt file bytes (#98924) — must route through the
same one-writable-open heal as malformed schema."""
import hermes_state
- from hermes_cli import web_server
db_path = tmp_path / "state.db"
db_path.write_bytes(b"not-empty")
@@ -754,9 +697,6 @@ class TestWebServerEndpoints:
] * len(paths)
-
-
-
def test_messaging_platforms_profile_scopes_gateway_reads(self, monkeypatch):
"""?profile=<name> must resolve liveness from the profile's own home.
@@ -803,30 +743,15 @@ class TestWebServerEndpoints:
assert worker_home in seen["expected_homes"]
-
-
def test_gateway_drain_bad_action_400(self):
resp = self.client.post("/api/gateway/drain", json={"action": "explode"})
assert resp.status_code == 400
-
-
@staticmethod
def _provider_field_map(payload):
return {field["key"]: field for field in payload["fields"]}
- def test_openviking_recall_fields_are_numeric_dashboard_controls(self):
- resp = self.client.get("/api/memory/providers/openviking/config")
-
- assert resp.status_code == 200
- fields = self._provider_field_map(resp.json())
- assert fields["recall_limit"]["kind"] == "integer"
- assert fields["recall_limit"]["minimum"] == 1
- assert fields["recall_limit"]["maximum"] == 100
- assert fields["recall_score_threshold"]["kind"] == "number"
- assert fields["recall_score_threshold"]["step"] == 0.01
- assert fields["recall_resources"]["kind"] == "boolean"
def test_openviking_dashboard_persists_typed_recall_values(self):
from hermes_cli.config import load_config
@@ -869,7 +794,6 @@ class TestWebServerEndpoints:
)
assert resp.status_code == 400
- assert "must be at most 100" in resp.json()["detail"]
def test_openviking_dashboard_rejects_blocked_endpoint_before_saving(self):
from hermes_cli.config import load_config
@@ -884,16 +808,11 @@ class TestWebServerEndpoints:
)
assert resp.status_code == 400
- assert "blocked metadata address" in resp.json()["detail"]
assert "credential" not in resp.json()["detail"]
memory_config = load_config().get("memory", {})
assert "openviking" not in memory_config
-
-
-
-
# A user-installed memory provider with a DECLARED config surface (``config_schema.py``, flat
# ``<home>/<name>/config.json`` storage) and a live ``get_config_schema``/``save_config`` pair.
# Bundled providers no longer ship a flat-storage declared schema (hindsight moved to the
@@ -987,10 +906,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert "api_key" not in provider_config
-
-
-
-
def test_post_memory_provider_setup_routes_pip_through_lazy_deps(self, monkeypatch):
"""NS-605: dashboard pip installs must use the environment-aware
lazy_deps pipeline (durable-target redirect on immutable hosted
@@ -1036,9 +951,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert installed == [("honcho-ai",)]
-
-
-
def test_put_memory_provider_config_writes_config_and_secret(self):
from hermes_constants import get_hermes_home
from hermes_cli.config import load_config, load_env
@@ -1096,8 +1008,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert "secret-value" not in json.dumps(data)
-
-
# ── Memory provider config (Honcho host-block backend) ──────────────
@pytest.fixture(autouse=True)
@@ -1184,15 +1094,9 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert "secret-value" not in json.dumps(data)
-
-
-
# ── GET /api/media (remote image display) ───────────────────────────
-
-
-
def test_get_media_requires_auth(self):
from hermes_cli.web_server import _SESSION_HEADER_NAME
@@ -1206,33 +1110,9 @@ CONFIG_SCHEMA = ProviderConfigSchema(
# ── POST /api/chat/image-upload (browser clipboard/drop images) ─────
-
-
-
# ── Dashboard font override ─────────────────────────────────────────
-
-
- def _create_session_with_heavy_fields(self, session_id: str) -> None:
- from hermes_state import SessionDB
-
- db = SessionDB()
- try:
- db.create_session(
- session_id=session_id,
- source="cli",
- system_prompt="# SOUL.md\n" + ("prompt body " * 500),
- model_config={"temperature": 0.7, "notes": "x" * 200},
- )
- finally:
- db.close()
-
-
-
-
-
-
def test_import_sessions_endpoint_imports_exported_json(self):
from hermes_state import SessionDB
@@ -1276,20 +1156,8 @@ CONFIG_SCHEMA = ProviderConfigSchema(
json={"sessions": [{"source": "cli", "messages": []}]},
)
assert invalid.status_code == 400
- assert invalid.json()["detail"]["errors"] == [
- {"index": 0, "error": "session id is required"}
- ]
-
-
-
-
-
-
-
-
-
-
-
+ errors = invalid.json()["detail"]["errors"]
+ assert [e["index"] for e in errors] == [0] and errors[0]["error"]
def test_latest_descendant_survives_parent_cycle(self):
@@ -1343,21 +1211,7 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert resp.json()["session_id"] == "primary-cont"
-
-
-
-
-
-
-
-
-
-
-
-
-
def test_update_hermes_returns_docker_guidance_without_spawning(self, monkeypatch):
- import hermes_cli.web_server as web_server
spawned = False
@@ -1386,7 +1240,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert data["name"] == "hermes-update"
assert data["pid"] is None
assert data["error"] == "docker_update_unsupported"
- assert "docker pull nousresearch/hermes-agent:latest" in data["message"]
assert spawned is False
status = self.client.get("/api/actions/hermes-update/status")
@@ -1395,10 +1248,8 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert status_data["running"] is False
assert status_data["exit_code"] == 1
assert status_data["pid"] is None
- assert any("docker pull nousresearch/hermes-agent:latest" in line for line in status_data["lines"])
def test_update_hermes_returns_apt_guidance_without_spawning(self, monkeypatch):
- import hermes_cli.web_server as web_server
spawned = False
@@ -1426,7 +1277,7 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert data["ok"] is False
assert data["pid"] is None
assert data["error"] == "apt_update_required"
- assert data["update_command"] == "pkg upgrade hermes-agent"
+ assert data["update_command"]
assert spawned is False
check = self.client.get("/api/hermes/update/check")
@@ -1434,11 +1285,9 @@ CONFIG_SCHEMA = ProviderConfigSchema(
check_data = check.json()
assert check_data["install_method"] == "apt"
assert check_data["can_apply"] is False
- assert check_data["update_command"] == "pkg upgrade hermes-agent"
- assert "Termux APT" in check_data["message"]
+ assert check_data["update_command"] == data["update_command"]
def test_update_status_recovers_completed_result_after_dashboard_restart(self, monkeypatch, tmp_path):
- import hermes_cli.web_server as web_server
action_id = "c" * 32
(tmp_path / "hermes-update.log").write_text(
@@ -1500,7 +1349,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
]
def test_update_hermes_reuses_running_action(self, monkeypatch):
- import hermes_cli.web_server as web_server
class Proc:
pid = 24680
@@ -1534,46 +1382,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
}
-
-
-
-
-
-
- def _schema_provider_options(self, key):
- resp = self.client.get("/api/config/schema")
- assert resp.status_code == 200
- return resp.json()["fields"][key]["options"]
-
-
-
-
-
-
-
- def test_platform_scoped_messaging_env_vars_are_channel_managed(self):
- """Platform-scoped vars belong to a Channels card; cross-cutting
- gateway vars belong to the Keys page.
-
- Uses credentials as the example: the self-configuring knobs
- (*_HOME_CHANNEL, *_ALLOW_ALL_USERS, …) were deliberately dropped from
- the setup cards and handed back to Keys — see
- tests/hermes_cli/test_setup_hidden_env.py.
- """
- from hermes_cli.web_server_messaging import _MESSAGING_KEYS_PAGE_KEYS, _build_catalog_entry, _channel_managed_env_keys
-
- discord = _build_catalog_entry("discord")
- assert "DISCORD_BOT_TOKEN" in discord["env_vars"]
- assert "DISCORD_ALLOWED_USERS" in discord["env_vars"]
-
- managed = _channel_managed_env_keys()
- assert "DISCORD_BOT_TOKEN" in managed
- assert "MATTERMOST_TOKEN" in managed
- assert "GATEWAY_PROXY_URL" not in managed
- assert "GATEWAY_PROXY_URL" in _MESSAGING_KEYS_PAGE_KEYS
-
-
-
def test_model_set_maps_unknown_vendor_to_aggregator(self, monkeypatch):
"""A bare vendor name from analytics rows (no billing_provider) is not
a Hermes provider — keep the user's aggregator instead of writing a
@@ -1634,12 +1442,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
fb.reset_for_tests()
-
-
-
-
-
-
def test_reveal_env_var(self, tmp_path):
"""POST /api/env/reveal should return the real unredacted value."""
from hermes_cli.config import save_env_value
@@ -1656,8 +1458,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert data["value"] == "super-secret-value-12345"
-
-
def test_reveal_env_var_custom_session_header_ignores_proxy_authorization(self, tmp_path):
"""A valid dashboard session header should coexist with proxy auth."""
from hermes_cli.config import save_env_value
@@ -1691,10 +1491,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert resp.status_code == 200
-
-
-
-
def test_messaging_catalog_prefers_plugin_label_over_enum_pseudo_member(self):
"""A plugin platform that leaked into Platform.__members__ as a pseudo-
member must still render with its plugin label, not a title-cased id.
@@ -1732,18 +1528,9 @@ CONFIG_SCHEMA = ProviderConfigSchema(
Platform._member_map_.pop("PSEUDOFAKE", None)
-
-
-
-
-
-
-
-
def test_telegram_onboarding_apply_reports_restart_failure_after_save(
self, monkeypatch
):
- import hermes_cli.web_server as ws
from hermes_cli.config import load_config, load_env
with _web_server_messaging._telegram_onboarding_lock:
@@ -1803,9 +1590,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert load_config()["platforms"]["telegram"]["enabled"] is True
-
-
-
def test_unauthenticated_api_blocked(self):
"""API requests without the session token should be rejected."""
from starlette.testclient import TestClient
@@ -1827,11 +1611,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert resp.status_code == 200
-
-
-
-
-
def test_parse_model_ids_handles_openai_and_bare_shapes(self):
"""Model discovery must tolerate the common /v1/models shapes and
never raise (so a slightly non-standard local endpoint still works)."""
@@ -1901,26 +1680,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
)
-
-
-
-
- def _seed_custom_provider_with_key(self):
- from hermes_cli.config import load_config, save_config
-
- cfg = load_config()
- cfg["providers"] = {
- "acme": {
- "name": "Acme",
- "base_url": "https://llm.acme.corp/v1",
- "model": "acme/m1",
- "api_key": "sk-stored-old",
- "models": {"acme/m1": {}},
- }
- }
- save_config(cfg)
-
-
def test_deleting_the_active_custom_endpoint_clears_its_model_mirror(self):
"""Deleting an endpoint must not leave its credential running the agent.
@@ -1977,11 +1736,11 @@ CONFIG_SCHEMA = ProviderConfigSchema(
"model:\n"
" provider: 2070\n"
" default: Qwen.gguf\n"
- " base_url: http://192.168.1.10:8082/v1\n"
+ " base_url: http://127.0.0.1:1/v1\n"
"providers:\n"
" 2070:\n"
" name: 2070\n"
- " base_url: http://192.168.1.10:8082/v1\n"
+ " base_url: http://127.0.0.1:1/v1\n"
" model: Qwen.gguf\n",
encoding="utf-8",
)
@@ -2282,10 +2041,10 @@ CONFIG_SCHEMA = ProviderConfigSchema(
"name": "x", "base_url": "https://gw.example.com/v1", "model": "", "api_mode": api_mode}).json()
assert body["ok"] is False and body["reachable"] is True
assert body["transport_checked"] == "chat_completions"
- assert "/chat/completions" in body["message"] and "Chat Completions" in body["message"]
+ assert body["message"]
assert body["models"] == ["gpt-5.6-sol"], "discovered models still returned so the user can re-pick"
assert posted[-1][0] == "https://gw.example.com/v1/chat/completions"
- assert posted[-1][1]["model"] == "gpt-5.6-sol" and posted[-1][1]["max_tokens"] == 1
+ assert posted[-1][1]["model"] == "gpt-5.6-sol"
def test_custom_endpoint_validate_passes_when_the_pinned_transport_is_served(self, monkeypatch):
posted = []
@@ -2294,8 +2053,8 @@ CONFIG_SCHEMA = ProviderConfigSchema(
"name": "x", "base_url": "https://gw.example.com/v1", "model": "", "api_mode": "codex_responses"}).json()
assert body["ok"] is True and body["message"] == ""
assert body["transport_checked"] == "codex_responses"
- assert posted == [("https://gw.example.com/v1/responses",
- {"model": "gpt-5.6-sol", "input": "hi", "max_output_tokens": 16})]
+ assert [url for url, _ in posted] == ["https://gw.example.com/v1/responses"]
+ assert posted[0][1]["model"] == "gpt-5.6-sol"
def test_custom_endpoint_save_leaves_a_hand_written_env_ref_alone(self, monkeypatch):
"""``api_key: ${MY_KEY}`` is already safe — don't copy it elsewhere.
@@ -2450,7 +2209,7 @@ CONFIG_SCHEMA = ProviderConfigSchema(
cfg = load_config()
cfg["custom_providers"] = [
- {"name": "Old Box", "base_url": "http://10.0.0.5:8080/v1", "model": "qwen", "api_key": "sk-old"},
+ {"name": "Old Box", "base_url": "http://127.0.0.1:1/v1", "model": "qwen", "api_key": "sk-old"},
]
save_config(cfg)
@@ -2458,7 +2217,7 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert activated.status_code == 200, activated.text
cfg = load_config()
assert cfg.get("custom_providers") == []
- assert cfg["providers"]["old-box"]["api"] == "http://10.0.0.5:8080/v1"
+ assert cfg["providers"]["old-box"]["api"] == "http://127.0.0.1:1/v1"
assert cfg["model"]["provider"] == "old-box"
assert cfg["model"]["default"] == "qwen"
@@ -2468,9 +2227,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
resp = self.client.get("/api/sessions?limit=-1")
assert resp.status_code == 422
- def test_get_sessions_rejects_negative_offset(self):
- resp = self.client.get("/api/sessions?offset=-1")
- assert resp.status_code == 422
def test_get_sessions_positive_limit_still_works(self):
from hermes_state import SessionDB
@@ -2495,9 +2251,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
resp = self.client.get("/api/profiles/sessions?limit=-1")
assert resp.status_code == 422
- def test_profiles_sessions_rejects_negative_offset(self):
- resp = self.client.get("/api/profiles/sessions?offset=-1")
- assert resp.status_code == 422
def test_profiles_sessions_positive_limit_still_works(self):
from hermes_state import SessionDB
@@ -2534,18 +2287,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
resp = self.client.get("/api/sessions/neg-limit-messages/messages?limit=-1")
assert resp.status_code == 422
- def test_get_session_messages_rejects_negative_offset(self):
- from hermes_state import SessionDB
-
- db = SessionDB()
- try:
- db.create_session(session_id="neg-offset-messages", source="cli")
- db.append_message(session_id="neg-offset-messages", role="user", content="hi")
- finally:
- db.close()
-
- resp = self.client.get("/api/sessions/neg-offset-messages/messages?offset=-1")
- assert resp.status_code == 422
def test_get_session_messages_limit_above_500_is_capped_not_rejected(self):
"""A limit above the documented 500-row cap is silently clamped
@@ -2821,11 +2562,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
assert calls == [(500, 0), (500, 500)]
-
-
-
-
-
# ---------------------------------------------------------------------------
# _build_schema_from_config tests
# ---------------------------------------------------------------------------
@@ -2834,23 +2570,6 @@ CONFIG_SCHEMA = ProviderConfigSchema(
class TestBuildSchemaFromConfig:
- def test_overrides_applied(self):
- from hermes_cli.web_server_config import CONFIG_SCHEMA
- # terminal.backend should be a select with options
- if "terminal.backend" in CONFIG_SCHEMA:
- entry = CONFIG_SCHEMA["terminal.backend"]
- assert entry["type"] == "select"
- assert "options" in entry
- assert "local" in entry["options"]
- assert "vercel_sandbox" in entry["options"]
- runtime_entry = CONFIG_SCHEMA["terminal.vercel_runtime"]
- assert runtime_entry["type"] == "select"
- assert "node24" in runtime_entry["options"]
- assert "python3.13" in runtime_entry["options"]
- assert len(runtime_entry["options"]) >= 3
-
-
-
def test_timezone_field_is_searchable_select(self):
"""timezone must ship as a searchable, clearable select of IANA ids.
@@ -2881,7 +2600,6 @@ class TestBuildSchemaFromConfig:
_schema_with_dynamic_provider_options must recompute it so a provider
installed mid-session is selectable without a restart.
"""
- from hermes_cli import web_server
monkeypatch.setattr(_cfg_mod, "load_config", lambda: {"memory": {"provider": "honcho"}})
monkeypatch.setattr(
@@ -2898,20 +2616,6 @@ class TestBuildSchemaFromConfig:
assert _web_server_config.CONFIG_SCHEMA["memory.provider"] is not fields["memory.provider"]
-
-
-
-
-
- def test_no_single_field_categories(self):
- """After merging, no category should have just 1 field."""
- from hermes_cli.web_server_config import CONFIG_SCHEMA
- from collections import Counter
- cats = Counter(e["category"] for e in CONFIG_SCHEMA.values())
- for cat, count in cats.items():
- assert count >= 2, f"Category '{cat}' has only {count} field(s) — should be merged"
-
-
# ---------------------------------------------------------------------------
# Config round-trip tests
# ---------------------------------------------------------------------------
@@ -2931,16 +2635,12 @@ class TestConfigRoundTrip:
self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
-
-
-
-
def test_round_trip_preserves_schema_invisible_nested_keys(self):
"""Nested keys that aren't in CONFIG_SCHEMA must also survive a
round-trip. Deep-merge is required — a shallow merge would drop
``agent.<custom_key>`` when the frontend sends a partial ``agent``
dict containing only schema-known sub-fields."""
- from hermes_cli.config import load_config, read_raw_config, save_config
+ from hermes_cli.config import read_raw_config, save_config
# Seed config with a key under `agent` that isn't in the schema.
# Use a sentinel name to avoid colliding with future schema fields.
@@ -3049,12 +2749,9 @@ class TestNewEndpoints:
# --- Automation Blueprints ---
-
-
# --- Profiles ---
-
def test_profiles_create_builder_mcp_auth_is_profile_scoped(
self, monkeypatch
):
@@ -3137,20 +2834,9 @@ class TestNewEndpoints:
assert not (root / ".env").exists()
-
# --- New profiles endpoints: active / description / model / describe-auto ---
-
-
-
-
-
-
-
-
-
-
def test_discord_toolsets_read_and_write_discord_platform(self):
"""Platform-restricted toolsets must not be saved as successful CLI no-ops."""
from hermes_cli.config import load_config
@@ -3188,36 +2874,6 @@ class TestNewEndpoints:
config["platform_toolsets"]["discord"]
)
- def test_toolsets_resolve_subscription_features_once(self, monkeypatch):
- import hermes_cli.tools_config as tools_config
- from hermes_cli.nous_subscription import NousSubscriptionFeatures
-
- calls = 0
- features = NousSubscriptionFeatures(
- subscribed=False,
- nous_auth_present=False,
- provider_is_nous=False,
- features={},
- account_info=None,
- )
-
- def resolve_features(config, *, force_fresh=False):
- nonlocal calls
- calls += 1
- return features
-
- monkeypatch.setattr(
- tools_config,
- "get_nous_subscription_features",
- resolve_features,
- )
-
- resp = self.client.get("/api/tools/toolsets")
-
- assert resp.status_code == 200
- assert resp.json()
- assert calls == 1
-
def test_get_toolset_config_returns_provider_matrix(self):
"""GET .../config returns provider rows with structured env_vars."""
@@ -3295,10 +2951,6 @@ class TestNewEndpoints:
assert by_name["ElevenLabs"]["status"] == "needs_keys"
-
-
-
-
def test_select_managed_nous_provider_reports_needs_nous_auth(self, monkeypatch):
"""Selecting a managed Nous row while logged out flags needs_nous_auth.
@@ -3338,7 +2990,6 @@ class TestNewEndpoints:
# -- Web capability split (search vs extract backends) ------------------
-
def test_select_web_search_backend_matches_runtime_resolution(self, monkeypatch):
"""PUT provider with capability=search writes web.search_backend and the
runtime search dispatcher resolves to it — while extract is untouched."""
@@ -3383,12 +3034,8 @@ class TestNewEndpoints:
# -- Terminal execution backend picker ---------------------------------
-
-
-
def test_terminal_ssh_probe_ready_when_configured(self, monkeypatch):
"""SSH host + user in config.yaml -> ready."""
- import hermes_cli.web_server as web_server
from hermes_cli.config import load_config, save_config
monkeypatch.setattr(shutil, "which", lambda name: None)
@@ -3404,13 +3051,6 @@ class TestNewEndpoints:
assert "[email protected]" in ssh["detail"]
-
-
-
-
-
-
-
def test_analytics_usage_includes_skill_breakdown(self):
from hermes_state import SessionDB
@@ -3467,38 +3107,6 @@ class TestNewEndpoints:
assert top_skill["total_count"] == 1
assert top_skill["last_used_at"] is not None
- def test_analytics_usage_skips_full_insights_generate(self):
- """get_usage_analytics must call get_usage_breakdown, not generate()."""
- from unittest.mock import patch
- from agent.insights import InsightsEngine
- from hermes_state import SessionDB
-
- db = SessionDB()
- try:
- db.create_session(
- session_id="usage-tools-test",
- source="cli",
- model="anthropic/claude-sonnet-4",
- )
- db.update_token_counts(
- "usage-tools-test",
- input_tokens=10,
- output_tokens=5,
- )
- db.append_message(
- "usage-tools-test",
- role="tool",
- content="read output",
- tool_name="read_file",
- )
- finally:
- db.close()
-
- with patch.object(InsightsEngine, "generate") as mock_generate:
- resp = self.client.get("/api/analytics/usage?days=7")
- assert resp.status_code == 200
- mock_generate.assert_not_called()
- assert any(tool["tool"] == "read_file" for tool in resp.json()["tools"])
# ---------------------------------------------------------------------------
# Desktop-owned loopback backends are not gated by dashboard.public_url (#96490)
@@ -3733,24 +3341,6 @@ class TestDenormalizeProviderSwitch:
assert cfg_path.read_bytes() == before
-class TestModelContextLengthSchema:
- """Tests for model_context_length placement in CONFIG_SCHEMA."""
-
-
- def test_schema_model_context_length_after_model(self):
- """model_context_length should appear immediately after model in schema."""
- from hermes_cli.web_server_config import CONFIG_SCHEMA
- keys = list(CONFIG_SCHEMA.keys())
- model_idx = keys.index("model")
- assert keys[model_idx + 1] == "model_context_length"
-
- def test_schema_model_context_length_is_number(self):
- from hermes_cli.web_server_config import CONFIG_SCHEMA
- entry = CONFIG_SCHEMA["model_context_length"]
- assert entry["type"] == "number"
- assert "category" in entry
-
-
class TestModelInfoEndpoint:
"""Tests for GET /api/model/info endpoint."""
@@ -3765,7 +3355,6 @@ class TestModelInfoEndpoint:
def test_model_info_with_dict_config(self, monkeypatch):
- import hermes_cli.web_server as ws
monkeypatch.setattr(_cfg_mod, "load_config", lambda: {
"model": {
@@ -3788,7 +3377,6 @@ class TestModelInfoEndpoint:
def test_model_info_graceful_on_metadata_error(self, monkeypatch):
"""Endpoint should return zeros on import/resolution errors, not 500."""
- import hermes_cli.web_server as ws
monkeypatch.setattr(_cfg_mod, "load_config", lambda: {
"model": "some/obscure-model"
@@ -3832,8 +3420,6 @@ class TestProbeGatewayHealth:
assert timeouts == [0.75, 0.75]
-
-
def test_detailed_fails_falls_back_to_simple_health(self, monkeypatch):
"""If /health/detailed fails, falls back to /health."""
import hermes_cli.web_server as ws
@@ -3897,30 +3483,6 @@ class TestStatusRemoteGateway:
assert data["gateway_health_url"] == "http://gw:8642"
- def test_status_remote_probe_not_attempted_when_local_pid_found(self, monkeypatch):
- """When local PID check succeeds, the remote probe is never called."""
- import hermes_cli.web_server as ws
-
- monkeypatch.setattr(_gw_status, "get_running_pid_cached", lambda: 1234)
- monkeypatch.setattr(_gw_status, "read_runtime_status", lambda: {
- "gateway_state": "running",
- "platforms": {},
- })
- monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
- probe_called = [False]
- original = _web_server_gateway._probe_gateway_health
-
- def track_probe():
- probe_called[0] = True
- return original()
-
- monkeypatch.setattr(_web_server_gateway, "_probe_gateway_health", track_probe)
-
- resp = self.client.get("/api/status")
- assert resp.status_code == 200
- assert not probe_called[0]
-
-
def test_status_remote_running_null_pid(self, monkeypatch):
"""Remote gateway running but PID not in response — pid should be None."""
import hermes_cli.web_server as ws
@@ -3967,7 +3529,6 @@ class TestStatusInstallId:
self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
def test_status_reports_persistent_install_id(self, monkeypatch):
- import hermes_cli.web_server as ws
from hermes_constants import get_default_hermes_root
monkeypatch.setattr(_gw_status, "get_running_pid_cached", lambda: None)
@@ -4057,7 +3618,6 @@ class TestGatewayBusyReadout:
"""While draining, the gateway is not a fresh begin-drain target, and
busy is False even with a stale active_agents>0 in the file — the state
gate dominates."""
- import hermes_cli.web_server as ws
monkeypatch.setattr(_gw_status, "get_running_pid_cached", lambda: 1234)
monkeypatch.setattr(_gw_status, "read_runtime_status", lambda: {
@@ -4074,7 +3634,6 @@ class TestGatewayBusyReadout:
def test_active_agents_unparseable_in_file_degrades_to_zero(self, monkeypatch):
"""A corrupt active_agents value in the status file must not 500 or
produce a spurious busy — it degrades to 0/not-busy."""
- import hermes_cli.web_server as ws
monkeypatch.setattr(_gw_status, "get_running_pid_cached", lambda: 1234)
monkeypatch.setattr(_gw_status, "read_runtime_status", lambda: {
@@ -4102,12 +3661,6 @@ class TestStatusMemoryBlock:
self.client = TestClient(app)
self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
- def test_memory_block_present_with_pressure_field(self):
- data = self.client.get("/api/status").json()
- assert "memory" in data
- assert data["memory"]["pressure"] in {
- "ok", "elevated", "critical", "unknown",
- }
def test_memory_block_degrades_when_collector_raises(self, monkeypatch):
"""A broken collector must never take down the status endpoint —
@@ -4122,12 +3675,6 @@ class TestStatusMemoryBlock:
assert resp.status_code == 200
assert resp.json()["memory"] == {"pressure": "unknown"}
- def test_disk_block_present_with_pressure_field(self):
- data = self.client.get("/api/status").json()
- assert "disk" in data
- assert data["disk"]["pressure"] in {
- "ok", "elevated", "critical", "unknown",
- }
def test_disk_block_degrades_when_collector_raises(self, monkeypatch):
"""Same contract as the memory block: a broken collector must never
@@ -4179,7 +3726,6 @@ class TestGatewayUpdatedAtContract:
def test_local_runtime_valid_epoch_becomes_iso_string(self, monkeypatch):
"""A plausible legacy epoch value is converted, not dropped."""
from datetime import datetime, timezone
- import hermes_cli.web_server as ws
epoch = 1750000000
monkeypatch.setattr(_gw_status, "get_running_pid_cached", lambda: 1234)
@@ -4253,15 +3799,11 @@ class TestNormaliseThemeDefinition:
assert result["palette"]["foreground"]["alpha"] == 0.0
-
-
-
class TestDiscoverUserThemes:
"""Tests for _discover_user_themes() — scans ~/.hermes/dashboard-themes/."""
def test_returns_empty_when_dir_missing(self, tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- from hermes_cli import web_server
assert _web_server_dashboard._discover_user_themes() == []
def test_loads_and_normalises_yaml(self, tmp_path, monkeypatch):
@@ -4278,7 +3820,6 @@ class TestDiscoverUserThemes:
"layout:\n"
" density: spacious\n"
)
- from hermes_cli import web_server
results = _web_server_dashboard._discover_user_themes()
assert len(results) == 1
assert results[0]["name"] == "ocean"
@@ -4302,7 +3843,6 @@ class TestDiscoverUserThemes:
reset_hermes_home_override,
set_hermes_home_override,
)
- from hermes_cli import web_server
token = set_hermes_home_override(str(other))
try:
@@ -4336,39 +3876,6 @@ class TestThemeBootstrapCSS:
encoding="utf-8",
)
- def test_user_theme_renders_bundle_vars(self, tmp_path, monkeypatch):
- """Active user theme → style block with ONLY variable names the
- bundle actually consumes (layerVars/typographyVars tokens)."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- self._write_theme(tmp_path)
- from hermes_cli import web_server
- monkeypatch.setattr(
- _cfg_mod, "load_config", lambda: {"dashboard": {"theme": "ocean"}}
- )
- css = _web_server_dashboard._render_active_theme_bootstrap_css()
- assert css.startswith('<style id="hermes-theme-bootstrap">')
- assert css.endswith("</style>")
- # Real bundle tokens (web/src/themes/context.tsx + index.css).
- assert "--background-base:#0a1628;" in css
- assert "--midground-base:#dbe4f0;" in css
- assert "--theme-font-sans:Inter, sans-serif;" in css
- assert "--theme-base-size:17px;" in css
- # Names that do NOT exist in the bundle must not be emitted.
- for bogus in ("--color-background", "--color-midground",
- "--font-sans:", "--font-base-size"):
- assert bogus not in css
- # Canvas rule flows through the variables (never goes stale when
- # applyTheme() rewrites them as inline styles at runtime).
- assert "html,body{background-color:var(--background-base);" in css
- assert "font-family:var(--theme-font-sans);" in css
- assert "font-size:var(--theme-base-size);" in css
- # No baked literal values in the html,body rule.
- assert "#0a1628" not in css.split("html,body")[1]
-
-
-
-
-
@staticmethod
def _mount_spa_client(tmp_path, monkeypatch):
@@ -4390,7 +3897,6 @@ class TestThemeBootstrapCSS:
def test_serve_index_injects_bootstrap_for_user_theme(self, tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
self._write_theme(tmp_path)
- import hermes_cli.web_server as ws
monkeypatch.setattr(
_cfg_mod, "load_config", lambda: {"dashboard": {"theme": "ocean"}}
)
@@ -4404,17 +3910,12 @@ class TestThemeBootstrapCSS:
assert "hermes-theme-bootstrap" in head
-
-
class TestNormaliseThemeExtensions:
"""Tests for the extended normaliser fields (assets, customCSS,
componentStyles, layoutVariant) — the surfaces themes use to reskin
the dashboard without shipping code."""
-
-
-
def test_custom_css_passthrough_and_capped(self):
from hermes_cli.web_server_dashboard import _normalise_theme_definition
# Small CSS passes through verbatim.
@@ -4452,8 +3953,6 @@ class TestNormaliseThemeExtensions:
assert "rogueBucket" not in r["componentStyles"]
-
-
class TestDeleteSessionEndpoint:
"""Tests for ``DELETE /api/sessions/{session_id}`` — the single-row delete
behind the desktop sidebar's per-session delete.
@@ -4484,26 +3983,6 @@ class TestDeleteSessionEndpoint:
self.auth_client = TestClient(app)
self.auth_client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
- def _seed(self, ids):
- from hermes_state import SessionDB
-
- db = SessionDB()
- try:
- for sid in ids:
- db.create_session(session_id=sid, source="cli")
- finally:
- db.close()
-
- def _exists(self, sid) -> bool:
- from hermes_state import SessionDB
-
- db = SessionDB()
- try:
- return db.get_session(sid) is not None
- finally:
- db.close()
-
-
def test_delete_absent_session_is_idempotent(self):
# PREMISE / regression: deleting a row that no longer exists must NOT
# 404 — the desktop would resurrect the ghost row and show
@@ -4578,26 +4057,6 @@ class TestBulkDeleteSessionsEndpoint:
db.close()
-
-
- def test_route_order_not_shadowed_by_session_id(self):
- """Pin the route-ordering contract: ``POST /api/sessions/bulk-delete``
- must hit the bulk handler, not be re-interpreted via the
- templated ``/api/sessions/{session_id}`` family. Concretely the
- response carries our ``ok`` + ``deleted`` keys."""
- resp = self.auth_client.post(
- "/api/sessions/bulk-delete", json={"ids": []}
- )
- assert resp.status_code == 200
- body = resp.json()
- assert body.get("ok") is True
- assert "deleted" in body, (
- "If this assertion fails, /api/sessions/bulk-delete is "
- "being shadowed by /api/sessions/{session_id} — check "
- "registration order in hermes_cli/web_server.py."
- )
-
-
class TestDeleteEmptySessionsEndpoint:
"""Tests for ``GET /api/sessions/empty/count`` and
``DELETE /api/sessions/empty`` — the bulk-delete endpoints backing
@@ -4703,26 +4162,6 @@ class TestDeleteEmptySessionsEndpoint:
db.close()
- def test_route_order_empty_not_shadowed_by_session_id(self):
- """Pin the route-ordering contract: ``DELETE /api/sessions/empty``
- must hit the bulk handler, not the templated single-session
- handler (which would 404 because no session has id 'empty').
-
- Concretely: a request against the bulk path on an EMPTY corpus
- returns ``{ok: True, deleted: 0}``. If the templated route were
- winning, we'd see 404 ("Session not found") instead.
- """
- resp = self.auth_client.delete("/api/sessions/empty")
- assert resp.status_code == 200
- body = resp.json()
- assert "deleted" in body, (
- "If this assertion fails, the literal /api/sessions/empty "
- "route is being shadowed by the templated /api/sessions/"
- "{session_id} route — check registration order in "
- "hermes_cli/web_server.py."
- )
-
-
class TestPluginAPIAuth:
"""Tests that plugin API routes require the session token (issue #19533)."""
@@ -4801,32 +4240,6 @@ class TestPluginAPIAuth:
resp = self.client.get("/api/plugins/_definitely_not_a_plugin_/anything")
assert resp.status_code == 401
- def test_plugin_websocket_unaffected_by_http_middleware(self):
- """The kanban /events WebSocket has its own ``?token=`` check;
- the HTTP middleware change must not start gating WS upgrades.
-
- Starlette doesn't run HTTP middleware on WebSocket upgrades anyway,
- but pin the behavior so a future refactor that moves auth into a
- shared layer can't silently break the WS auth contract.
- """
- from starlette.websockets import WebSocketDisconnect
-
- # Without a token the WS endpoint must close the upgrade itself
- # (its own _check_ws_token), NOT 401 from the HTTP middleware.
- try:
- with self.client.websocket_connect(
- "/api/plugins/kanban/events"
- ):
- pass # if we got here without disconnect, the WS accepted us
- except WebSocketDisconnect:
- pass # expected — WS endpoint rejected via its own check
- except Exception:
- # The kanban plugin may not be mounted in this test environment,
- # in which case the route doesn't exist at all (3xx/4xx during
- # upgrade). That's fine for this regression — it only matters
- # that the HTTP middleware didn't start intercepting WS upgrades.
- pass
-
class TestDashboardPluginManifestExtensions:
"""Tests for the extended plugin manifest fields (tab.override,
@@ -4877,7 +4290,6 @@ class TestDashboardPluginManifestExtensions:
other.mkdir()
monkeypatch.setenv("HERMES_HOME", str(launch_home))
- from hermes_cli import web_server
token = set_hermes_home_override(str(other))
try:
plugins = _web_server_dashboard._discover_dashboard_plugins()
@@ -4900,7 +4312,6 @@ class TestDashboardPluginManifestExtensions:
})
monkeypatch.setenv("HERMES_HOME", str(profile_home))
- from hermes_cli import web_server
plugins = _web_server_dashboard._discover_dashboard_plugins()
assert any(p["name"] == "meeting-intelligence" for p in plugins)
@@ -4924,13 +4335,12 @@ class TestDashboardPluginManifestExtensions:
})
monkeypatch.setenv("HERMES_HOME", str(profile_home))
- from hermes_cli import web_server
plugins = _web_server_dashboard._discover_dashboard_plugins()
entries = [p for p in plugins if p["name"] == "dupe"]
assert len(entries) == 1
assert entries[0]["tab"]["path"] == "/from-profile"
- def test_unreadable_plugin_paths_do_not_block_discovery(self, tmp_path, monkeypatch, caplog):
+ def test_unreadable_plugin_paths_do_not_block_discovery(self, tmp_path, monkeypatch):
"""A denied plugin directory or manifest must not prevent valid plugins loading."""
from pathlib import Path
@@ -4972,10 +4382,6 @@ class TestDashboardPluginManifestExtensions:
assert "valid" in {plugin["name"] for plugin in plugins}
assert "denied" not in {plugin["name"] for plugin in plugins}
- assert "Skipping unreadable dashboard plugin root" in caplog.text
- assert "Skipping unreadable dashboard plugin" in caplog.text
-
-
# ---------------------------------------------------------------------------
@@ -4987,7 +4393,6 @@ class TestDashboardPluginManifestExtensions:
# monkeypatch that hook.
# ---------------------------------------------------------------------------
-import sys
from hermes_cli import main_tui_launch
@@ -5022,10 +4427,8 @@ class TestPtyWebSocket:
return f"/api/pty?{urlencode(q)}"
-
def test_tui_python_command_uses_child_path(self, tmp_path):
"""Bare Python commands are resolved from the TUI child's PATH."""
- import hermes_cli.main as main_mod
command = f"hermes-review-python{Path(sys.executable).suffix}"
bin_dir = tmp_path / "bin"
@@ -5045,76 +4448,6 @@ class TestPtyWebSocket:
assert env["HERMES_PYTHON"] == command
-
-
-
- def test_resolve_chat_argv_async_uses_worker_thread(self, monkeypatch):
- captured: dict = {}
-
- def fake_resolve(resume=None, sidecar_url=None, profile=None):
- captured["resume"] = resume
- captured["sidecar_url"] = sidecar_url
- captured["profile"] = profile
- return (["node", "dist/entry.js"], "/tmp/ui-tui", {"NODE_ENV": "production"})
-
- async def fake_to_thread(fn, *args, **kwargs):
- captured["thread_fn"] = fn
- captured["thread_args"] = args
- captured["thread_kwargs"] = kwargs
- return fn(*args, **kwargs)
-
- monkeypatch.setattr(_web_server_chat, "_resolve_chat_argv", fake_resolve)
- monkeypatch.setattr(_web_server_chat.asyncio, "to_thread", fake_to_thread)
-
- argv, cwd, env = asyncio.run(
- _web_server_chat._resolve_chat_argv_async(
- resume="sess-42",
- sidecar_url="ws://127.0.0.1:9119/api/pub?channel=abc",
- profile="worker",
- )
- )
-
- assert callable(captured["thread_fn"])
- assert captured["thread_args"] == ()
- assert captured["thread_kwargs"] == {
- "resume": "sess-42",
- "sidecar_url": "ws://127.0.0.1:9119/api/pub?channel=abc",
- "profile": "worker",
- }
- assert argv == ["node", "dist/entry.js"]
- assert cwd == "/tmp/ui-tui"
- assert env == {"NODE_ENV": "production"}
- assert captured["resume"] == "sess-42"
- assert captured["sidecar_url"] == "ws://127.0.0.1:9119/api/pub?channel=abc"
- assert captured["profile"] == "worker"
-
-
- def _assert_pty_propagates(self, monkeypatch, raising_resolver, *, profile=None, expect_detail=None):
- """Drive /api/pty with a resolver that raises, and assert the error
- propagates through the real _resolve_chat_argv_async -> asyncio.to_thread
- -> lock -> re-raise chain into pty_ws's handler: the "Chat unavailable"
- notice is sent and the socket closes with code 1011 (the stable
- contract — we assert the close code, not the exact notice wording)."""
- from starlette.websockets import WebSocketDisconnect
-
- # Patch the REAL resolver so the whole wrapper/to_thread/lock chain runs.
- monkeypatch.setattr(_web_server_chat, "_resolve_chat_argv", raising_resolver)
-
- url = self._url(profile=profile) if profile else self._url()
- with self.client.websocket_connect(url) as conn:
- notice = conn.receive_text()
- with pytest.raises(WebSocketDisconnect) as exc:
- conn.receive_text()
- assert "Chat could not start" in notice
- assert exc.value.code == 1011
- if expect_detail is not None:
- assert expect_detail in notice
-
-
-
-
-
-
def test_unavailable_platform_closes_with_message(self, monkeypatch):
from hermes_cli.pty_bridge import PtyUnavailableError
@@ -5135,7 +4468,6 @@ class TestPtyWebSocket:
assert "pty missing" in msg or "unavailable" in msg.lower() or "pty" in msg.lower()
-
def test_pub_broadcasts_to_events_subscribers(self):
"""A frame handed to _broadcast_event is sent verbatim to every
subscriber registered on that channel — and not to subscribers on
@@ -5358,7 +4690,6 @@ class TestValidateProviderCredential:
assert data["ok"] is False and data["reachable"] is False
-
def test_local_endpoint_forwards_api_key_as_bearer(self, monkeypatch):
"""A custom endpoint that gates /v1/models behind auth must still
enumerate models: the optional api_key is sent as a Bearer header so the
@@ -5478,23 +4809,11 @@ class TestValidateProviderCredential:
},
)
- assert response.json() == {
- "ok": True,
- "reachable": True,
- "message": "",
- "models": ["local-model"],
- "resolved_base_url": "http://localhost:8000/v1",
- "model_details": [{"id": "local-model"}],
- "transport_checked": "chat_completions",
- }
- assert captured == {
- "url": "http://localhost:8000/v1/models",
- "headers": {
- "Accept": "application/json",
- "Authorization": "Bearer local-secret",
- },
- "posted": "http://localhost:8000/v1/chat/completions",
- }
+ body = response.json()
+ assert body["ok"] is True and body["reachable"] is True
+ assert body["models"] == ["local-model"]
+ assert captured["url"] == "http://localhost:8000/v1/models"
+ assert captured["headers"]["Authorization"] == "Bearer local-secret"
class TestDesktopCronTicker:
@@ -5510,7 +4829,6 @@ class TestDesktopCronTicker:
return TestClient(app)
def test_ticker_runs_when_desktop(self, monkeypatch, _isolate_hermes_home):
- import threading
import cron.scheduler as sched
called = threading.Event()
@@ -5554,9 +4872,7 @@ class TestServeIndexMissingIndex:
for route in ("/", "/chat"):
resp = client.get(route)
assert resp.status_code == 404
- assert resp.json()["error"] == (
- "Frontend not built. Run: cd web && npm run build"
- )
+ assert resp.json()["error"]
def test_index_deleted_after_mount_returns_json_404(self, tmp_path, monkeypatch):
client, dist = self._client_with_dist(tmp_path, monkeypatch, write_index=True)
@@ -5564,7 +4880,7 @@ class TestServeIndexMissingIndex:
(dist / "index.html").unlink()
resp = client.get("/chat")
assert resp.status_code == 404
- assert "Frontend not built" in resp.json()["error"]
+ assert resp.json()["error"]
# And recovers once the index reappears (e.g. a rebuild finished).
(dist / "index.html").write_text(
"<html><head></head><body>SPA-rebuilt</body></html>", encoding="utf-8"
@@ -5657,7 +4973,6 @@ class TestHeadlessServeTokenPage:
client, ws = self._headless_client(monkeypatch, gated=True)
resp = client.get("/")
assert resp.status_code == 404
- assert "web UI disabled" in resp.json()["error"]
assert ws._SESSION_TOKEN not in resp.text
def test_non_root_paths_stay_404_json(self, monkeypatch):
@@ -5665,7 +4980,6 @@ class TestHeadlessServeTokenPage:
for route in ("/chat", "/api/status-page", "/assets/index-abc.js"):
resp = client.get(route)
assert resp.status_code == 404
- assert "web UI disabled" in resp.json()["error"]
assert ws._SESSION_TOKEN not in resp.text
@@ -5768,13 +5082,9 @@ class TestDashboardComponentHealth:
# -- middleware -------------------------------------------------------
-
-
# -- /api/status components ------------------------------------------
-
-
def test_public_component_payload_carries_no_secret_bearing_fields(self):
"""PUBLIC_API_PATHS contract: counts/enums only — no paths/messages."""
self.ws.DASHBOARD_HEALTH.record_error("RuntimeError", "/api/secret-route?token=abc")
@@ -5864,10 +5174,6 @@ class TestSessionPatchUnread:
rows = self.auth_client.get("/api/sessions?limit=100").json()["sessions"]
assert next(s for s in rows if s["id"] == "s1")["unread"] is False
- def test_patch_unread_alone_is_accepted(self):
- # The route's "Nothing to update" guard must not reject a bare unread.
- resp = self.auth_client.patch("/api/sessions/s1", json={"unread": True})
- assert resp.status_code == 200
def test_patch_unread_rejects_non_bool(self):
# NB: pydantic v2 coerces "yes"/"no"/"1"/"0"/"on"/"off" to bool, so use
@@ -5890,10 +5196,6 @@ class TestSessionPatchUnread:
rows = self.auth_client.get("/api/sessions?limit=100").json()["sessions"]
assert bool(next(s for s in rows if s["id"] == "s1")["hidden"]) is False
- def test_patch_hidden_alone_is_accepted(self):
- resp = self.auth_client.patch("/api/sessions/s1", json={"hidden": True})
- assert resp.status_code == 200
-
def test_mount_spa_dynamic_web_dist_recheck(tmp_path, monkeypatch):
from fastapi import FastAPI
@@ -5910,7 +5212,7 @@ def test_mount_spa_dynamic_web_dist_recheck(tmp_path, monkeypatch):
# 1. missing build -> 404
res1 = client.get("/")
assert res1.status_code == 404
- assert res1.json()["error"] == "Frontend not built. Run: cd web && npm run build"
+ assert res1.json()["error"]
# 2. build created dynamically -> 200
dist.mkdir(parents=True, exist_ok=True)
diff --git a/tests/hermes_cli/test_web_server_boot_handshake.py b/tests/hermes_cli/test_web_server_boot_handshake.py
index 8fdea100c45..7f0e9aacb74 100644
--- a/tests/hermes_cli/test_web_server_boot_handshake.py
+++ b/tests/hermes_cli/test_web_server_boot_handshake.py
@@ -5,21 +5,9 @@ Simulates a slow hermes_cli.gateway import (15-30 s on a fresh Windows install
with Defender scanning every new .pyc) by patching the two helpers that touch
the blocking import and measuring response latency.
-Three scenarios are covered:
-
-1. _lifespan synchronous warmup: patched _warm_gateway_module sleeps N seconds;
- TestClient startup blocks for >= N seconds (intentional — see #73083/#73291:
- the import doesn't release the GIL on Windows + Python 3.11, so
- run_in_executor still froze the event loop. Absorbing the cost before the
- lifespan yield ensures the server socket doesn't accept probes until the
- import is complete).
-
-2. get_status run_in_executor: patched _resolve_restart_drain_timeout sleeps N
- seconds in a thread; a concurrent fast endpoint (/api/version) must respond
- during the wait, proving the event loop stayed free.
-
-3. No orphan accumulation: three concurrent /api/status requests all receive a
- 200 response — no socket timeouts, no connection resets.
+Covered: backend startup is not blocked by hosted-room recovery, shutdown joins the
+state.db reconcile worker, and /api/status runs its slow drain-timeout resolution off
+the event loop so a concurrent fast endpoint (/api/version) still responds.
"""
from __future__ import annotations
@@ -29,8 +17,6 @@ import time
import threading
from unittest.mock import patch
-import pytest
-
import hermes_cli.web_server as web_server_mod
import hermes_cli.web_server_lifecycle as _web_server_lifecycle
@@ -41,13 +27,6 @@ SLOW_SECONDS = 1 # represents the Defender worst-case (scaled down for CI speed
# Helpers
# ---------------------------------------------------------------------------
-def _make_slow_warm(seconds: float):
- """Return a _warm_gateway_module replacement that sleeps in the caller thread."""
- def _slow():
- time.sleep(seconds)
- return _slow
-
-
def _make_slow_drain(seconds: float):
"""Return a _resolve_restart_drain_timeout replacement that sleeps in thread."""
def _slow():
@@ -56,35 +35,6 @@ def _make_slow_drain(seconds: float):
return _slow
-# ---------------------------------------------------------------------------
-# Test 1 — _lifespan synchronous warmup blocks startup (intentional)
-# ---------------------------------------------------------------------------
-
-def test_lifespan_warmup_is_synchronous():
- """
- _warm_gateway_module runs synchronously before the lifespan yield (#73083).
- Startup blocks for at least SLOW_SECONDS — this is intentional: on Windows
- + Python 3.11 the import doesn't release the GIL, so run_in_executor still
- froze the event loop. Absorbing the cost before the yield ensures probes
- arrive after the import is complete.
- """
- from fastapi.testclient import TestClient
-
- with patch.object(web_server_mod, "_warm_gateway_module", _make_slow_warm(SLOW_SECONDS)):
- t0 = time.perf_counter()
- with TestClient(web_server_mod.app, raise_server_exceptions=False) as _client:
- startup_ms = (time.perf_counter() - t0) * 1000
-
- # Startup must block for at least SLOW_SECONDS (the import runs synchronously).
- # If startup were faster, the import would still be fire-and-forget (old behavior).
- threshold_ms = (SLOW_SECONDS * 1000) * 0.8
- assert startup_ms >= threshold_ms, (
- f"_lifespan did not block for the warmup import: startup took {startup_ms:.0f} ms "
- f"but slow import is {SLOW_SECONDS * 1000:.0f} ms — "
- f"warmup is not synchronous."
- )
-
-
def test_hosted_room_recovery_cannot_block_or_abort_backend_startup(monkeypatch):
from fastapi.testclient import TestClient
from tui_gateway import methods_groups
@@ -98,8 +48,12 @@ def test_hosted_room_recovery_cannot_block_or_abort_backend_startup(monkeypatch)
raise RuntimeError("state.db is locked")
monkeypatch.setattr(web_server_mod, "_warm_gateway_module", lambda: None)
- monkeypatch.setattr(methods_groups, "start_hosted_room_service", blocked_failure)
monkeypatch.setattr(methods_groups, "stop_hosted_room_service", lambda **_kwargs: True)
+ # Warm lifespan imports first so the bound below measures the recovery hook, not cold imports.
+ monkeypatch.setattr(methods_groups, "start_hosted_room_service", lambda *a, **k: None)
+ with TestClient(web_server_mod.app, raise_server_exceptions=False):
+ pass
+ monkeypatch.setattr(methods_groups, "start_hosted_room_service", blocked_failure)
before = time.perf_counter()
with TestClient(web_server_mod.app, raise_server_exceptions=False):
@@ -148,7 +102,6 @@ def test_get_status_does_not_block_event_loop():
free during the import.
"""
import httpx
- from anyio import from_thread, to_thread
results: dict[str, float] = {}
errors: list[str] = []
@@ -205,40 +158,3 @@ def test_get_status_does_not_block_event_loop():
# Test 3 — no orphan accumulation: concurrent probes all receive 200
# ---------------------------------------------------------------------------
-def test_concurrent_status_probes_all_respond():
- """
- Three concurrent /api/status requests must all receive HTTP 200.
- If the event loop were blocked, later requests would pile up and
- the desktop shell would eventually reset the connection (WinError 10054).
- """
- import httpx
-
- PROBES = 3
- responses: list[int] = []
-
- async def _run():
- transport = httpx.ASGITransport(app=web_server_mod.app)
- async with httpx.AsyncClient(
- transport=transport, base_url="http://test"
- ) as client:
- tasks = [
- client.get("/api/status", timeout=SLOW_SECONDS + 5)
- for _ in range(PROBES)
- ]
- results = await asyncio.gather(*tasks, return_exceptions=True)
- for r in results:
- if isinstance(r, Exception):
- responses.append(-1)
- else:
- responses.append(r.status_code)
-
- with patch.object(
- _web_server_lifecycle, "_resolve_restart_drain_timeout", _make_slow_drain(SLOW_SECONDS)
- ):
- asyncio.run(_run())
-
- failed = [c for c in responses if c != 200]
- assert not failed, (
- f"{len(failed)}/{PROBES} probes failed (codes: {responses}). "
- f"This would cause WinError 10054 and orphan accumulation on desktop."
- )
diff --git a/tests/hermes_cli/test_web_server_console_ws.py b/tests/hermes_cli/test_web_server_console_ws.py
index 212d7db1acb..1ebf16fde26 100644
--- a/tests/hermes_cli/test_web_server_console_ws.py
+++ b/tests/hermes_cli/test_web_server_console_ws.py
@@ -137,9 +137,8 @@ def blocking_provider():
srv.shutdown()
[email protected]("stop", ["cancel", "timeout"])
-def test_console_cancel_stops_forked_agent_request_before_reporting(console_client, monkeypatch, blocking_provider, stop):
- """#106179: cancelling (or timing out) a console command whose worker forked an AIAgent must interrupt
+def test_console_cancel_stops_forked_agent_request_before_reporting(console_client, monkeypatch, blocking_provider):
+ """#106179: cancelling a console command whose worker forked an AIAgent must interrupt
that agent — closing its in-flight provider request — and wait for the worker to exit BEFORE the
prompt reports cancelled/timeout. asyncio can only drop the waiter; the thread keeps decoding otherwise."""
import threading
@@ -170,8 +169,6 @@ def test_console_cancel_stops_forked_agent_request_before_reporting(console_clie
worker_exited.set()
monkeypatch.setattr(chat_ws, "_execute_console_line", observed_execute)
- if stop == "timeout":
- monkeypatch.setattr(chat_ws, "_CONSOLE_COMMAND_TIMEOUT_SECONDS", 2.0)
line = "curator run --consolidate --dry-run"
with console_client.websocket_connect(_url()) as conn:
@@ -182,8 +179,7 @@ def test_console_cancel_stops_forked_agent_request_before_reporting(console_clie
worker_exited.clear()
conn.send_json({"type": "confirm", "command": line})
assert blocking_provider["started"].wait(60), "forked agent never reached the provider"
- if stop == "cancel":
- conn.send_json({"type": "cancel"})
+ conn.send_json({"type": "cancel"})
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
frame = conn.receive_json()
@@ -194,7 +190,7 @@ def test_console_cancel_stops_forked_agent_request_before_reporting(console_clie
observed = (frame["status"], blocking_provider["peer_closed"].is_set(), worker_exited.is_set())
blocking_provider["release"].set() # a leaked worker (the bug) must not wedge socket teardown
worker_exited.wait(30)
- assert observed == ("cancelled" if stop == "cancel" else "timeout", True, True), (
+ assert observed == ("cancelled", True, True), (
"(status, provider request closed, worker exited) at the terminal frame")
diff --git a/tests/hermes_cli/test_web_server_cron_profiles.py b/tests/hermes_cli/test_web_server_cron_profiles.py
index 6bf3bf9de3f..d4aa23c9178 100644
--- a/tests/hermes_cli/test_web_server_cron_profiles.py
+++ b/tests/hermes_cli/test_web_server_cron_profiles.py
@@ -2,7 +2,6 @@
from concurrent.futures import ThreadPoolExecutor
import json
-from queue import Empty, SimpleQueue
import threading
import pytest
@@ -41,15 +40,6 @@ def test_standalone_jobs_remain_discoverable_for_dashboard_management(isolated_p
assert _web_server_cron._find_cron_job_profile(job["id"]) == "worker_alpha"
-def _drain_queue(q):
- values = []
- while True:
- try:
- values.append(q.get_nowait())
- except Empty:
- return values
-
-
def test_fire_cron_job_scopes_store_and_runtime_home_together(
@@ -59,7 +49,6 @@ def test_fire_cron_job_scopes_store_and_runtime_home_together(
"""A profile fire must execute and persist under the same profile home."""
from cron import jobs as cron_jobs
from cron import scheduler
- from hermes_cli import web_server
from hermes_constants import (
reset_hermes_home_override,
@@ -103,7 +92,6 @@ def test_create_registers_scheduler_inside_target_profile(
"""Dashboard create must resolve and register under the selected profile."""
from cron import jobs as cron_jobs
from cron.scheduler_provider import CronScheduler
- from hermes_cli import web_server
from hermes_constants import get_hermes_home
worker_home = isolated_profiles["worker_alpha"]
@@ -147,7 +135,6 @@ def test_dashboard_create_reports_saved_but_unregistered(
):
"""Dashboard callers can distinguish persistence from remote registration."""
from cron.scheduler import CronSchedulerRegistrationError
- from hermes_cli import web_server
job = {"id": "saved-job", "name": "saved job"}
failure = CronSchedulerRegistrationError(
@@ -188,7 +175,6 @@ def test_notify_cron_provider_scopes_store_and_runtime_home_together(
"""Provider reconciliation must observe the mutated profile, not default."""
from cron import jobs as cron_jobs
from cron import scheduler
- from hermes_cli import web_server
from hermes_constants import (
reset_hermes_home_override,
@@ -231,7 +217,6 @@ def test_notify_cron_provider_failure_is_best_effort(
isolated_profiles,
monkeypatch,
):
- from hermes_cli import web_server
class FailNotifyProvider:
@property
@@ -270,7 +255,6 @@ def test_external_provider_reconcile_fails_closed_with_multiple_profiles(
armed one-shots in the shared NAS registry. The mutation itself still
succeeds (fail-closed only skips the remote converge)."""
from cron import scheduler
- from hermes_cli import web_server
monkeypatch.setattr(scheduler, "_hermes_home", None)
monkeypatch.setattr(
@@ -319,7 +303,6 @@ def test_builtin_provider_hook_still_fires_with_multiple_profiles(
safe no-op and must NOT be blocked by the multi-profile guard."""
from cron import scheduler
from cron.scheduler_provider import InProcessCronScheduler
- from hermes_cli import web_server
monkeypatch.setattr(scheduler, "_hermes_home", None)
monkeypatch.setattr(
@@ -356,7 +339,6 @@ def test_profile_call_cannot_retarget_ticker_store_mid_write(
):
"""A dashboard profile call must not redirect a concurrent ticker save."""
from cron import jobs as cron_jobs
- from hermes_cli import web_server
default_cron = isolated_profiles["default"] / "cron"
worker_cron = isolated_profiles["worker_alpha"] / "cron"
@@ -441,7 +423,6 @@ def test_profile_call_cannot_retarget_ticker_store_mid_write(
@pytest.mark.asyncio
async def test_cron_mutation_without_profile_finds_named_profile_job(isolated_profiles):
- from hermes_cli import web_server
worker_job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -469,7 +450,6 @@ async def test_dashboard_cron_mutations_notify_selected_profile_provider(
isolated_profiles,
monkeypatch,
):
- from hermes_cli import web_server
notified_profiles = []
monkeypatch.setattr(
@@ -503,7 +483,6 @@ async def test_blueprint_instantiation_notifies_selected_profile_provider(
isolated_profiles,
monkeypatch,
):
- from hermes_cli import web_server
notified_profiles = []
monkeypatch.setattr(
@@ -530,7 +509,6 @@ async def test_trigger_cron_job_fires_only_selected_job_and_returns_refreshed_st
monkeypatch,
):
from cron import jobs as cron_jobs
- from hermes_cli import web_server
selected = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -602,7 +580,6 @@ async def test_trigger_cron_job_reports_lost_claim_as_conflict(
isolated_profiles,
monkeypatch,
):
- from hermes_cli import web_server
job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -625,7 +602,6 @@ async def test_trigger_cron_job_reports_lost_claim_as_conflict(
await _rt_cron.trigger_cron_job(job["id"], profile="worker_alpha")
assert exc.value.status_code == 409
- assert "already running" in exc.value.detail
@pytest.mark.asyncio
@@ -634,7 +610,6 @@ async def test_trigger_cron_job_forces_paused_job_atomically(
monkeypatch,
):
from cron import jobs as cron_jobs
- from hermes_cli import web_server
job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -675,7 +650,6 @@ async def test_trigger_paused_job_rejects_legacy_provider_without_mutating_job(
monkeypatch,
):
from fastapi import HTTPException
- from hermes_cli import web_server
job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -701,7 +675,6 @@ async def test_trigger_paused_job_rejects_legacy_provider_without_mutating_job(
await _rt_cron.trigger_cron_job(job["id"], profile="worker_alpha")
assert exc.value.status_code == 409
- assert "forced" in exc.value.detail.lower()
assert calls == []
persisted = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -718,7 +691,6 @@ async def test_trigger_cron_job_returns_refreshed_execution_failure(
monkeypatch,
):
from cron import jobs as cron_jobs
- from hermes_cli import web_server
job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -753,7 +725,6 @@ async def test_trigger_cron_job_returns_completed_snapshot_for_retained_oneshot(
monkeypatch,
):
from cron import jobs as cron_jobs
- from hermes_cli import web_server
job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
@@ -794,63 +765,13 @@ async def test_trigger_cron_job_returns_completed_snapshot_for_retained_oneshot(
assert retained["state"] == "completed"
-async def test_cron_profile_scan_runs_off_event_loop(isolated_profiles, monkeypatch):
- from hermes_cli import web_server
-
- worker_job = _web_server_cron._call_cron_for_profile(
- "worker_alpha",
- "create_job",
- prompt="managed by named profile",
- schedule="every 1h",
- name="thread-offload-job",
- )
-
- event_loop_thread = threading.get_ident()
- profile_scan_threads = SimpleQueue()
- worker_threads = SimpleQueue()
- original_profile_dicts = _web_server_cron._cron_profile_dicts
- original_find = _web_server_cron._find_cron_job_profile
-
- def tracking_profile_dicts():
- profile_scan_threads.put(threading.get_ident())
- return original_profile_dicts()
-
- def tracking_find(job_id):
- worker_threads.put(threading.get_ident())
- return original_find(job_id)
-
- monkeypatch.setattr(_web_server_cron, "_cron_profile_dicts", tracking_profile_dicts)
- monkeypatch.setattr(_web_server_cron, "_find_cron_job_profile", tracking_find)
-
- jobs = await _rt_cron.list_cron_jobs(profile="all")
- paused = await _rt_cron.pause_cron_job(worker_job["id"])
-
- assert any(job["id"] == worker_job["id"] for job in jobs)
- assert paused["profile"] == "worker_alpha"
- profile_scan_thread_ids = _drain_queue(profile_scan_threads)
- worker_thread_ids = _drain_queue(worker_threads)
- assert profile_scan_thread_ids
- assert worker_thread_ids
- assert all(thread_id != event_loop_thread for thread_id in profile_scan_thread_ids)
- assert all(thread_id != event_loop_thread for thread_id in worker_thread_ids)
-
-
-async def test_cron_dashboard_io_rejects_async_callables():
- from hermes_cli import web_server
- async def async_callable():
- return "nope"
- with pytest.raises(TypeError, match="only accepts sync callables"):
- await _web_server_cron._run_cron_dashboard_io(async_callable)
@pytest.mark.asyncio
async def test_update_cron_job_normalizes_dashboard_core_fields(isolated_profiles, tmp_path):
- from hermes_cli import web_server
scripts_dir = isolated_profiles["worker_alpha"] / "scripts"
scripts_dir.mkdir()
@@ -886,7 +807,6 @@ async def test_update_cron_job_normalizes_dashboard_core_fields(isolated_profile
async def test_create_cron_job_rejects_script_outside_profile_scripts(
isolated_profiles, tmp_path
):
- from hermes_cli import web_server
outside = tmp_path / "outside.py"
outside.write_text("print('nope')\n", encoding="utf-8")
@@ -902,12 +822,10 @@ async def test_create_cron_job_rejects_script_outside_profile_scripts(
)
assert exc.value.status_code == 400
- assert "inside" in exc.value.detail
@pytest.mark.asyncio
async def test_create_cron_job_rejects_empty_agent_job(isolated_profiles):
- from hermes_cli import web_server
with pytest.raises(HTTPException) as exc:
await _rt_cron.create_cron_job(
@@ -916,12 +834,10 @@ async def test_create_cron_job_rejects_empty_agent_job(isolated_profiles):
)
assert exc.value.status_code == 400
- assert "prompt, skill, or script" in exc.value.detail
@pytest.mark.asyncio
async def test_update_cron_job_no_agent_reuses_existing_script(isolated_profiles):
- from hermes_cli import web_server
scripts_dir = isolated_profiles["worker_alpha"] / "scripts"
scripts_dir.mkdir()
@@ -947,7 +863,6 @@ async def test_update_cron_job_no_agent_reuses_existing_script(isolated_profiles
@pytest.mark.asyncio
async def test_dashboard_cron_rejects_missing_context_from(isolated_profiles):
- from hermes_cli import web_server
with pytest.raises(HTTPException) as create_exc:
await _rt_cron.create_cron_job(
@@ -989,7 +904,6 @@ async def test_dashboard_cron_rejects_missing_context_from(isolated_profiles):
async def test_update_cron_job_rejects_id_mutation(isolated_profiles, monkeypatch):
"""Dashboard surfaces a 400 (not a 500 or silent rename) when an
id-mutation attempt is rejected by cron/jobs.update_job."""
- from hermes_cli import web_server
notified_profiles = []
monkeypatch.setattr(
@@ -1021,7 +935,6 @@ async def test_update_cron_job_rejects_id_mutation(isolated_profiles, monkeypatc
@pytest.mark.asyncio
async def test_cron_delete_with_profile_deletes_only_target_profile(isolated_profiles):
- from hermes_cli import web_server
default_job = _web_server_cron._call_cron_for_profile(
"default",
@@ -1049,7 +962,6 @@ async def test_cron_delete_with_profile_deletes_only_target_profile(isolated_pro
@pytest.mark.asyncio
async def test_cron_profile_validation_errors(isolated_profiles):
- from hermes_cli import web_server
with pytest.raises(HTTPException) as bad_name:
await _rt_cron.list_cron_jobs(profile="../bad")
@@ -1067,7 +979,6 @@ async def test_create_cron_job_without_profile_uses_backend_own_profile(
"""A pool backend scoped to a named profile must not default creates to
``~/.hermes`` when the request carries no explicit ``profile`` (the
Desktop app's pre-profileScoped clients sent none)."""
- from hermes_cli import web_server
monkeypatch.setenv(
"HERMES_HOME", str(isolated_profiles["worker_alpha"])
@@ -1093,7 +1004,6 @@ async def test_create_cron_job_without_profile_defaults_when_unscoped(
):
"""HERMES_HOME at the default home (or unrecognized) keeps the legacy
``default`` fallback."""
- from hermes_cli import web_server
monkeypatch.setenv("HERMES_HOME", str(isolated_profiles["default"]))
@@ -1135,7 +1045,6 @@ async def test_cron_run_history_resolves_the_jobs_owner_profile(isolated_profile
hint as the owning profile, opened the wrong profile's state.db and answered
``200 {"runs": []}``, so every job owned by another profile rendered
"No runs yet" for history that existed."""
- from hermes_cli import web_server
worker_job = _web_server_cron._call_cron_for_profile(
"worker_alpha",
diff --git a/tests/hermes_cli/test_web_server_files.py b/tests/hermes_cli/test_web_server_files.py
index efa7fb30151..344b4579f0c 100644
--- a/tests/hermes_cli/test_web_server_files.py
+++ b/tests/hermes_cli/test_web_server_files.py
@@ -226,7 +226,6 @@ def test_stream_rejects_non_media_active_content(forced_files_client):
file_path = _seed_file(client, root, name=name)
response = client.get("/api/files/stream", params={"path": str(file_path)})
assert response.status_code == 415
- assert response.json()["detail"] == "Unsupported media type"
def test_query_token_does_not_authenticate_other_endpoints(forced_files_client):
diff --git a/tests/hermes_cli/test_web_server_host_header.py b/tests/hermes_cli/test_web_server_host_header.py
index 41b8df35db5..f21fe11fc35 100644
--- a/tests/hermes_cli/test_web_server_host_header.py
+++ b/tests/hermes_cli/test_web_server_host_header.py
@@ -96,7 +96,6 @@ class TestHostHeaderMiddleware:
headers={"Host": "evil.example"},
)
assert resp.status_code == 400
- assert "Invalid Host header" in resp.json()["detail"]
finally:
# Clean up so other tests don't inherit the bound_host
if hasattr(app.state, "bound_host"):
diff --git a/tests/hermes_cli/test_web_server_messaging_profiles.py b/tests/hermes_cli/test_web_server_messaging_profiles.py
index 54e2416f8df..d396aa81a1b 100644
--- a/tests/hermes_cli/test_web_server_messaging_profiles.py
+++ b/tests/hermes_cli/test_web_server_messaging_profiles.py
@@ -229,7 +229,6 @@ class TestMultiplexPortBindingGuard:
)
if platform_id in SHARED_LISTENER_MIRROR_PLATFORMS:
assert resp.status_code == 409, platform_id
- assert "default profile" in resp.json()["detail"]
else: # served at /p/worker_alpha/<path> on the shared listener
assert resp.status_code == 200, (platform_id, resp.text)
diff --git a/tests/hermes_cli/test_web_server_profile_unification.py b/tests/hermes_cli/test_web_server_profile_unification.py
index 42e7d36b22a..a77179879c0 100644
--- a/tests/hermes_cli/test_web_server_profile_unification.py
+++ b/tests/hermes_cli/test_web_server_profile_unification.py
@@ -7,7 +7,6 @@ reads/writes land in the REQUESTED profile, the dashboard's own profile
stays untouched, and the chat PTY env is scoped via HERMES_HOME.
"""
import json
-from contextlib import contextmanager
from pathlib import Path
import pytest
@@ -17,7 +16,6 @@ import hermes_cli.config as _cfg_mod
import hermes_cli.web_server_chat as _web_server_chat
import hermes_cli.web_server_gateway as _web_server_gateway
import hermes_cli.web_server_messaging as _web_server_messaging
-import hermes_cli.web_server_profiles as _web_server_profiles
@pytest.fixture
@@ -201,28 +199,6 @@ class TestProfileScopedMcp:
# No size for tool-b → the key is simply absent (additive-optional).
assert "schema_chars" not in tools["tool-b"]
- def test_mcp_test_without_schema_chars_keeps_old_wire_shape(
- self, client, isolated_profiles, monkeypatch
- ):
- """A probe that never fills schema_chars (older code path) produces the
- exact pre-overlay tool objects — nothing new for old renderers."""
- import hermes_cli.mcp_config as mcp_config
-
- (isolated_profiles["worker_beta"] / "config.yaml").write_text(
- "mcp_servers:\n plain-srv:\n url: http://x/mcp\n",
- encoding="utf-8",
- )
- monkeypatch.setattr(
- mcp_config,
- "_probe_single_server",
- lambda name, config, connect_timeout=30, details=None: [("tool-a", "desc")],
- )
-
- resp = client.post(
- "/api/mcp/servers/plain-srv/test", params={"profile": "worker_beta"}
- )
- assert resp.status_code == 200
- assert resp.json()["tools"] == [{"name": "tool-a", "description": "desc"}]
def test_mcp_test_resolves_profile_secret_source_scope(
self, client, isolated_profiles, monkeypatch
@@ -360,46 +336,6 @@ class TestProfileScopedModel:
assert "Unknown provider 'nobox'" in resp.json()["model_error"]
- def test_model_options_uses_config_only_scope_for_selected_profile(
- self, client, monkeypatch
- ):
- """Regression (#58576): _profile_scope holds _SKILLS_PROFILE_LOCK
- across its body, and the payload build can block up to 15s on a
- models.dev cache miss — a cold request would starve concurrent
- /api/config on the same lock. The handler must scope the worker
- through _config_profile_scope (contextvar only, no lock) for the
- selected profile."""
- import hermes_cli.web_server as web_server
-
- scopes = []
-
- @contextmanager
- def _recording_config_scope(profile):
- scopes.append(("config", profile))
- yield object()
-
- @contextmanager
- def _recording_profile_scope(profile):
- scopes.append(("full", profile))
- yield object()
-
- monkeypatch.setattr(
- _web_server_profiles, "_config_profile_scope", _recording_config_scope
- )
- monkeypatch.setattr(_web_server_profiles, "_profile_scope", _recording_profile_scope)
- monkeypatch.setattr(
- "hermes_cli.inventory.load_picker_context", lambda: object()
- )
- monkeypatch.setattr(
- "hermes_cli.inventory.build_model_options_payload",
- lambda _ctx, **kwargs: {"providers": [], "model": "", "provider": ""},
- )
-
- resp = client.get("/api/model/options", params={"profile": "worker_beta"})
- assert resp.status_code == 200
- # Only the config-only scope may wrap the payload build; entering
- # _profile_scope would hold _SKILLS_PROFILE_LOCK across it (#58576).
- assert scopes == [("config", "worker_beta")]
def test_model_info_unknown_profile_404(self, client, isolated_profiles):
"""Regression: the broad except used to convert the 404 into a 200
@@ -415,7 +351,6 @@ class TestProfileScopedPostSetup:
"""Post-setup runs in a -p scoped subprocess so hooks that read
config / write per-profile state see the same HERMES_HOME the rest
of the drawer's writes targeted."""
- import hermes_cli.web_server as web_server
calls = []
@@ -440,31 +375,6 @@ class TestProfileScopedPostSetup:
["-p", "worker_beta", "tools", "post-setup", "agent_browser"]
]
- def test_post_setup_without_profile_keeps_legacy_argv(
- self, client, isolated_profiles, monkeypatch
- ):
- import hermes_cli.web_server as web_server
-
- calls = []
-
- class _FakeProc:
- pid = 777
-
- monkeypatch.setattr(
- _web_server_gateway,
- "_spawn_hermes_action",
- lambda subcommand, name: calls.append(list(subcommand)) or _FakeProc(),
- )
- monkeypatch.setattr(
- "hermes_cli.tools_config.valid_post_setup_keys",
- lambda: {"agent_browser"},
- )
- resp = client.post(
- "/api/tools/toolsets/browser/post-setup",
- json={"key": "agent_browser"},
- )
- assert resp.status_code == 200
- assert calls == [["tools", "post-setup", "agent_browser"]]
class TestProfileScopedGateway:
@@ -661,7 +571,6 @@ class TestProfileScopedTelegramOnboarding:
self, client, isolated_profiles, monkeypatch
):
import time
- import hermes_cli.web_server as web_server
with _web_server_messaging._telegram_onboarding_lock:
_web_server_messaging._telegram_onboarding_pairings.clear()
@@ -716,7 +625,6 @@ class TestProfileScopedTelegramOnboarding:
class TestProfileScopedChatPty:
def test_chat_argv_scopes_hermes_home(self, isolated_profiles, monkeypatch):
- import hermes_cli.web_server as web_server
monkeypatch.setattr(
"hermes_cli.main_tui_launch._make_tui_argv",
@@ -732,7 +640,6 @@ class TestProfileScopedChatPty:
def test_chat_argv_bridges_selected_profile_terminal_config(
self, isolated_profiles, monkeypatch
):
- import hermes_cli.web_server as web_server
(isolated_profiles["default"] / "config.yaml").write_text(
"terminal:\n"
@@ -769,7 +676,6 @@ class TestProfileScopedChatPty:
def test_chat_argv_default_profile_preserves_exported_terminal_values(
self, isolated_profiles, monkeypatch
):
- import hermes_cli.web_server as web_server
(isolated_profiles["default"] / "config.yaml").write_text(
"terminal:\n backend: docker\n",
@@ -793,7 +699,6 @@ class TestProfileScopedChatPty:
def test_chat_argv_placeholder_cwd_preserves_exported_value(
self, isolated_profiles, monkeypatch, placeholder
):
- import hermes_cli.web_server as web_server
(isolated_profiles["default"] / "config.yaml").write_text(
f"terminal:\n backend: docker\n cwd: {placeholder}\n",
@@ -847,7 +752,6 @@ class TestProfileScopedChatPty:
assert env is not None
assert env["HERMES_HOME"] == str(isolated_profiles["worker_beta"])
assert "TERMINAL_ENV" not in env
- assert "Failed to apply terminal config bridge for dashboard chat" in caplog.text
class TestProfileScopedAudio:
diff --git a/tests/hermes_cli/test_web_server_pty_import.py b/tests/hermes_cli/test_web_server_pty_import.py
index b8787af7f28..694584ab434 100644
--- a/tests/hermes_cli/test_web_server_pty_import.py
+++ b/tests/hermes_cli/test_web_server_pty_import.py
@@ -10,9 +10,7 @@ backend, POSIX gets the fcntl/termios one. Both branches must:
3. Never raise at import time when the platform-native dependency is
missing — the dashboard's non-chat tabs must keep loading.
-This test asserts the live state on whichever platform CI runs on, plus a
-source-text check confirming the branch shape is preserved so a future
-refactor can't accidentally collapse it back to a POSIX-only import.
+This test asserts the live POSIX state (the Linux CI lane).
"""
from __future__ import annotations
@@ -24,15 +22,6 @@ import pytest
import hermes_cli.web_server_chat as _web_server_chat
-def test_web_server_exposes_pty_bridge_symbols():
- """The two symbols /api/pty consumes must always exist."""
- assert hasattr(_web_server_chat, "PtyBridge")
- assert hasattr(_web_server_chat, "PtyUnavailableError")
- assert hasattr(_web_server_chat, "_PTY_BRIDGE_AVAILABLE")
- # PtyUnavailableError is always an exception class — either the real
- # one from the platform bridge, or the local fallback class.
- assert isinstance(_web_server_chat.PtyUnavailableError, type)
- assert issubclass(_web_server_chat.PtyUnavailableError, BaseException)
@pytest.mark.skipif(sys.platform.startswith("win"), reason="POSIX-only")
@@ -46,27 +35,3 @@ def test_web_server_uses_posix_pty_bridge_on_posix():
assert _web_server_chat.PtyUnavailableError is PosixErr
-def test_pty_bridge_import_block_is_platform_branched():
- """Source-level guard: a future refactor must not collapse the branch
- back to a single POSIX import. Reads the module that owns the import
- block (``web_server_chat``) directly so this fails the same way on every
- OS — the runtime symbol checks above can pass even when the branch shape
- is wrong on the current platform."""
- from hermes_cli import web_server_chat
-
- src = pytest.importorskip("inspect").getsource(web_server_chat)
- # The shape we expect (from PR #39913):
- #
- # if sys.platform.startswith("win"):
- # try:
- # from hermes_cli.win_pty_bridge import WinPtyBridge as PtyBridge, ...
- # except ImportError:
- # PtyBridge = None
- # ...
- # else:
- # try:
- # from hermes_cli.pty_bridge import PtyBridge, PtyUnavailableError
- # ...
- assert 'sys.platform.startswith("win")' in src or "sys.platform.startswith('win')" in src
- assert "from hermes_cli.win_pty_bridge import" in src
- assert "from hermes_cli.pty_bridge import" in src
diff --git a/tests/hermes_cli/test_web_server_sessiondb_eventloop.py b/tests/hermes_cli/test_web_server_sessiondb_eventloop.py
deleted file mode 100644
index 1444180f4a6..00000000000
--- a/tests/hermes_cli/test_web_server_sessiondb_eventloop.py
+++ /dev/null
@@ -1,197 +0,0 @@
-import ast
-import asyncio
-import threading
-from pathlib import Path
-
-import pytest
-
-from hermes_cli import web_server
-import hermes_cli.web_models as _web_models
-import hermes_cli.web_routers.sessions as _rt_sessions
-import hermes_cli.web_server_sessions as _web_server_sessions
-from hermes_cli import web_server_sessions
-from hermes_cli.web_routers import analytics as web_analytics
-from hermes_cli.web_routers import sessions as web_sessions
-
-
-TARGET_HANDLERS = {
- "bulk_delete_sessions_endpoint",
- "count_empty_sessions_endpoint",
- "delete_empty_sessions_endpoint",
- "get_session_latest_descendant",
- "get_session_messages",
- "delete_session_endpoint",
- "export_session_endpoint",
- "prune_sessions_endpoint",
- "get_usage_analytics",
- "get_models_analytics",
- "search_sessions",
- "get_session_stats",
- "get_session_detail",
-}
-
-
-def _call_name(call: ast.Call) -> str | None:
- if isinstance(call.func, ast.Name):
- return call.func.id
- if isinstance(call.func, ast.Attribute):
- return call.func.attr
- return None
-
-
-def test_sessiondb_handlers_open_connections_inside_executor_helpers():
- # The session and analytics route handlers were extracted to
- # web_routers/{sessions,analytics}.py; the executor helpers live in
- # web_server_sessions.py (and any left in web_server.py) — scan all
- # four modules' top-level bodies.
- handlers: dict[str, ast.AsyncFunctionDef] = {}
- top_level_helpers: dict[str, ast.FunctionDef] = {}
- for mod in (web_server, web_server_sessions, web_sessions, web_analytics):
- tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))
- for node in tree.body:
- if isinstance(node, ast.AsyncFunctionDef) and node.name in TARGET_HANDLERS:
- handlers[node.name] = node
- elif isinstance(node, ast.FunctionDef):
- top_level_helpers[node.name] = node
- assert handlers.keys() == TARGET_HANDLERS
-
- for name, handler in handlers.items():
- helpers = {
- **top_level_helpers,
- **{
- node.name: node
- for node in handler.body
- if isinstance(node, ast.FunctionDef)
- },
- }
- offloaded = {
- arg.id
- for node in ast.walk(handler)
- if isinstance(node, ast.Call)
- and _call_name(node) == "to_thread"
- for arg in node.args[:1]
- if isinstance(arg, ast.Name)
- }
- db_open_owners = {
- helper_name
- for helper_name, helper in helpers.items()
- if helper_name in offloaded
- and any(
- isinstance(node, ast.Call)
- and _call_name(node) == "_open_session_db_for_profile"
- for node in ast.walk(helper)
- )
- }
- assert db_open_owners, f"{name} does not offload SessionDB open + work"
-
-
-def test_sessiondb_opens_declare_access_mode():
- for mod in (web_server_sessions, web_sessions):
- tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))
- calls = [
- node
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and _call_name(node) == "_open_session_db_for_profile"
- ]
- assert calls
- for call in calls:
- assert any(keyword.arg == "read_only" for keyword in call.keywords)
-
-
-def test_bulk_delete_sessiondb_work_runs_off_event_loop(monkeypatch):
- loop_thread = threading.get_ident()
- db_threads: list[int] = []
- db_modes: list[bool] = []
-
- class _DB:
- def delete_sessions(self, ids):
- db_threads.append(threading.get_ident())
- assert ids == ["one", "two"]
- return 2
-
- def close(self):
- db_threads.append(threading.get_ident())
-
- def _open_db(profile=None, *, read_only):
- assert profile is None
- db_modes.append(read_only)
- return _DB()
-
- monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", _open_db)
-
- result = asyncio.run(
- _rt_sessions.bulk_delete_sessions_endpoint(
- _web_models.BulkDeleteSessions(ids=["one", "two"])
- )
- )
-
- assert result == {"ok": True, "deleted": 2}
- assert db_modes == [False]
- assert db_threads
- assert all(thread_id != loop_thread for thread_id in db_threads)
-
-
-class _ReadDB:
- """Read-only stand-in that records which thread every SessionDB call runs on."""
-
- def __init__(self, threads: list[int]):
- self._threads = threads
-
- def _hit(self, value=None):
- self._threads.append(threading.get_ident())
- return value
-
- def session_count(self, **_kw):
- return self._hit(3)
-
- def message_count(self):
- return self._hit(7)
-
- def session_count_by_source(self, **_kw):
- return self._hit({"cli": 3})
-
- def get_session(self, sid):
- return self._hit({"id": sid, "title": "t"})
-
- def get_session_rich_row(self, sid):
- return self._hit(None)
-
- def get_compression_tip(self, root_id):
- return self._hit(None)
-
- def search_sessions_by_id(self, q, **_kw):
- return self._hit([{"id": "sess-1", "preview": "hello", "started_at": 1.0}])
-
- def search_messages(self, **_kw):
- return self._hit([])
-
- def close(self):
- self._hit()
-
-
- "call",
- [
- pytest.param(lambda: _rt_sessions.search_sessions(q="hello"), id="search"),
- pytest.param(lambda: _rt_sessions.get_session_stats(), id="stats"),
- pytest.param(lambda: _rt_sessions.get_session_detail("sess-1"), id="detail"),
- ],
-)
-def test_session_read_handlers_run_sessiondb_work_off_event_loop(monkeypatch, call):
- """Regression for #60747: /search, /stats and /{id} ran FTS + SQLite inline on the
- loop thread, so a large state.db froze every other dashboard request."""
- loop_thread = threading.get_ident()
- db_threads: list[int] = []
-
- def _open_db(profile=None, *, read_only):
- assert read_only is True
- return _ReadDB(db_threads)
-
- monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", _open_db)
- monkeypatch.setattr(_rt_sessions, "_resolve_session_id", lambda db, sid: sid)
-
- asyncio.run(call())
-
- assert db_threads, "handler never touched the SessionDB"
- assert all(thread_id != loop_thread for thread_id in db_threads)
diff --git a/tests/hermes_cli/test_web_server_status_topology_cache.py b/tests/hermes_cli/test_web_server_status_topology_cache.py
index 1a493b1c85d..e1604f37702 100644
--- a/tests/hermes_cli/test_web_server_status_topology_cache.py
+++ b/tests/hermes_cli/test_web_server_status_topology_cache.py
@@ -12,7 +12,6 @@ loop, so the desktop WS never received gateway.ready and boot escalated to the
import threading
import time
-from hermes_cli import web_server
import hermes_cli.web_server_gateway as _web_server_gateway
@@ -95,24 +94,3 @@ def test_topology_cache_collapses_concurrent_scans(monkeypatch):
assert len(calls) == 1
assert len(results) == 8
assert all(r == results[0] for r in results)
-def test_topology_cache_misses_when_collector_is_swapped(monkeypatch):
- """Tests (and hot-reload scenarios) monkeypatch the collector; a swapped
- function identity must be a cache miss so stale data from the previous
- collector never leaks across the swap."""
- calls_a, calls_b = [], []
- monkeypatch.setattr(
- _web_server_gateway, "_collect_profile_gateway_topology", _fake_topology(calls_a)
- )
- _reset_cache()
- try:
- first = _web_server_gateway._collect_profile_gateway_topology_cached()
- monkeypatch.setattr(
- _web_server_gateway, "_collect_profile_gateway_topology", _fake_topology(calls_b)
- )
- second = _web_server_gateway._collect_profile_gateway_topology_cached()
- finally:
- _reset_cache()
-
- assert len(calls_a) == 1
- assert len(calls_b) == 1
- assert first is not second
diff --git a/tests/hermes_cli/test_web_server_ws_ping.py b/tests/hermes_cli/test_web_server_ws_ping.py
index ed81bce22ac..2dbdf24b474 100644
--- a/tests/hermes_cli/test_web_server_ws_ping.py
+++ b/tests/hermes_cli/test_web_server_ws_ping.py
@@ -207,43 +207,6 @@ def test_start_server_runs_on_uvicorns_loop_factory(monkeypatch):
)
-def test_start_server_keeps_bare_asyncio_run_on_posix(monkeypatch):
- """POSIX continues to serve via the plain ``asyncio.run(_serve())`` path,
- never the Windows loop-factory branch.
-
- The #50641 fix is intentionally win32-scoped to keep the loop selection
- unchanged — Python's default loop on POSIX is already a SelectorEventLoop
- (or uvloop), which is what uvicorn serves on.
-
- No platform patching: the Linux CI host is already POSIX, so this asserts
- the real host's serve path.
- """
- _stub_uvicorn(monkeypatch)
-
- # If the Windows branch were taken, the loop-factory runner would fire.
- runner_called = {"hit": False}
-
- def _fake_runner(coro, *, loop_factory=None):
- runner_called["hit"] = True
- coro.close()
-
- monkeypatch.setattr("uvicorn._compat.asyncio_run", _fake_runner, raising=False)
-
- bare_called = {"hit": False}
-
- def _fake_asyncio_run(coro):
- bare_called["hit"] = True
- coro.close()
- return None
-
- monkeypatch.setattr(asyncio, "run", _fake_asyncio_run)
-
- web_server.start_server(host="127.0.0.1", port=0, open_browser=False)
-
- assert bare_called["hit"] is True, "POSIX must serve via bare asyncio.run"
- assert runner_called["hit"] is False, (
- "POSIX must not take the Windows loop-factory branch"
- )
def test_start_server_treats_posix_keyboardinterrupt_as_clean_shutdown(monkeypatch):
diff --git a/tests/hermes_cli/test_web_ui_build.py b/tests/hermes_cli/test_web_ui_build.py
index d19ec872da2..567aa1c1ac2 100644
--- a/tests/hermes_cli/test_web_ui_build.py
+++ b/tests/hermes_cli/test_web_ui_build.py
@@ -18,9 +18,9 @@ from unittest.mock import patch
import pytest
-from hermes_cli.main_web_build import _build_web_ui, _run_npm_install_deterministic
-from hermes_cli.main_web_build import _web_ui_build_needed, _compute_web_ui_content_hash, _missing_web_build_tool, _web_ui_stamp_path, _write_web_ui_build_stamp
-from hermes_cli.update_cmd import _web_build_toolchain_ready, _web_toolchain_roots
+from hermes_cli.main_web_build import _build_web_ui
+from hermes_cli.main_web_build import _web_ui_build_needed, _missing_web_build_tool, _write_web_ui_build_stamp
+from hermes_cli.update_cmd import _web_build_toolchain_ready
@pytest.fixture(autouse=True)
@@ -84,26 +84,7 @@ class TestWebUIBuildNeeded:
- def test_content_hash_is_deterministic(self, tmp_path):
- web_dir, _ = _make_web_dir(tmp_path)
- (web_dir / "src").mkdir(parents=True, exist_ok=True)
- (web_dir / "src" / "App.tsx").write_text("export const A = 1\n")
- root = self._root(web_dir)
- h1 = _compute_web_ui_content_hash(root, web_dir)
- h2 = _compute_web_ui_content_hash(root, web_dir)
- assert h1 == h2
- assert len(h1) == 64
-
- def test_write_stamp_creates_file_with_hash(self, tmp_path):
- import json as _json
- web_dir, _ = _make_web_dir(tmp_path)
- (web_dir / "src").mkdir(parents=True, exist_ok=True)
- (web_dir / "src" / "App.tsx").write_text("export const A = 1\n")
- self._stamp_current(web_dir)
- stamp = _web_ui_stamp_path()
- assert stamp.is_file()
- data = _json.loads(stamp.read_text())
- assert data["contentHash"] == _compute_web_ui_content_hash(self._root(web_dir), web_dir)
+
@@ -146,7 +127,6 @@ class TestBuildWebUISkipsWhenFresh:
args, kwargs = mock_run.call_args
assert "--workspace" not in args[0]
assert Path(args[0][0]).name in {"npm", "npm.cmd"}
- assert args[0][1:] == ["ci", "--include=dev", "--silent", "--prefer-offline"]
assert kwargs["cwd"] == web_dir
assert "ESBUILD_BINARY_PATH" not in kwargs["env"]
assert "ESBUILD_BINARY_PATH" not in mock_build.call_args.kwargs["env"]
@@ -204,29 +184,6 @@ class TestBuildWebUISkipsWhenFresh:
assert "--include-workspace-root" in cmd
assert "web" in cmd
- def test_web_build_uses_idle_timeout_helper(self, tmp_path):
- """npm run build now goes through _run_with_idle_timeout (issue #33788).
-
- The install step keeps its capture_output behavior (the existing
- retry-on-EPERM contract depends on it); only the long-running build
- step is streamed + idle-killed.
- """
- web_dir, _ = _make_web_dir(tmp_path)
-
- install_cp = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
- build_cp = __import__("subprocess").CompletedProcess([], 0, stdout="", stderr="")
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
- patch("hermes_cli.main.subprocess.run", return_value=install_cp), \
- patch("hermes_cli.main_web_build._run_with_idle_timeout", return_value=build_cp) as mock_idle:
- result = _build_web_ui(web_dir)
-
- assert result is True
- # Build was invoked through the idle-timeout helper, not subprocess.run.
- mock_idle.assert_called_once()
- args, kwargs = mock_idle.call_args
- # Positional: [npm, "run", "build"]; cwd passed as kwarg.
- assert args[0] == ["/usr/bin/npm", "run", "build"]
- assert kwargs["cwd"] == web_dir
class TestBuildWebUIRetryAndStaleFallback:
@@ -240,7 +197,7 @@ class TestBuildWebUIRetryAndStaleFallback:
build_fail = Subprocess.CompletedProcess([], 1, stdout="EPERM", stderr="")
build_ok = Subprocess.CompletedProcess([], 0, stdout="", stderr="")
with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
- patch("hermes_cli.main_web_build._time.sleep") as mock_sleep, \
+ patch("hermes_cli.main_web_build._time.sleep"), \
patch("hermes_cli.main.subprocess.run", return_value=install_ok), \
patch("hermes_cli.main_web_build._run_with_idle_timeout",
side_effect=[build_fail, build_ok]) as mock_idle:
@@ -248,7 +205,6 @@ class TestBuildWebUIRetryAndStaleFallback:
assert result is True
assert mock_idle.call_count == 2 # build + retry
- mock_sleep.assert_called_once_with(3)
def test_falls_back_to_stale_dist_when_retry_also_fails(self, tmp_path, capsys):
web_dir, dist_dir = _make_web_dir(tmp_path)
@@ -270,7 +226,6 @@ class TestBuildWebUIRetryAndStaleFallback:
# because cmd_dashboard passes fatal=True and is the primary caller.
assert result is True
out = capsys.readouterr().out
- assert "serving stale dist as fallback" in out
assert "vite ENOMEM" in out # combined output surfaced to user
@@ -318,9 +273,6 @@ class TestBuildWebUIFlock:
assert result is True
mock_run.assert_not_called() # fresh after the wait -> no rebuild
- def test_lock_file_is_gitignored(self):
- gitignore = Path(__file__).resolve().parents[2] / ".gitignore"
- assert ".web_ui_build.lock" in gitignore.read_text(encoding="utf-8")
def _link_shims(bin_dir: Path, *names: str) -> None:
@@ -347,17 +299,12 @@ class TestWebBuildToolchainReady:
assert _web_build_toolchain_ready(web_dir, tmp_path) is True
- @pytest.mark.parametrize("shim", ["tsc.cmd", "tsc.ps1", "tsc.exe"])
- def test_windows_shim_extensions_count(self, tmp_path, shim):
+ def test_windows_shim_extensions_count(self, tmp_path):
web_dir, _ = _make_web_dir(tmp_path)
- _link_shims(tmp_path / "node_modules" / ".bin", shim, "vite.cmd")
+ _link_shims(tmp_path / "node_modules" / ".bin", "tsc.cmd", "vite.cmd")
assert _web_build_toolchain_ready(web_dir, tmp_path) is True
-class TestWebToolchainRoots:
- def test_searches_the_package_and_its_workspace_root(self, tmp_path):
- web_dir, _ = _make_web_dir(tmp_path)
- assert _web_toolchain_roots(web_dir) == (web_dir, tmp_path)
class TestMissingWebBuildTool:
diff --git a/tests/hermes_cli/test_webhook_cli.py b/tests/hermes_cli/test_webhook_cli.py
index 0ac55bce7c9..9f13b063059 100644
--- a/tests/hermes_cli/test_webhook_cli.py
+++ b/tests/hermes_cli/test_webhook_cli.py
@@ -95,7 +95,6 @@ class TestSubscribe:
webhook_action="subscribe", name="notifier", route_profile="missing"
))
- assert "does not exist" in capsys.readouterr().out
assert _load_subscriptions()["notifier"]["secret"] == "original"
@@ -122,7 +121,6 @@ class TestCronJobSubscribe:
webhook_command(_make_args(
webhook_action="subscribe", name="ev", cron_job="nope"
))
- assert "no cron job matches" in capsys.readouterr().out
assert "ev" not in _load_subscriptions()
def test_cron_job_plus_deliver_only_rejected(self, capsys):
@@ -133,21 +131,9 @@ class TestCronJobSubscribe:
deliver_only=True,
deliver="telegram",
))
- assert "mutually exclusive" in capsys.readouterr().out
assert "ev" not in _load_subscriptions()
-class TestList:
-
- def test_with_entries(self, capsys):
- webhook_command(_make_args(webhook_action="subscribe", name="a"))
- webhook_command(_make_args(webhook_action="subscribe", name="b"))
- capsys.readouterr() # clear
- webhook_command(_make_args(webhook_action="list"))
- out = capsys.readouterr().out
- assert "2 webhook" in out
- assert "a" in out
- assert "b" in out
class TestRemove:
@@ -204,22 +190,5 @@ class TestWebhookEnabledGate:
out = capsys.readouterr().out
assert "not enabled" in out.lower()
- def test_allows_when_enabled(self, capsys):
- # _is_webhook_enabled already patched to True by autouse fixture
- webhook_command(_make_args(webhook_action="subscribe", name="allowed"))
- out = capsys.readouterr().out
- assert "Created" in out
- assert "allowed" in _load_subscriptions()
- def test_real_check_disabled(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.webhook._get_webhook_config",
- lambda: {},
- )
- monkeypatch.setattr(
- "hermes_cli.webhook._is_webhook_enabled",
- lambda: bool({}.get("enabled")),
- )
- import hermes_cli.webhook as wh_mod
- assert wh_mod._is_webhook_enabled() is False
diff --git a/tests/hermes_cli/test_win_pty_bridge.py b/tests/hermes_cli/test_win_pty_bridge.py
index 465880055cd..d7f0ff9936d 100644
--- a/tests/hermes_cli/test_win_pty_bridge.py
+++ b/tests/hermes_cli/test_win_pty_bridge.py
@@ -64,16 +64,7 @@ class TestWinPtyBridgeUnavailable:
web_server platform branch doesn't blow up at import time when pywinpty
is missing or the host isn't Windows."""
- def test_error_is_importable_and_carries_message(self):
- err = PtyUnavailableError("conpty missing")
- assert "conpty" in str(err)
-
- def test_bridge_class_is_importable(self):
- # The platform-branched import in web_server.py relies on this:
- # from hermes_cli.win_pty_bridge import WinPtyBridge, PtyUnavailableError
- # Both symbols must always exist; ``is_available()`` is the gate.
- assert WinPtyBridge is not None
- assert callable(WinPtyBridge.is_available)
+
@pytest.mark.asyncio
async def test_write_has_nonblocking_async_contract(self):
diff --git a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
index 191793d02c7..877acecd287 100644
--- a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
+++ b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
@@ -18,15 +18,10 @@ does not restart the messaging gateway itself.
from __future__ import annotations
-import json
-from hermes_cli import gateway as hermes_gateway
-from hermes_cli import gateway_windows
from hermes_cli import main as cli_main
-import hermes_cli.main_install_repair as main_install_repair
from hermes_cli import process_identity
from hermes_cli import update_cmd
-import hermes_cli.update_cmd_windows as update_cmd_windows
def _live_serve_ledger_entry() -> dict:
@@ -95,253 +90,3 @@ def test_orphaned_control_plane_does_not_own_lifecycle(monkeypatch):
assert update_cmd._desktop_owns_gateway_lifecycle() is False
-def test_pause_skips_cold_start_plan_when_desktop_owns_lifecycle(monkeypatch):
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(
- hermes_gateway, "find_windows_gateway_services", lambda **_k: []
- )
- monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
- monkeypatch.setattr(gateway_windows, "attested_death_generation", lambda **_k: None)
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
- monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
-
- assert update_cmd._pause_windows_gateways_for_update() is None
-
-
-def test_pause_still_cold_starts_when_autostart_and_no_desktop_owner(monkeypatch):
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(
- hermes_gateway, "find_windows_gateway_services", lambda **_k: []
- )
- monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: False)
- monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: False)
-
- token = update_cmd._pause_windows_gateways_for_update()
-
- assert token == {
- "resume_needed": True,
- "profiles": {},
- "unmapped_pids": [],
- "unmapped": [],
- "cold_start_if_installed": True,
- }
-
-
-def test_cold_start_aborts_when_desktop_owns_lifecycle(monkeypatch):
- spawned = []
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(gateway_windows, "attested_death_generation", lambda **_k: None)
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
- monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
- monkeypatch.setattr(
- gateway_windows, "_spawn_detached", lambda: spawned.append(1) or 4242
- )
-
- update_cmd._cold_start_windows_gateway_after_update()
-
- assert spawned == []
-
-
-def test_attested_dead_gateway_survives_desktop_ownership_and_marker_is_consumed_on_spawn(
- monkeypatch, tmp_path, capsys
-):
- """#109538: the Desktop hand-off can kill the running gateway moments before update
- discovery runs, so a dead start attestation is the surviving "a gateway was up"
- evidence. It must keep the plan AND survive the spawn-time ownership re-check.
- Once the spawn happens the marker is consumed, so a stale crash marker cannot
- re-authorize a cold start against Desktop ownership on a later update."""
- monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: str(tmp_path))
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(hermes_gateway, "find_windows_gateway_services", lambda **_k: [])
- monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
- monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
- gateway_windows._write_start_attestation([555], "direct spawn (PID 555)")
- marker = tmp_path / "state" / "gateway.start-attestation.json"
-
- token = update_cmd._pause_windows_gateways_for_update()
-
- generation = token.pop("attested_generation")
- assert generation == json.loads(marker.read_text(encoding="utf-8"))["generation"]
- assert token == {
- "resume_needed": True,
- "profiles": {},
- "unmapped_pids": [],
- "unmapped": [],
- "cold_start_if_installed": True,
- }
- token["attested_generation"] = generation
- assert marker.exists() # plan-time probe is read-only
-
- spawned = []
- monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda: spawned.append(1) or 4242)
- monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: [4242])
- monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)
-
- # A token written by pre-generation code and resumed across this very update carries no
- # ``attested_generation`` key: the marker is probed again rather than the spawn skipped.
- legacy_token = {k: v for k, v in token.items() if k != "attested_generation"}
- assert update_cmd._cold_start_windows_gateway_after_update(legacy_token) is True
- assert spawned == [1]
- assert "Gateway started via cold-start after update (PID: 4242)" in capsys.readouterr().out
- assert not marker.exists() # consumed by the spawn
- assert gateway_windows.attested_death_generation(current_pids=[]) is None
-
-
-def test_cold_start_is_authorized_by_the_token_generation_not_the_mutable_marker(
- monkeypatch, tmp_path, capsys
-):
- """#110020 review (a): the marker is a one-shot that a concurrent ``hermes gateway status``
- consumes between plan and execution. The spawn must still happen (authority lives on the
- token), and a *newer* marker written by a concurrent ``hermes gateway start`` must not be
- consumed as if it were ours."""
- monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: str(tmp_path))
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(hermes_gateway, "find_windows_gateway_services", lambda **_k: [])
- monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
- monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
- gateway_windows._write_start_attestation([555], "direct spawn (PID 555)")
- marker = tmp_path / "state" / "gateway.start-attestation.json"
- token = update_cmd._pause_windows_gateways_for_update()
- assert token["attested_generation"]
-
- # Concurrent ``hermes gateway status`` consumed the marker...
- assert gateway_windows.check_start_attestation(current_pids=[]) is not None
- assert not marker.exists()
- # ...and a concurrent ``hermes gateway start`` wrote a fresh one for its own PID.
- gateway_windows._write_start_attestation([777], "direct spawn (PID 777)")
- newer = json.loads(marker.read_text(encoding="utf-8"))["generation"]
- assert newer != token["attested_generation"]
-
- spawned = []
- monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda: spawned.append(1) or 4242)
- monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: [4242])
- monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)
-
- assert update_cmd._cold_start_windows_gateway_after_update(token) is True
- assert spawned == [1] # authorized by the token, not by the (consumed) marker
- assert json.loads(marker.read_text(encoding="utf-8"))["generation"] == newer # not ours to consume
-
-
-def _running_beta_pause_fixture(monkeypatch, tmp_path):
- """Windows update with ``beta`` (PID 777) running and the default profile home at ``tmp_path``."""
- from types import SimpleNamespace
- import hermes_cli.profiles as profiles_mod
-
- homes = {"default": tmp_path, "beta": tmp_path / "profiles" / "beta"}
- homes["beta"].mkdir(parents=True)
- monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: str(tmp_path))
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
- monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
- beta = SimpleNamespace(pid=777, profile="beta")
- monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({777: beta}, [], set(), [777]))
- monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({"beta": 777}, [777], []))
- monkeypatch.setattr(cli_main, "_venv_launcher_ancestors", lambda pids: [])
- monkeypatch.setattr(cli_main, "_wait_for_windows_update_gateway_exit", lambda pids, timeout: set())
- monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: "default")
- monkeypatch.setattr(profiles_mod, "profiles_to_serve", lambda multiplex, **_kw: [(n, h) for n, h in homes.items() if n in ("default", "beta")])
- monkeypatch.setattr(profiles_mod, "get_profile_dir", lambda name: homes[name])
- # Resume side.
- monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)
- monkeypatch.setattr(hermes_gateway, "launch_detached_profile_gateway_restart", lambda p, o: True)
- ready_probes: list = []
- monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: ready_probes.append(k) or [4242])
- homes["_ready_probes"] = ready_probes
- return homes
-
-
-def test_dead_attested_default_is_cold_started_beside_running_beta(monkeypatch, tmp_path, capsys):
- """#110959: the all-or-nothing plan never ran while ``beta`` was alive, so a default gateway
- that died after a ✓ stayed down after the update. Its dead attestation must become a per-profile
- cold-start obligation on the token; resume spawns it under the default home and consumes only
- that generation, while ``beta`` still goes through the ordinary relaunch."""
- homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
- gateway_windows._write_start_attestation([555], "direct spawn (PID 555)")
- marker = tmp_path / "state" / "gateway.start-attestation.json"
- generation = json.loads(marker.read_text(encoding="utf-8"))["generation"]
-
- token = update_cmd._pause_windows_gateways_for_update()
-
- assert token["profiles"] == {"beta": 777}
- assert token["cold_start_profiles"] == {"default": generation}
- assert marker.exists() # plan-time probe is read-only
-
- spawned = []
- monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda **k: spawned.append(k) or 4242)
- update_cmd._resume_windows_gateways_after_update(token)
-
- assert spawned == [{"home": homes["default"]}]
- # Readiness is probed in the default profile's own home: live ``beta`` must not vouch for it.
- assert {"home": homes["default"]} in homes["_ready_probes"]
- # The authorizing generation is consumed and the NEW PID is attested in the same profile home,
- # so a death after this CLI exits stays visible to the next update.
- reattested = json.loads(marker.read_text(encoding="utf-8"))
- assert (reattested["pids"], reattested["generation"] != generation) == ([4242], True)
- assert "cold_start_profiles" not in token
- assert token["relaunched_profiles"] == ["beta"]
- assert token["resume_needed"] is False
- out = capsys.readouterr().out
- assert "Gateway profile default started via cold-start after update (PID: 4242)" in out
-
-
-def test_every_dead_attested_profile_is_cold_started_when_nothing_runs(monkeypatch, tmp_path):
- """Nothing running, active profile exited cleanly (plan → None), ``beta`` dead-attested: beta still
- gets a token and a spawn. And when BOTH owe a spawn, the fleet-wide active cold-start runs FIRST —
- a beta spawned earlier would satisfy its any-live-gateway guard and the active profile would stay down."""
- homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
- monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({}, [], set(), []))
- monkeypatch.setattr(update_cmd_windows, "_windows_cold_start_plan", lambda: None)
- gateway_windows._write_start_attestation([556], "direct spawn (PID 556)", home=homes["beta"])
- beta_marker = homes["beta"] / "state" / "gateway.start-attestation.json"
- beta_generation = json.loads(beta_marker.read_text(encoding="utf-8"))["generation"]
-
- token = update_cmd._pause_windows_gateways_for_update()
- assert token["cold_start_profiles"] == {"beta": beta_generation}
- assert token["profiles"] == {}
-
- order = []
- monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda **k: order.append(k.get("home")) or 4242)
- monkeypatch.setattr(
- cli_main, "_cold_start_windows_gateway_after_update", lambda token=None: order.append("active") or True)
- token["cold_start_if_installed"] = True # both owe a spawn
- update_cmd._resume_windows_gateways_after_update(token)
- assert order == ["active", homes["beta"]]
- assert json.loads(beta_marker.read_text(encoding="utf-8"))["generation"] != beta_generation
- assert token["resume_needed"] is False
-
-
-def test_service_supervised_running_profile_is_not_cold_started(monkeypatch, tmp_path):
- """A profile whose gateway is alive under an SCM service is skipped by the socket pause, so it is
- absent from ``token["profiles"]``; it must still count as RUNNING for the per-profile probe or its
- live attestation reads as dead and resume spawns a second, unsupervised gateway beside the
- restarted service."""
- from types import SimpleNamespace
-
- homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
- svc_proc = SimpleNamespace(pid=900, profile="beta", path=homes["beta"])
- service = SimpleNamespace(name="HermesGw-beta", profile="beta", service_pid=800, gateway_pid=900,
- descendant_identities=(), service_create_time=1.0, gateway_create_time=2.0)
- monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({900: svc_proc}, [service], {900}, [900]))
- monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({}, [], []))
- monkeypatch.setattr(update_cmd, "_stop_windows_gateway_service", lambda *a, **k: None)
- gateway_windows._write_start_attestation([900], "direct spawn (PID 900)", home=homes["beta"])
-
- token = update_cmd._pause_windows_gateways_for_update()
-
- assert token["services"] == ["HermesGw-beta"]
- assert token["profiles"] == {}
- assert "cold_start_profiles" not in token
diff --git a/tests/hermes_cli/test_windows_gateway_job_teardown.py b/tests/hermes_cli/test_windows_gateway_job_teardown.py
index 78d9dd5187e..48bc6519739 100644
--- a/tests/hermes_cli/test_windows_gateway_job_teardown.py
+++ b/tests/hermes_cli/test_windows_gateway_job_teardown.py
@@ -20,16 +20,9 @@ Two fixes under test:
updater's Job Object teardown.
"""
-from unittest.mock import patch
-import pytest
import hermes_cli.gateway as gateway
-import hermes_cli.gateway_windows as gateway_windows
-import hermes_cli.main as hm
-import hermes_cli.main_install_repair as main_install_repair
-from hermes_cli._subprocess_compat import _WINDOWS_GATEWAY_BREAKAWAY_ENV
-from hermes_cli.update_cmd import _resume_windows_gateways_after_update
# ---------------------------------------------------------------------------
@@ -60,35 +53,7 @@ def _captured_watcher_source(monkeypatch) -> str:
class TestWatcherRespawnTemplate:
- def test_respawn_stdio_routed_to_sidecar_log_not_devnull(self, monkeypatch):
- """DEVNULL swallowed the dying gateway's last words (#48820 4th
- repro: 'Zero trace anywhere ... because the watcher respawns with
- stdout=DEVNULL, stderr=DEVNULL')."""
- src = _captured_watcher_source(monkeypatch)
- assert "gateway-stdio.log" in src, (
- "watcher respawn must route stray stdout/stderr to the same "
- "sidecar log _spawn_detached uses, so a gateway killed moments "
- "after respawn leaves a trace"
- )
- # DEVNULL remains only as the fallback when the log dir is
- # unavailable — the popen kwargs must not be hardwired to it.
- assert '"stdout": _stdio_target' in src
- assert '"stderr": _stdio_target' in src
-
- def test_respawn_stamps_breakaway_state_like_spawn_detached(
- self, monkeypatch
- ):
- """The respawned gateway must carry _HERMES_GATEWAY_BREAKAWAY=1 on
- the primary (breakaway) spawn and =0 on the no-breakaway fallback,
- mirroring gateway_windows._spawn_detached — without the stamp, a
- job-teardown kill is indistinguishable from any other silent death
- in the exit diagnostics."""
- src = _captured_watcher_source(monkeypatch)
- assert "_WINDOWS_GATEWAY_BREAKAWAY_ENV" in src
- assert _WINDOWS_GATEWAY_BREAKAWAY_ENV == "_HERMES_GATEWAY_BREAKAWAY"
- # Primary stamps "1", the OSError fallback stamps "0".
- assert '_WINDOWS_GATEWAY_BREAKAWAY_ENV: "1"' in src
- assert '_WINDOWS_GATEWAY_BREAKAWAY_ENV: "0"' in src
+
def test_respawn_source_compiles(self, monkeypatch):
"""The inlined -c template is built via str.format over a
@@ -96,96 +61,9 @@ class TestWatcherRespawnTemplate:
src = _captured_watcher_source(monkeypatch)
compile(src, "<watcher>", "exec")
- def test_watcher_fallback_retry_preserved(self, monkeypatch):
- """The ERROR_ACCESS_DENIED retry without breakaway must survive."""
- src = _captured_watcher_source(monkeypatch)
- assert "windows_detach_flags_without_breakaway" in src
-
# ---------------------------------------------------------------------------
# 2. Post-update resume liveness gate
# ---------------------------------------------------------------------------
-def _token(profiles: dict) -> dict:
- return {
- "resume_needed": True,
- "profiles": profiles,
- "unmapped_pids": [],
- "unmapped": [],
- }
-
-
-class TestResumeLivenessGate:
- @pytest.fixture(autouse=True)
- def _windows(self, monkeypatch):
- monkeypatch.setattr(hm, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hm, "_refresh_windows_gateway_launchers", lambda: None)
- monkeypatch.setattr(
- gateway, "launch_detached_profile_gateway_restart", lambda *_a: True
- )
- monkeypatch.setattr(
- gateway, "launch_detached_gateway_restart_by_cmdline", lambda *_a: True
- )
-
- def test_dead_respawn_fails_the_resume_instead_of_printing_check(
- self, monkeypatch
- ):
- """No stable gateway after the relaunch → the resume raises (update
- marked incomplete) instead of printing '✓ Restarting'. This is the
- exact #48820 3rd/4th-repro hole: spawn succeeded, gateway died
- within seconds, success was reported, platforms were offline for
- 12.5 hours."""
- monkeypatch.setattr(
- gateway_windows, "_wait_for_gateway_ready", lambda **_kw: []
- )
- token = _token({"default": 1111})
- printed = []
- with patch("builtins.print", side_effect=lambda *a, **k: printed.append(a)):
- with pytest.raises(RuntimeError, match="not verified alive"):
- _resume_windows_gateways_after_update(token)
-
- text = " ".join(str(a) for a in printed)
- assert "✓ Restarting" not in text
- assert "could not be verified" in text
- # The profile stays on the token so retry/reporting still sees it.
- assert token["profiles"] == {"default": 1111}
- assert token["resume_needed"] is True
-
- def test_live_respawn_prints_check_and_writes_attestation(self, monkeypatch):
- monkeypatch.setattr(
- gateway_windows, "_wait_for_gateway_ready", lambda **_kw: [777]
- )
- attested = {}
- monkeypatch.setattr(
- gateway_windows,
- "_write_start_attestation",
- lambda pids, via: attested.update(pids=pids, via=via),
- )
- token = _token({"default": 1111})
- printed = []
- with patch("builtins.print", side_effect=lambda *a, **k: printed.append(a)):
- _resume_windows_gateways_after_update(token)
-
- text = " ".join(str(a) for a in printed)
- assert "✓ Restarting" in text
- assert attested == {"pids": [777], "via": "post-update relaunch"}
- assert token["resume_needed"] is False
-
- def test_liveness_poll_scans_all_profiles(self, monkeypatch):
- """The resume relaunches the whole fleet; the verification must not
- be scoped to the active profile."""
- seen = {}
-
- def fake_wait(**kwargs):
- seen.update(kwargs)
- return [777]
-
- monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", fake_wait)
- monkeypatch.setattr(
- gateway_windows, "_write_start_attestation", lambda *_a, **_kw: None
- )
- with patch("builtins.print"):
- _resume_windows_gateways_after_update(_token({"work": 2222}))
- assert seen.get("all_profiles") is True
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 2594ff8d48d..00000000000
--- a/tests/hermes_cli/test_windows_native_docs.py
+++ /dev/null
@@ -1,22 +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()
- install = Path("scripts/install.ps1").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
- # Installer exposes $HermesHome\bin, and must copy the launchers into it.
- assert '$hermesBin = "$HermesHome\\bin"' in install
- assert "hermes.exe" in install and "hermes-acp.exe" in install
- # Guard against regressions to either legacy layout.
- assert '$hermesBin = "$InstallDir\\venv\\Scripts"' not in install
- assert '$hermesBin = "$InstallDir\\bin"' not in install
diff --git a/tests/hermes_cli/test_windows_update_restart_reconciliation.py b/tests/hermes_cli/test_windows_update_restart_reconciliation.py
index e6c63c55d53..4b9b465f1eb 100644
--- a/tests/hermes_cli/test_windows_update_restart_reconciliation.py
+++ b/tests/hermes_cli/test_windows_update_restart_reconciliation.py
@@ -23,26 +23,8 @@ from unittest.mock import patch
import pytest
-import hermes_cli.gateway as gateway
import hermes_cli.gateway_windows as gateway_windows
import hermes_cli.main as hm
-import hermes_cli.main_install_repair as main_install_repair
-from hermes_cli.update_cmd import _resume_windows_gateways_after_update
-from hermes_cli.update_inventory import (
- RuntimeRecord,
- UpdatePlan,
- match_runtime_outcomes,
- report_unaccounted_runtimes,
-)
-
-
-def _token(profiles: dict) -> dict:
- return {
- "resume_needed": True,
- "profiles": profiles,
- "unmapped_pids": [],
- "unmapped": [],
- }
@pytest.fixture(autouse=True)
@@ -60,117 +42,6 @@ def _stub_post_relaunch_liveness(monkeypatch):
)
-def test_resume_records_successfully_relaunched_profiles_on_the_token(monkeypatch):
- monkeypatch.setattr(hm, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hm, "_refresh_windows_gateway_launchers", lambda: None)
- monkeypatch.setattr(
- gateway, "launch_detached_profile_gateway_restart", lambda *_a: True
- )
- monkeypatch.setattr(
- gateway, "launch_detached_gateway_restart_by_cmdline", lambda *_a: True
- )
-
- token = _token({"default": 1111, "work": 2222})
- with patch("builtins.print"):
- _resume_windows_gateways_after_update(token)
-
- assert sorted(token["relaunched_profiles"]) == ["default", "work"]
-
-
-def test_resume_omits_profiles_whose_relaunch_failed(monkeypatch):
- """A profile whose relaunch genuinely fails must NOT be marked
- 'relaunched' — it needs to keep surfacing as unaccounted so the user is
- told to restart it manually (Windows has no watcher to recover it)."""
- monkeypatch.setattr(hm, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hm, "_refresh_windows_gateway_launchers", lambda: None)
-
- def _relaunch(profile, _old_pid):
- return profile == "default" # "work" fails to relaunch
-
- monkeypatch.setattr(
- gateway, "launch_detached_profile_gateway_restart", _relaunch
- )
- monkeypatch.setattr(
- gateway, "launch_detached_gateway_restart_by_cmdline", lambda *_a: True
- )
-
- token = _token({"default": 1111, "work": 2222})
- with patch("builtins.print"):
- # Fail-closed contract: a profile whose relaunch failed
- # raises so the update is marked incomplete (the caller catches,
- # records the phase error, and exits 1 in gateway mode).
- with pytest.raises(RuntimeError, match="Could not restart every paused"):
- _resume_windows_gateways_after_update(token)
-
- assert token["relaunched_profiles"] == ["default"]
-
-
-def test_merged_windows_relaunch_resolves_as_restarted_not_unaccounted(monkeypatch):
- """End-to-end shape of the actual fix: the token's relaunched_profiles,
- merged into the shared list _cmd_update_impl passes to
- match_runtime_outcomes, must turn a Windows gateway's plan row from
- 'unaccounted' (loud warning + exit 1) into 'restarted' (clean)."""
- monkeypatch.setattr(hm, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(hm, "_refresh_windows_gateway_launchers", lambda: None)
- monkeypatch.setattr(
- gateway, "launch_detached_profile_gateway_restart", lambda *_a: True
- )
- monkeypatch.setattr(
- gateway, "launch_detached_gateway_restart_by_cmdline", lambda *_a: True
- )
-
- old_pid = 4242
- token = _token({"default": old_pid})
- with patch("builtins.print"):
- _resume_windows_gateways_after_update(token)
-
- # collect_runtime_inventory() would have recorded the pre-update PID —
- # the plan is built BEFORE the pause/relaunch, so it still names the old
- # pid even though a fresh process now owns the port.
- plan = UpdatePlan()
- plan.runtimes = [
- RuntimeRecord(
- kind="gateway", profile="default", pid=old_pid, supervisor="manual",
- restart_via="manual",
- )
- ]
-
- # Without the merge (the pre-fix state): unaccounted, escalates.
- pre_fix_outcomes = match_runtime_outcomes(
- plan, restarted_services=[], relaunched_profiles=[],
- externally_supervised_profiles=[], killed_pids=set(), failed_units=[],
- )
- assert pre_fix_outcomes[0]["outcome"] == "unaccounted"
- assert report_unaccounted_runtimes(pre_fix_outcomes) is True
-
- # With the merge _cmd_update_impl now performs: restarted, clean.
- relaunched_profiles: list = []
- for profile in token.get("relaunched_profiles") or []:
- if profile not in relaunched_profiles:
- relaunched_profiles.append(profile)
-
- post_fix_outcomes = match_runtime_outcomes(
- plan, restarted_services=[], relaunched_profiles=relaunched_profiles,
- externally_supervised_profiles=[], killed_pids=set(), failed_units=[],
- )
- assert post_fix_outcomes[0]["outcome"] == "restarted"
- assert report_unaccounted_runtimes(post_fix_outcomes) is False
-
-
-def test_resume_with_no_relaunched_profiles_key_does_not_crash_the_merge():
- """A token from an early-return path (e.g. cold-start, no profiles) may
- never gain a 'relaunched_profiles' key at all — the merge in
- _cmd_update_impl must tolerate that (.get(...) or [])."""
- token = {"resume_needed": False}
- relaunched_profiles: list = []
- for profile in token.get("relaunched_profiles") or []:
- relaunched_profiles.append(profile)
- assert relaunched_profiles == []
-
-
def test_merge_helper_reads_token_keys_into_restart_outcome(monkeypatch):
"""Drive the real merge helper (not a mirror): the Windows resume token's
``relaunched_profiles`` / ``restarted_services`` / ``service_profiles`` /
diff --git a/tests/hermes_cli/test_worktree.py b/tests/hermes_cli/test_worktree.py
index b1ba38e380d..ff7eb653778 100644
--- a/tests/hermes_cli/test_worktree.py
+++ b/tests/hermes_cli/test_worktree.py
@@ -5,12 +5,10 @@ Verifies worktree creation, cleanup, .worktreeinclude handling,
"""
import os
-import shutil
import subprocess
import pytest
from hermes_cli import worktree_ops
-from pathlib import Path
@pytest.fixture
@@ -70,736 +68,19 @@ def git_repo_no_remote(tmp_path):
return repo
-def git_repo_remote_no_tracking(tmp_path):
- """Create a temporary git repo with a remote but no remote-tracking refs."""
- repo = tmp_path / "test-repo-remote-no-tracking"
- repo.mkdir()
- subprocess.run(["git", "init"], cwd=repo, capture_output=True)
- subprocess.run(
- ["git", "config", "user.email", "[email protected]"],
- cwd=repo, capture_output=True,
- )
- subprocess.run(
- ["git", "config", "user.name", "Test"],
- cwd=repo, capture_output=True,
- )
- (repo / "README.md").write_text("# Test Repo\n")
- subprocess.run(["git", "add", "."], cwd=repo, capture_output=True)
- subprocess.run(
- ["git", "commit", "-m", "Initial commit"],
- cwd=repo, capture_output=True,
- )
- subprocess.run(
- ["git", "remote", "add", "origin", "https://example.com/test-repo.git"],
- cwd=repo, capture_output=True,
- )
- return repo
-
-
-# ---------------------------------------------------------------------------
-# Lightweight reimplementations for testing (avoid importing cli.py)
-# ---------------------------------------------------------------------------
-
-def _git_repo_root(cwd=None):
- """Test version of _git_repo_root."""
- try:
- result = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- capture_output=True, text=True, timeout=5,
- cwd=cwd,
- )
- if result.returncode == 0:
- return result.stdout.strip()
- except Exception:
- pass
- return None
-
-
-def _setup_worktree(repo_root):
- """Test version of _setup_worktree — creates a worktree."""
- import uuid
- short_id = uuid.uuid4().hex[:8]
- wt_name = f"hermes-{short_id}"
- branch_name = f"hermes/{wt_name}"
-
- worktrees_dir = Path(repo_root) / ".worktrees"
- worktrees_dir.mkdir(parents=True, exist_ok=True)
- wt_path = worktrees_dir / wt_name
-
- result = subprocess.run(
- ["git", "worktree", "add", str(wt_path), "-b", branch_name, "HEAD"],
- capture_output=True, text=True, timeout=30, cwd=repo_root,
- )
- if result.returncode != 0:
- return None
-
- return {
- "path": str(wt_path),
- "branch": branch_name,
- "repo_root": repo_root,
- }
-
-
-def _has_unpushed_commits(worktree_path, timeout=10):
- """Test version of the worktree unpushed-commit helper."""
- try:
- remote_refs = subprocess.run(
- ["git", "for-each-ref", "--format=%(refname)", "refs/remotes"],
- capture_output=True, text=True, timeout=timeout, cwd=worktree_path,
- )
- if remote_refs.returncode != 0:
- return True
- if not remote_refs.stdout.strip():
- return False
-
- result = subprocess.run(
- ["git", "log", "--oneline", "HEAD", "--not", "--remotes"],
- capture_output=True, text=True, timeout=timeout, cwd=worktree_path,
- )
- if result.returncode != 0:
- return True
- return bool(result.stdout.strip())
- except Exception:
- return True
-
-
-def _cleanup_worktree(info):
- """Test version of _cleanup_worktree.
-
- Preserves the worktree only if it has unpushed commits.
- Dirty working tree alone is not enough to keep it.
- """
- wt_path = info["path"]
- branch = info["branch"]
- repo_root = info["repo_root"]
-
- if not Path(wt_path).exists():
- return
-
- if _has_unpushed_commits(wt_path, timeout=10):
- return False # Did not clean up — has unpushed commits
-
- subprocess.run(
- ["git", "worktree", "remove", wt_path, "--force"],
- capture_output=True, text=True, timeout=15, cwd=repo_root,
- )
- subprocess.run(
- ["git", "branch", "-D", branch],
- capture_output=True, text=True, timeout=10, cwd=repo_root,
- )
- return True # Cleaned up
-
-
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
-class TestGitRepoDetection:
- """Test git repo root detection."""
-
- def test_detects_git_repo(self, git_repo):
- root = _git_repo_root(cwd=str(git_repo))
- assert root is not None
- assert Path(root).resolve() == git_repo.resolve()
-
-
- def test_returns_none_outside_repo(self, tmp_path):
- # tmp_path itself is not a git repo
- bare_dir = tmp_path / "not-a-repo"
- bare_dir.mkdir()
- root = _git_repo_root(cwd=str(bare_dir))
- assert root is None
-
-
-class TestWorktreeCreation:
- """Test worktree setup."""
-
- def test_creates_worktree(self, git_repo):
- info = _setup_worktree(str(git_repo))
- assert info is not None
- assert Path(info["path"]).exists()
- assert info["branch"].startswith("hermes/hermes-")
- assert info["repo_root"] == str(git_repo)
-
- # Verify it's a valid git worktree
- result = subprocess.run(
- ["git", "rev-parse", "--is-inside-work-tree"],
- capture_output=True, text=True, cwd=info["path"],
- )
- assert result.stdout.strip() == "true"
-
- def test_worktree_has_own_branch(self, git_repo):
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # Check branch name in worktree
- result = subprocess.run(
- ["git", "branch", "--show-current"],
- capture_output=True, text=True, cwd=info["path"],
- )
- assert result.stdout.strip() == info["branch"]
-
- def test_worktree_is_independent(self, git_repo):
- """Two worktrees from the same repo are independent."""
- info1 = _setup_worktree(str(git_repo))
- info2 = _setup_worktree(str(git_repo))
- assert info1 is not None
- assert info2 is not None
- assert info1["path"] != info2["path"]
- assert info1["branch"] != info2["branch"]
-
- # Create a file in worktree 1
- (Path(info1["path"]) / "only-in-wt1.txt").write_text("hello")
-
- # It should NOT appear in worktree 2
- assert not (Path(info2["path"]) / "only-in-wt1.txt").exists()
-
-
-
-
-class TestWorktreeCleanup:
- """Test worktree cleanup on exit."""
-
- def test_clean_worktree_removed(self, git_repo):
- info = _setup_worktree(str(git_repo))
- assert info is not None
- assert Path(info["path"]).exists()
-
- result = _cleanup_worktree(info)
- assert result is True
- assert not Path(info["path"]).exists()
-
-
-
-
-
- def test_branch_deleted_on_cleanup(self, git_repo):
- info = _setup_worktree(str(git_repo))
- branch = info["branch"]
-
- _cleanup_worktree(info)
-
- # Branch should be gone
- result = subprocess.run(
- ["git", "branch", "--list", branch],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- assert branch not in result.stdout
-
- def test_cleanup_nonexistent_worktree(self, git_repo):
- """Cleanup should handle already-removed worktrees gracefully."""
- info = {
- "path": str(git_repo / ".worktrees" / "nonexistent"),
- "branch": "hermes/nonexistent",
- "repo_root": str(git_repo),
- }
- # Should not raise
- _cleanup_worktree(info)
-
-
-class TestWorktreeInclude:
- """Test .worktreeinclude file handling."""
-
- def test_copies_included_files(self, git_repo):
- """Files listed in .worktreeinclude should be copied to the worktree."""
- # Create a .env file (gitignored)
- (git_repo / ".env").write_text("SECRET=abc123")
- (git_repo / ".gitignore").write_text(".env\n.worktrees/\n")
- subprocess.run(
- ["git", "add", ".gitignore"],
- cwd=str(git_repo), capture_output=True,
- )
- subprocess.run(
- ["git", "commit", "-m", "Add gitignore"],
- cwd=str(git_repo), capture_output=True,
- )
-
- # Create .worktreeinclude
- (git_repo / ".worktreeinclude").write_text(".env\n")
-
- # Import and use the real _setup_worktree logic for include handling
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # Manually copy .worktreeinclude entries (mirrors cli.py logic)
- include_file = git_repo / ".worktreeinclude"
- wt_path = Path(info["path"])
- for line in include_file.read_text().splitlines():
- entry = line.strip()
- if not entry or entry.startswith("#"):
- continue
- src = git_repo / entry
- dst = wt_path / entry
- if src.is_file():
- dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(str(src), str(dst))
-
- # Verify .env was copied
- assert (wt_path / ".env").exists()
- assert (wt_path / ".env").read_text() == "SECRET=abc123"
# Should not crash — just skip all lines
-class TestGitignoreManagement:
- """Test that .worktrees/ is added to .gitignore."""
-
- def test_adds_to_gitignore(self, git_repo):
- """Creating a worktree should add .worktrees/ to .gitignore."""
- # Remove any existing .gitignore
- gitignore = git_repo / ".gitignore"
- if gitignore.exists():
- gitignore.unlink()
-
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # Now manually add .worktrees/ to .gitignore (mirrors cli.py logic)
- _ignore_entry = ".worktrees/"
- existing = gitignore.read_text() if gitignore.exists() else ""
- if _ignore_entry not in existing.splitlines():
- with open(gitignore, "a") as f:
- if existing and not existing.endswith("\n"):
- f.write("\n")
- f.write(f"{_ignore_entry}\n")
-
- content = gitignore.read_text()
- assert ".worktrees/" in content
-
-
-
-class TestMultipleWorktrees:
- """Test running multiple worktrees concurrently (the core use case)."""
-
- def test_ten_concurrent_worktrees(self, git_repo):
- """Create 10 worktrees — simulating 10 parallel agents."""
- worktrees = []
- for _ in range(10):
- info = _setup_worktree(str(git_repo))
- assert info is not None
- worktrees.append(info)
-
- # All should exist and be independent
- paths = [info["path"] for info in worktrees]
- assert len(set(paths)) == 10 # All unique
-
- # Each should have the repo files
- for info in worktrees:
- assert (Path(info["path"]) / "README.md").exists()
-
- # Edit a file in one worktree
- (Path(worktrees[0]["path"]) / "README.md").write_text("Modified in wt0")
-
- # Others should be unaffected
- for info in worktrees[1:]:
- assert (Path(info["path"]) / "README.md").read_text() == "# Test Repo\n"
-
- # List worktrees via git
- result = subprocess.run(
- ["git", "worktree", "list"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- # Should have 11 entries: main + 10 worktrees
- lines = [l for l in result.stdout.strip().splitlines() if l.strip()]
- assert len(lines) == 11
-
- # Cleanup all (git_repo fixture has a fake remote ref so cleanup works)
- for info in worktrees:
- # Discard changes first so cleanup works
- subprocess.run(
- ["git", "checkout", "--", "."],
- cwd=info["path"], capture_output=True,
- )
- _cleanup_worktree(info)
-
- # All should be removed
- for info in worktrees:
- assert not Path(info["path"]).exists()
-
-
-def _can_symlink():
- """Check if we can create symlinks (needs admin/dev-mode on Windows)."""
- import tempfile
- try:
- with tempfile.TemporaryDirectory() as d:
- src = Path(d) / "src"
- src.write_text("x")
- lnk = Path(d) / "lnk"
- lnk.symlink_to(src)
- return True
- except OSError:
- return False
-
-
[email protected](not _can_symlink(), reason="Symlinks need elevated privileges")
-class TestWorktreeDirectorySymlink:
- """Test .worktreeinclude with directories (symlinked)."""
-
- def test_symlinks_directory(self, git_repo):
- """Directories in .worktreeinclude should be symlinked."""
- # Create a .venv directory
- venv_dir = git_repo / ".venv" / "lib"
- venv_dir.mkdir(parents=True)
- (venv_dir / "marker.txt").write_text("venv marker")
- (git_repo / ".gitignore").write_text(".venv/\n.worktrees/\n")
- subprocess.run(
- ["git", "add", ".gitignore"], cwd=str(git_repo), capture_output=True
- )
- subprocess.run(
- ["git", "commit", "-m", "gitignore"], cwd=str(git_repo), capture_output=True
- )
-
- (git_repo / ".worktreeinclude").write_text(".venv/\n")
-
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- wt_path = Path(info["path"])
- src = git_repo / ".venv"
- dst = wt_path / ".venv"
-
- # Manually symlink (mirrors cli.py logic)
- if not dst.exists():
- dst.parent.mkdir(parents=True, exist_ok=True)
- os.symlink(str(src.resolve()), str(dst))
-
- assert dst.is_symlink()
- assert (dst / "lib" / "marker.txt").read_text() == "venv marker"
-
-
-class TestStaleWorktreePruning:
- """Test _prune_stale_worktrees garbage collection."""
-
- def test_prunes_old_clean_worktree(self, git_repo):
- """Old clean worktrees should be removed on prune."""
- import time
-
- info = _setup_worktree(str(git_repo))
- assert info is not None
- assert Path(info["path"]).exists()
-
- # Make the worktree look old (set mtime to 25h ago)
- old_time = time.time() - (25 * 3600)
- os.utime(info["path"], (old_time, old_time))
-
- # Reimplementation of prune logic (matches cli.py)
- worktrees_dir = git_repo / ".worktrees"
- cutoff = time.time() - (24 * 3600)
-
- for entry in worktrees_dir.iterdir():
- if not entry.is_dir() or not entry.name.startswith("hermes-"):
- continue
- try:
- mtime = entry.stat().st_mtime
- if mtime > cutoff:
- continue
- except Exception:
- continue
-
- status = subprocess.run(
- ["git", "status", "--porcelain"],
- capture_output=True, text=True, timeout=5, cwd=str(entry),
- )
- if status.stdout.strip():
- continue
-
- branch_result = subprocess.run(
- ["git", "branch", "--show-current"],
- capture_output=True, text=True, timeout=5, cwd=str(entry),
- )
- branch = branch_result.stdout.strip()
- subprocess.run(
- ["git", "worktree", "remove", str(entry), "--force"],
- capture_output=True, text=True, timeout=15, cwd=str(git_repo),
- )
- if branch:
- subprocess.run(
- ["git", "branch", "-D", branch],
- capture_output=True, text=True, timeout=10, cwd=str(git_repo),
- )
-
- assert not Path(info["path"]).exists()
-
- def test_keeps_recent_worktree(self, git_repo):
- """Recent worktrees should NOT be pruned."""
- import time
-
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # Don't modify mtime — it's recent
- worktrees_dir = git_repo / ".worktrees"
- cutoff = time.time() - (24 * 3600)
-
- pruned = False
- for entry in worktrees_dir.iterdir():
- if not entry.is_dir() or not entry.name.startswith("hermes-"):
- continue
- mtime = entry.stat().st_mtime
- if mtime > cutoff:
- continue # Too recent
- pruned = True
-
- assert not pruned
- assert Path(info["path"]).exists()
-
-
-
-
- def test_force_prunes_very_old_worktree(self, git_repo):
- """Worktrees older than 72h should be force-pruned regardless."""
- import time
-
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # Make an unpushed commit (would normally protect it)
- (Path(info["path"]) / "work.txt").write_text("stale work")
- subprocess.run(["git", "add", "work.txt"], cwd=info["path"], capture_output=True)
- subprocess.run(
- ["git", "commit", "-m", "old agent work"],
- cwd=info["path"], capture_output=True,
- )
-
- # Make it very old (73h — beyond the 72h hard threshold)
- old_time = time.time() - (73 * 3600)
- os.utime(info["path"], (old_time, old_time))
-
- # Simulate the force-prune tier check
- hard_cutoff = time.time() - (72 * 3600)
- mtime = Path(info["path"]).stat().st_mtime
- assert mtime <= hard_cutoff # Should qualify for force removal
-
- # Actually remove it (simulates _prune_stale_worktrees force path)
- branch_result = subprocess.run(
- ["git", "branch", "--show-current"],
- capture_output=True, text=True, timeout=5, cwd=info["path"],
- )
- branch = branch_result.stdout.strip()
-
- subprocess.run(
- ["git", "worktree", "remove", info["path"], "--force"],
- capture_output=True, text=True, timeout=15, cwd=str(git_repo),
- )
- if branch:
- subprocess.run(
- ["git", "branch", "-D", branch],
- capture_output=True, text=True, timeout=10, cwd=str(git_repo),
- )
-
- assert not Path(info["path"]).exists()
-
-
-class TestEdgeCases:
- """Test edge cases for robustness."""
-
- def test_no_commits_repo(self, tmp_path):
- """Worktree creation should fail gracefully on a repo with no commits."""
- repo = tmp_path / "empty-repo"
- repo.mkdir()
- subprocess.run(["git", "init"], cwd=str(repo), capture_output=True)
-
- info = _setup_worktree(str(repo))
- assert info is None # Should fail gracefully
-
- def test_not_a_git_repo(self, tmp_path):
- """Repo detection should return None for non-git directories."""
- bare = tmp_path / "not-git"
- bare.mkdir()
- root = _git_repo_root(cwd=str(bare))
- assert root is None
-
- def test_worktrees_dir_already_exists(self, git_repo):
- """Should work fine if .worktrees/ already exists."""
- (git_repo / ".worktrees").mkdir(exist_ok=True)
- info = _setup_worktree(str(git_repo))
- assert info is not None
- assert Path(info["path"]).exists()
-
-
-class TestCLIFlagLogic:
- """Test the flag/config OR logic from main()."""
-
- def test_worktree_flag_triggers(self):
- """--worktree flag should trigger worktree creation."""
- worktree = True
- w = False
- config_worktree = False
- use_worktree = worktree or w or config_worktree
- assert use_worktree
-
-
-
- def test_none_set_no_trigger(self):
- """No flags and no config should not trigger."""
- worktree = False
- w = False
- config_worktree = False
- use_worktree = worktree or w or config_worktree
- assert not use_worktree
-
-
-class TestTerminalCWDIntegration:
- """Test that TERMINAL_CWD is correctly set to the worktree path."""
-
- def test_terminal_cwd_set(self, git_repo):
- """After worktree setup, TERMINAL_CWD should point to the worktree."""
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # This is what main() does:
- os.environ["TERMINAL_CWD"] = info["path"]
- assert os.environ["TERMINAL_CWD"] == info["path"]
- assert Path(os.environ["TERMINAL_CWD"]).exists()
-
- # Clean up env
- del os.environ["TERMINAL_CWD"]
-
-
-
-class TestOrphanedBranchPruning:
- """Test cleanup of orphaned hermes/* and pr-* branches."""
-
- def test_prunes_orphaned_hermes_branch(self, git_repo):
- """hermes/hermes-* branches with no worktree should be deleted."""
- # Create a branch that looks like a worktree branch but has no worktree
- subprocess.run(
- ["git", "branch", "hermes/hermes-deadbeef", "HEAD"],
- cwd=str(git_repo), capture_output=True,
- )
-
- # Verify it exists
- result = subprocess.run(
- ["git", "branch", "--list", "hermes/hermes-deadbeef"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- assert "hermes/hermes-deadbeef" in result.stdout
-
- # Simulate _prune_orphaned_branches logic
- result = subprocess.run(
- ["git", "branch", "--format=%(refname:short)"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- all_branches = [b.strip() for b in result.stdout.strip().split("\n") if b.strip()]
-
- wt_result = subprocess.run(
- ["git", "worktree", "list", "--porcelain"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- active_branches = {"main"}
- for line in wt_result.stdout.split("\n"):
- if line.startswith("branch refs/heads/"):
- active_branches.add(line.split("branch refs/heads/", 1)[-1].strip())
-
- orphaned = [
- b for b in all_branches
- if b not in active_branches
- and (b.startswith("hermes/hermes-") or b.startswith("pr-"))
- ]
- assert "hermes/hermes-deadbeef" in orphaned
-
- # Delete them
- if orphaned:
- subprocess.run(
- ["git", "branch", "-D"] + orphaned,
- capture_output=True, text=True, cwd=str(git_repo),
- )
-
- # Verify gone
- result = subprocess.run(
- ["git", "branch", "--list", "hermes/hermes-deadbeef"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- assert "hermes/hermes-deadbeef" not in result.stdout
-
- def test_prunes_orphaned_pr_branch(self, git_repo):
- """pr-* branches should be deleted during pruning."""
- subprocess.run(
- ["git", "branch", "pr-1234", "HEAD"],
- cwd=str(git_repo), capture_output=True,
- )
- subprocess.run(
- ["git", "branch", "pr-5678", "HEAD"],
- cwd=str(git_repo), capture_output=True,
- )
-
- result = subprocess.run(
- ["git", "branch", "--format=%(refname:short)"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- all_branches = [b.strip() for b in result.stdout.strip().split("\n") if b.strip()]
-
- active_branches = {"main"}
- orphaned = [
- b for b in all_branches
- if b not in active_branches and b.startswith("pr-")
- ]
- assert "pr-1234" in orphaned
- assert "pr-5678" in orphaned
-
- subprocess.run(
- ["git", "branch", "-D"] + orphaned,
- capture_output=True, text=True, cwd=str(git_repo),
- )
-
- # Verify gone
- result = subprocess.run(
- ["git", "branch", "--format=%(refname:short)"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- remaining = result.stdout.strip()
- assert "pr-1234" not in remaining
- assert "pr-5678" not in remaining
-
-
- def test_preserves_main_branch(self, git_repo):
- """main branch should never be pruned."""
- result = subprocess.run(
- ["git", "branch", "--format=%(refname:short)"],
- capture_output=True, text=True, cwd=str(git_repo),
- )
- all_branches = [b.strip() for b in result.stdout.strip().split("\n") if b.strip()]
- active_branches = {"main"}
-
- orphaned = [
- b for b in all_branches
- if b not in active_branches
- and (b.startswith("hermes/hermes-") or b.startswith("pr-"))
- ]
- assert "main" not in orphaned
-
-
-class TestSystemPromptInjection:
- """Test that the agent gets worktree context in its system prompt."""
-
- def test_prompt_note_format(self, git_repo):
- """Verify the system prompt note contains all required info."""
- info = _setup_worktree(str(git_repo))
- assert info is not None
-
- # This is what main() does:
- wt_note = (
- f"\n\n[System note: You are working in an isolated git worktree at "
- f"{info['path']}. Your branch is `{info['branch']}`. "
- f"Changes here do not affect the main working tree or other agents. "
- f"Remember to commit and push your changes, and create a PR if appropriate. "
- f"The original repo is at {info['repo_root']}.]\n"
- )
-
- assert info["path"] in wt_note
- assert info["branch"] in wt_note
- assert info["repo_root"] in wt_note
- assert "isolated git worktree" in wt_note
- assert "commit and push" in wt_note
-
-
class TestWorktreeLockReaping:
"""Exercise the REAL cli._prune_stale_worktrees lock/dirty/unpushed logic.
- Unlike the reimplementation-based tests above, these import the actual
- production functions so the behavior contract is enforced against the
- shipped code:
+ These import the actual production functions so the behavior contract is
+ enforced against the shipped code:
- live-locked (owning pid running) -> never reaped, any age
- dead-locked clean (owning pid gone) -> unlocked + reaped (fixes the
@@ -876,7 +157,6 @@ class TestWorktreeLockReaping:
assert wt.exists(), "dirty worktree must survive even past the 72h tier"
-
class TestWorktreeLockPredicate:
"""_worktree_lock_is_live classification (real cli helper)."""
@@ -894,7 +174,6 @@ class TestWorktreeLockPredicate:
return p
def test_unlocked_returns_none(self, git_repo):
- import cli
p = git_repo / ".worktrees" / "hermes-x"
(git_repo / ".worktrees").mkdir(exist_ok=True)
subprocess.run(
@@ -904,14 +183,11 @@ class TestWorktreeLockPredicate:
assert worktree_ops._worktree_lock_is_live(str(git_repo), str(p)) is None
-
def test_foreign_lock_reason_returns_dead(self, git_repo):
- import cli
p = self._mk_locked(git_repo, "hermes-foreign", "some other tool")
assert worktree_ops._worktree_lock_is_live(str(git_repo), str(p)) == "dead"
def test_bad_repo_root_fails_safe_to_live(self, tmp_path):
- import cli
# Not a git repo -> git query fails -> must report "live" (never delete)
assert worktree_ops._worktree_lock_is_live(str(tmp_path), str(tmp_path / "x")) == "live"
@@ -991,8 +267,6 @@ class TestWidenedPruner:
assert wt.exists(), "named tree under 72h must be kept (3x scratch timeline)"
-
-
# -- squash-merge escape hatch ------------------------------------------
def test_squash_merged_tree_is_reaped(self, git_repo):
@@ -1012,8 +286,6 @@ class TestWidenedPruner:
# -- _worktree_commits_all_merged_upstream unit contracts ----------------
-
-
def test_merged_predicate_fails_safe_without_upstream(self, git_repo_no_remote):
"""No remote: the local trunk is the baseline (a tree at trunk IS merged). No trunk at
all — detached main checkout, no main/master — leaves nothing to compare against -> False."""
@@ -1038,8 +310,6 @@ class TestWidenedPruner:
# -- preserved-work warning ----------------------------------------------
-
-
class TestMergeVerdictCache:
"""The ``git cherry`` patch-equivalence probe is memoized on disk because it
dominates ``hermes -w`` startup (~0.2-1.0s per worktree, re-run on every
@@ -1057,7 +327,6 @@ class TestMergeVerdictCache:
def test_cache_hit_matches_uncached_verdict(self, git_repo):
"""A cached verdict must equal what the real git call returns."""
- import cli
wt, sha = self._mk(git_repo, "hermes-cachehit", commit=True)
self._merge_upstream(git_repo, sha)
@@ -1076,7 +345,6 @@ class TestMergeVerdictCache:
This is the guard against the cache turning a 'merged, reapable' verdict
into a stale approval to delete a tree that has since gained real work.
"""
- import cli
wt, sha = self._mk(git_repo, "hermes-moves", commit=True)
self._merge_upstream(git_repo, sha)
@@ -1093,10 +361,8 @@ class TestMergeVerdictCache:
assert set(cache) != key_after_merge, "moved HEAD must produce a new key"
-
def test_cache_is_bounded(self, monkeypatch, tmp_path):
"""The cache file must not grow without limit across sessions."""
- import cli
from hermes_cli import worktree_ops
path = tmp_path / "verdicts.json"
monkeypatch.setattr(worktree_ops, "_worktree_merge_cache_path", lambda: path)
@@ -1197,7 +463,6 @@ class TestPruneParallelEquivalence:
assert not wt.exists(), "serial fallback must still reap the merged tree"
-
class TestShallowCloneDeepening:
"""Shallow installer clones (`git clone --depth 1`) break the unpushed
guard: the shallow boundary disconnects an older worktree HEAD from
@@ -1337,7 +602,6 @@ class TestShallowCloneDeepening:
)
def test_deepen_noop_on_full_clone(self, git_repo):
- import cli
assert worktree_ops._deepen_shallow_repo(str(git_repo)) is True
def test_real_unpushed_work_survives_deepening(self, tmp_path):
@@ -1435,7 +699,6 @@ class TestPrMergedEscapeHatch:
def test_merged_verdict_memoized_by_branch_and_head(
self, git_repo, tmp_path, monkeypatch
):
- import cli
wt = self._mk_diverged(git_repo, "hermes-memo")
self._stub_gh(tmp_path, monkeypatch)
cache: dict = {}
@@ -1447,7 +710,6 @@ class TestPrMergedEscapeHatch:
assert worktree_ops._worktree_branch_pr_merged(str(wt), cache=cache) is True
def test_negative_verdict_not_cached(self, git_repo, tmp_path, monkeypatch):
- import cli
wt = self._mk_diverged(git_repo, "hermes-nocache-neg")
self._stub_gh(tmp_path, monkeypatch, stdout="[]")
cache: dict = {}
diff --git a/tests/hermes_cli/test_worktree_command.py b/tests/hermes_cli/test_worktree_command.py
index bf9443e7718..d837c1b20b5 100644
--- a/tests/hermes_cli/test_worktree_command.py
+++ b/tests/hermes_cli/test_worktree_command.py
@@ -75,11 +75,6 @@ def repo(tmp_path, monkeypatch):
os.chdir(tmp_path)
-@requires_git
-def test_status_no_active_worktree(repo):
- out = _run(_Stub(), "/worktree")
- assert "No active worktree" in out
- assert "/worktree new" in out
def test_status_outside_repo(tmp_path, monkeypatch):
@@ -141,7 +136,3 @@ def test_new_sanitizes_name(repo):
assert name == "weird-name"
-@requires_git
-def test_unknown_subcommand(repo):
- out = _run(_Stub(), "/worktree frobnicate")
- assert "Unknown /worktree subcommand" in out
diff --git a/tests/hermes_cli/test_xai_curated_models.py b/tests/hermes_cli/test_xai_curated_models.py
index c822cfb1afb..3c43ae49298 100644
--- a/tests/hermes_cli/test_xai_curated_models.py
+++ b/tests/hermes_cli/test_xai_curated_models.py
@@ -3,36 +3,31 @@
from unittest.mock import patch
from hermes_cli.models import (
- _MODELS_DEV_PREFERRED,
_PROVIDER_MODELS,
provider_model_ids,
)
-def test_grok_4_6_is_default_pin():
- models = _PROVIDER_MODELS["xai-oauth"]
- assert models[0] == "grok-4.6"
-def test_xai_providers_are_models_dev_preferred():
- assert "xai" in _MODELS_DEV_PREFERRED
- assert "xai-oauth" in _MODELS_DEV_PREFERRED
def test_xai_oauth_picker_merges_models_dev_at_call_time():
"""xai-oauth must not return the import-frozen list; merge at picker time."""
- mdev = ["grok-build-0.1", "grok-new-from-models-dev", "grok-4.6"]
+ top = _PROVIDER_MODELS["xai-oauth"][0]
+ mdev = ["grok-build-0.1", "grok-new-from-models-dev", top]
with patch("agent.models_dev.list_agentic_models", return_value=mdev) as mocked:
models = provider_model_ids("xai-oauth")
mocked.assert_called()
- assert models[0] == "grok-4.6"
+ assert models[0] == top
assert "grok-new-from-models-dev" in models
def test_xai_api_key_picker_merges_models_dev_when_live_unavailable():
"""Without a live /v1/models hit, xai uses the models.dev preferred path."""
- mdev = ["grok-build-0.1", "grok-new-from-models-dev", "grok-4.6"]
+ top = _PROVIDER_MODELS["xai-oauth"][0]
+ mdev = ["grok-build-0.1", "grok-new-from-models-dev", top]
with (
patch(
"hermes_cli.auth.resolve_api_key_provider_credentials",
@@ -44,13 +39,14 @@ def test_xai_api_key_picker_merges_models_dev_when_live_unavailable():
mocked.assert_called()
assert "grok-new-from-models-dev" in models
- assert models[0] == "grok-4.6"
+ assert models[0] == top
def test_xai_pin_survives_when_top_model_only_in_extras():
- """If models.dev omits grok-4.6, curated extras + finalize still pin it."""
+ """If models.dev omits the curated top model, curated extras + finalize still pin it."""
+ top = _PROVIDER_MODELS["xai-oauth"][0]
mdev = ["grok-build-0.1", "grok-new-from-models-dev"]
with patch("agent.models_dev.list_agentic_models", return_value=mdev):
models = provider_model_ids("xai-oauth")
- assert models[0] == "grok-4.6"
+ assert models[0] == top
diff --git a/tests/hermes_cli/test_xai_oauth_refresh.py b/tests/hermes_cli/test_xai_oauth_refresh.py
index b28d31cffe7..2308ced7cf4 100644
--- a/tests/hermes_cli/test_xai_oauth_refresh.py
+++ b/tests/hermes_cli/test_xai_oauth_refresh.py
@@ -21,8 +21,6 @@ def _jwt_with_exp(exp: int) -> str:
return f"{header}.{payload}.sig"
-def test_xai_oauth_refresh_skew_is_one_hour() -> None:
- assert auth.XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS == 3600
def test_xai_oauth_token_expiring_uses_one_hour_skew() -> None:
diff --git a/tests/hermes_cli/test_xai_provider_labels.py b/tests/hermes_cli/test_xai_provider_labels.py
index 212041b03e3..18c5f13f37b 100644
--- a/tests/hermes_cli/test_xai_provider_labels.py
+++ b/tests/hermes_cli/test_xai_provider_labels.py
@@ -1,13 +1,11 @@
"""Regression tests for xAI provider label disambiguation."""
-from hermes_cli.models import provider_label
from hermes_cli.providers import get_label
def test_xai_oauth_provider_label_is_not_collapsed_to_api_key_label():
"""The model picker must distinguish xAI API-key and OAuth providers."""
- assert get_label("xai") == "xAI"
- assert get_label("xai-oauth") == "xAI Grok OAuth (SuperGrok / Premium+)"
- assert get_label("grok-oauth") == "xAI Grok OAuth (SuperGrok / Premium+)"
+ assert get_label("xai-oauth") != get_label("xai")
+ assert get_label("grok-oauth") == get_label("xai-oauth")
diff --git a/tests/hermes_cli/test_xai_retirement.py b/tests/hermes_cli/test_xai_retirement.py
index 4b2c095865b..4081f346a39 100644
--- a/tests/hermes_cli/test_xai_retirement.py
+++ b/tests/hermes_cli/test_xai_retirement.py
@@ -3,14 +3,10 @@ from __future__ import annotations
from hermes_cli.xai_retirement import (
- MIGRATION_GUIDE_URL,
- RETIREMENT_DATE,
- RetirementIssue,
_RETIRED_MODELS,
_looks_like_xai,
_normalize,
find_retired_xai_refs,
- format_issue,
)
@@ -92,52 +88,9 @@ class TestMigrationSemantics:
# format_issue
# ---------------------------------------------------------------------------
-class TestFormatIssue:
- def test_basic_format(self):
- issue = RetirementIssue(
- config_path="principal.model",
- current_model="grok-3",
- replacement="grok-4.3",
- )
- s = format_issue(issue)
- assert "principal.model" in s
- assert "'grok-3'" in s
- assert "'grok-4.3'" in s
-
-
- def test_includes_note_when_set(self):
- issue = RetirementIssue(
- config_path="principal.model",
- current_model="grok-3",
- replacement="grok-4.3",
- note="ambiguous variant",
- )
- s = format_issue(issue)
- assert "[note: ambiguous variant]" in s
# ---------------------------------------------------------------------------
# Module-level constants sanity
# ---------------------------------------------------------------------------
-class TestModuleConstants:
- def test_retirement_date_is_may_15(self):
- assert "May 15, 2026" == RETIREMENT_DATE
-
- def test_migration_guide_url_points_to_xai(self):
- assert MIGRATION_GUIDE_URL.startswith("https://docs.x.ai/")
- assert "may-15" in MIGRATION_GUIDE_URL.lower()
-
- def test_retired_models_keyset_matches_doc(self):
- # Snapshot test: if xAI's list changes we want CI to flag it.
- expected = {
- "grok-4-0709",
- "grok-4-fast-reasoning",
- "grok-4-fast-non-reasoning",
- "grok-4-1-fast-reasoning",
- "grok-4-1-fast-non-reasoning",
- "grok-code-fast-1",
- "grok-3",
- "grok-imagine-image-pro",
- }
- assert set(_RETIRED_MODELS.keys()) == expected
diff --git a/tests/hermes_cli/test_xiaomi_provider.py b/tests/hermes_cli/test_xiaomi_provider.py
index 71f4bb515d7..66654228875 100644
--- a/tests/hermes_cli/test_xiaomi_provider.py
+++ b/tests/hermes_cli/test_xiaomi_provider.py
@@ -4,9 +4,7 @@
import pytest
from hermes_cli.auth import (
- PROVIDER_REGISTRY,
resolve_provider,
- get_api_key_provider_status,
resolve_api_key_provider_credentials,
)
@@ -16,15 +14,6 @@ from hermes_cli.auth import (
# =============================================================================
-class TestXiaomiProviderRegistry:
- """Verify Xiaomi is registered correctly in the PROVIDER_REGISTRY."""
-
- def test_registered(self):
- assert "xiaomi" in PROVIDER_REGISTRY
-
-
- def test_inference_base_url(self):
- assert PROVIDER_REGISTRY["xiaomi"].inference_base_url == "https://api.xiaomimimo.com/v1"
# =============================================================================
@@ -135,9 +124,6 @@ class TestXiaomiCredentials:
class TestXiaomiModelCatalog:
"""Xiaomi uses dynamic model discovery via models.dev."""
- def test_models_dev_mapping(self):
- from agent.models_dev import PROVIDER_TO_MODELS_DEV
- assert PROVIDER_TO_MODELS_DEV["xiaomi"] == "xiaomi"
def test_static_model_list_fallback(self):
"""Static _PROVIDER_MODELS fallback must exist for model picker.
@@ -191,10 +177,6 @@ class TestXiaomiNormalization:
"""Model name normalization — Xiaomi is a direct provider."""
- def test_matching_prefix_strip(self):
- """xiaomi/mimo-v2-pro should normalize to mimo-v2-pro for direct API."""
- from hermes_cli.model_normalize import _MATCHING_PREFIX_STRIP_PROVIDERS
- assert "xiaomi" in _MATCHING_PREFIX_STRIP_PROVIDERS
def test_lowercase_subset_of_matching_prefix(self):
@@ -215,13 +197,7 @@ class TestXiaomiNormalization:
@pytest.mark.parametrize("input_name,expected", [
("MiMo-V2.5-Pro", "mimo-v2.5-pro"),
- ("MIMO-V2.5-PRO", "mimo-v2.5-pro"),
- ("MiMo-v2.5-pro", "mimo-v2.5-pro"),
("mimo-v2.5-pro", "mimo-v2.5-pro"), # already lowercase
- ("MiMo-V2-Pro", "mimo-v2-pro"),
- ("MiMo-V2-Omni", "mimo-v2-omni"),
- ("MiMo-V2-Flash", "mimo-v2-flash"),
- ("MiMo-V2.5", "mimo-v2.5"),
])
def test_normalize_lowercases_mixed_case(self, input_name, expected):
"""Xiaomi's API requires lowercase model IDs — mixed case from docs must be lowered."""
@@ -240,11 +216,6 @@ class TestXiaomiURLMapping:
"""Test URL → provider inference for Xiaomi endpoints."""
- def test_provider_prefixes(self):
- from agent.model_metadata import _PROVIDER_PREFIXES
- assert "xiaomi" in _PROVIDER_PREFIXES
- assert "mimo" in _PROVIDER_PREFIXES
- assert "xiaomi-mimo" in _PROVIDER_PREFIXES
def test_infer_from_regional_urls(self):
@@ -260,29 +231,6 @@ class TestXiaomiURLMapping:
# =============================================================================
-class TestXiaomiProvidersModule:
- """Test Xiaomi in the unified providers module."""
-
- def test_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
- assert "xiaomi" in HERMES_OVERLAYS
- overlay = HERMES_OVERLAYS["xiaomi"]
- assert overlay.transport == "openai_chat"
- assert overlay.base_url_env_var == "XIAOMI_BASE_URL"
- assert not overlay.is_aggregator
-
-
-
- def test_get_provider(self):
- pdef = None
- try:
- from hermes_cli.providers import get_provider
- pdef = get_provider("xiaomi")
- except Exception:
- pass
- if pdef is not None:
- assert pdef.id == "xiaomi"
- assert pdef.transport == "openai_chat"
# =============================================================================
@@ -297,24 +245,5 @@ class TestXiaomiProvidersModule:
# =============================================================================
-class TestXiaomiDoctor:
- """Verify hermes doctor recognizes Xiaomi env vars."""
-
- def test_provider_env_hints(self):
- from hermes_cli.doctor import _PROVIDER_ENV_HINTS
- assert "XIAOMI_API_KEY" in _PROVIDER_ENV_HINTS
-
-
-class TestXiaomiAgentInit:
- """Verify the agent can be constructed with xiaomi provider without errors."""
- def test_no_syntax_errors(self):
- """Importing run_agent with xiaomi should not raise."""
- import importlib
- importlib.import_module("run_agent")
- def test_api_mode_is_chat_completions(self):
- from hermes_cli.providers import HERMES_OVERLAYS, TRANSPORT_TO_API_MODE
- overlay = HERMES_OVERLAYS["xiaomi"]
- api_mode = TRANSPORT_TO_API_MODE[overlay.transport]
- assert api_mode == "chat_completions"
diff --git a/tests/hermes_platform/test_facts.py b/tests/hermes_platform/test_facts.py
index 0741f8aea1c..b0e5768b7ed 100644
--- a/tests/hermes_platform/test_facts.py
+++ b/tests/hermes_platform/test_facts.py
@@ -98,5 +98,3 @@ def test_linux_live_cpu_facts_match_cpuinfo(cleared_fact_caches) -> None:
assert facts.cpu_model() in cpuinfo
-def test_interactive_session_is_bool() -> None:
- assert type(facts.interactive_session()) is bool
diff --git a/tests/hermes_platform/test_resolver_app.py b/tests/hermes_platform/test_resolver_app.py
index 55c45017172..0e41a2a8227 100644
--- a/tests/hermes_platform/test_resolver_app.py
+++ b/tests/hermes_platform/test_resolver_app.py
@@ -11,7 +11,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
import pytest
-from hermes_platform.resolver import CheckState, Effort, Probeable, Resolver
+from hermes_platform.resolver import CheckState, Effort
from hermes_platform.resolver.app import AppDef, AppResolver, Endpoint
TOKEN = "tok-3e1f9c-unique-fixture-value"
@@ -39,9 +39,6 @@ def _resolver(tmp_path, exe, server_json=None):
))
-def test_app_resolver_satisfies_both_protocols(tmp_path):
- r = AppResolver(AppDef("x", sys.platform, "executable", str(tmp_path / "x")))
- assert isinstance(r, Resolver) and isinstance(r, Probeable)
def test_locate_reports_expanded_path_when_missing(tmp_path, monkeypatch):
diff --git a/tests/hermes_platform/test_resolver_core.py b/tests/hermes_platform/test_resolver_core.py
index 1049945e674..d94934fc93e 100644
--- a/tests/hermes_platform/test_resolver_core.py
+++ b/tests/hermes_platform/test_resolver_core.py
@@ -6,7 +6,7 @@ import sys
import pytest
-from hermes_platform.resolver import ABSENT, CheckState, LookupContext, Observation, locate_command
+from hermes_platform.resolver import ABSENT, LookupContext, locate_command
def _make_exe(path):
@@ -91,10 +91,6 @@ def test_windows_pathext_is_honored_without_mutating_environ(tmp_path, monkeypat
assert os.environ.get("PATHEXT") == before
-def test_observation_not_checked_is_distinct_from_absent():
- assert Observation.not_checked().state is CheckState.NOT_CHECKED
- assert Observation(CheckState.ABSENT, False).state is not CheckState.NOT_CHECKED
- assert Observation(CheckState.ABSENT, False).value is False
def test_one_candidate_per_known_dir_regardless_of_pathext(tmp_path):
diff --git a/tests/hermes_state/test_bounded_recent_sessions.py b/tests/hermes_state/test_bounded_recent_sessions.py
index 6211ff7de06..7248b0d1706 100644
--- a/tests/hermes_state/test_bounded_recent_sessions.py
+++ b/tests/hermes_state/test_bounded_recent_sessions.py
@@ -21,14 +21,6 @@ def _set_activity(db, session_id, when):
db._conn.commit()
-def test_bounded_recent_uses_effective_activity_index(db):
- indexes = {
- row[0]
- for row in db._conn.execute(
- "SELECT name FROM sqlite_master WHERE type = 'index'"
- ).fetchall()
- }
- assert "idx_sessions_effective_activity" in indexes
def test_writable_startup_reconciles_legacy_activity_column_before_index(tmp_path):
@@ -223,7 +215,7 @@ def test_bounded_recent_cycle_is_deduplicated_and_omitted(db):
def test_bounded_recent_deadline_interrupts_sqlite(db):
- for i in range(300):
+ for i in range(40):
sid = f"session-{i}"
db.create_session(sid, source="cli")
db.append_message(sid, role="user", content=f"message {i}")
diff --git a/tests/hermes_state/test_cross_vm_fs_wal_refusal.py b/tests/hermes_state/test_cross_vm_fs_wal_refusal.py
index 3969cefa3d0..1307385ea79 100644
--- a/tests/hermes_state/test_cross_vm_fs_wal_refusal.py
+++ b/tests/hermes_state/test_cross_vm_fs_wal_refusal.py
@@ -120,5 +120,3 @@ class TestWalRefusalOnCrossVmFs:
conn.close()
errors = [r for r in caplog.records if r.levelno == logging.ERROR and "cross-VM" in r.getMessage()]
assert len(errors) == 1
- assert "hermes sessions set-journal-mode delete" in errors[0].getMessage()
- assert "native volume" in errors[0].getMessage()
diff --git a/tests/hermes_state/test_deleted_wal_generation_guard.py b/tests/hermes_state/test_deleted_wal_generation_guard.py
index d6731cb7dc5..f3f4ed89b20 100644
--- a/tests/hermes_state/test_deleted_wal_generation_guard.py
+++ b/tests/hermes_state/test_deleted_wal_generation_guard.py
@@ -16,7 +16,6 @@ from pathlib import Path
import pytest
-import hermes_state
import hermes_state_dbfile
import hermes_state_readpool
import hermes_state_wal
@@ -49,9 +48,6 @@ def test_classify_deleted_wal_separately_from_main_file_replacement():
assert classify_persistence_error(str(replaced)) == "replaced"
-def test_iter_holders_empty_on_non_linux(monkeypatch, tmp_path):
- monkeypatch.setattr(hermes_state.sys, "platform", "win32")
- assert iter_deleted_sqlite_sidecar_holders(tmp_path / "state.db") == []
def test_clean_open_and_second_open_still_work(tmp_path, force_wal):
diff --git a/tests/hermes_state/test_fts_rebuild_admission.py b/tests/hermes_state/test_fts_rebuild_admission.py
index 7604071aa07..a7d4b9f5d93 100644
--- a/tests/hermes_state/test_fts_rebuild_admission.py
+++ b/tests/hermes_state/test_fts_rebuild_admission.py
@@ -307,7 +307,6 @@ class TestOrphanedHolderStalenessBreak:
):
"""A record naming a live pid must defer even after timeout."""
import json
- import os
lock = _lock_file(db.db_path)
with _rebuild_lock_held_by_other_process(db.db_path) as proc:
@@ -537,7 +536,8 @@ class TestDeferredFtsRetryInProcess:
)
t0 = time.monotonic()
assert gw.retry_deferred_fts_recovery() is False
- assert time.monotonic() - t0 < 2.0
+ # Budget is 30s; a generous bound still proves it did not wait it out.
+ assert time.monotonic() - t0 < 15.0
assert gw._fts_stale is True
# Rate limit engaged: an immediate second call is a no-op.
assert gw.retry_deferred_fts_recovery() is False
diff --git a/tests/hermes_state/test_fts_trigram_subagent_exclusion.py b/tests/hermes_state/test_fts_trigram_subagent_exclusion.py
index 49ac8cbab00..f51ebb9fde4 100644
--- a/tests/hermes_state/test_fts_trigram_subagent_exclusion.py
+++ b/tests/hermes_state/test_fts_trigram_subagent_exclusion.py
@@ -11,7 +11,6 @@ import pytest
from hermes_state import SessionDB
from hermes_state_common import SCHEMA_VERSION
-from hermes_state_common import FTS_TRIGRAM_EXCLUDED_SOURCES, fts_trigram_session_sql
@pytest.fixture
@@ -155,8 +154,3 @@ def test_v29_install_purges_child_rows_on_upgrade(tmp_path):
migrated.close()
-def test_predicate_constants_agree():
- assert "subagent" in FTS_TRIGRAM_EXCLUDED_SOURCES
- assert "cron" in FTS_TRIGRAM_EXCLUDED_SOURCES
- sql = fts_trigram_session_sql("s")
- assert sql.startswith("s.source NOT IN (") and "s.model_config" in sql
diff --git a/tests/hermes_state/test_fts_update_of_narrowing.py b/tests/hermes_state/test_fts_update_of_narrowing.py
index 75742a76e2c..9e1002012dd 100644
--- a/tests/hermes_state/test_fts_update_of_narrowing.py
+++ b/tests/hermes_state/test_fts_update_of_narrowing.py
@@ -3,14 +3,12 @@
from __future__ import annotations
import sqlite3
-import tempfile
from pathlib import Path
import pytest
from hermes_state import SessionDB
from hermes_state_common import FTS_CJK_STALE_KEY
-from hermes_state_schema import SessionSchemaMixin
def _trigger_sql(conn: sqlite3.Connection, name: str) -> str | None:
@@ -123,14 +121,6 @@ def test_migrate_replaces_broad_update_trigger(tmp_path: Path):
db.close()
-def test_needs_narrowing_helper():
- assert SessionSchemaMixin._fts_update_trigger_needs_narrowing(
- "CREATE TRIGGER t AFTER UPDATE ON messages BEGIN SELECT 1; END"
- )
- assert not SessionSchemaMixin._fts_update_trigger_needs_narrowing(
- "CREATE TRIGGER t AFTER UPDATE OF content ON messages BEGIN SELECT 1; END"
- )
- assert not SessionSchemaMixin._fts_update_trigger_needs_narrowing(None)
def test_v23_status_only_update_bypasses_fts_trigger_body(tmp_path: Path):
diff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.py
index 9862a73aa02..3c9e315d173 100644
--- a/tests/hermes_state/test_hermes_state.py
+++ b/tests/hermes_state/test_hermes_state.py
@@ -1036,50 +1036,6 @@ class TestFTS5Search:
]
assert all("context" in row and row["context"] for row in default)
- def test_search_projection_skips_context_enrichment_queries(self, db, monkeypatch):
- db.create_session(session_id="s1", source="cli")
- db.append_message("s1", role="user", content="before")
- db.append_message("s1", role="assistant", content="projectionneedle")
- db.append_message("s1", role="user", content="after")
-
- statements = []
- traced_connections = []
- read_ctx = db._read_ctx
-
- @contextlib.contextmanager
- def trace_read_context():
- with read_ctx() as conn:
- conn.set_trace_callback(statements.append)
- traced_connections.append(conn)
- yield conn
-
- monkeypatch.setattr(db, "_read_ctx", trace_read_context)
-
- def context_query_count():
- normalized = (" ".join(sql.upper().split()) for sql in statements)
- return sum("WITH TARGET AS (" in sql for sql in normalized)
-
- try:
- projected = db.search_messages(
- "projectionneedle", fields=("session_id", "snippet")
- )
- assert len(projected) == 1
- assert context_query_count() == 0
-
- full = db.search_messages(
- "projectionneedle", fields=("session_id", "context")
- )
- assert len(full) == 1
- assert full[0]["context"]
- assert context_query_count() == 1
-
- default = db.search_messages("projectionneedle")
- assert len(default) == 1
- assert default[0]["context"]
- assert context_query_count() == 2
- finally:
- for conn in {id(conn): conn for conn in traced_connections}.values():
- conn.set_trace_callback(None)
def test_sanitize_fts5_query_strips_dangerous_chars(self):
"""Unit test for _sanitize_fts5_query static method."""
@@ -1234,10 +1190,6 @@ class TestCounts:
- def test_session_count_ge_empty(self, db):
- """session_count_ge should return False for 0 sessions."""
- assert db.session_count_ge(1) is False
- assert db.session_count_ge(2) is False
def test_session_count_ge_at_threshold(self, db):
"""session_count_ge should True when count >= n."""
@@ -2804,10 +2756,6 @@ class TestListSessionsRich:
activity = _activity_snapshot(db, "gw-1")
assert activity["last_activity_description"] == "compressing context"
- def test_order_by_last_active_surfaces_recently_touched_older_session_first(self, db):
- t0 = 1709500000.0
- db.create_session("old", "cli")
- db.create_session("new", "cli")
@@ -3041,16 +2989,6 @@ class TestListSessionsRich:
# tests/hermes_state/test_resolve_resume_session_id.py
# ::test_follows_compression_tip_when_parent_retains_messages.
- def test_session_key_predicate_can_use_session_key_index(self, db):
- plan = db._conn.execute(
- "EXPLAIN QUERY PLAN "
- "SELECT s.id FROM sessions s WHERE s.session_key = ? "
- "ORDER BY s.started_at DESC LIMIT 10",
- ("agent:main:telegram:dm:lane",),
- ).fetchall()
-
- detail = " ".join(row[-1] for row in plan)
- assert "idx_sessions_session_key" in detail, detail
def test_delegate_subagent_marker_hides_orphaned_row(self, db):
"""``_delegate_from`` keeps delegate rows out of pickers after orphaning."""
@@ -3401,49 +3339,6 @@ class TestCompressionChainProjection:
assert tip2_row["preview"].startswith("second conversation continuation")
assert tip2_row["cwd"] == "/tmp/workspaces/second"
- def test_list_batches_tip_row_fetch_into_one_query(self, db, monkeypatch):
- """Projection must resolve tip rows for a whole page in one batched
- query, not one _get_session_rich_row() call per compression root."""
- import time as _time
-
- t0 = _time.time() - 7200
- self._build_compression_chain(db, t0)
- db.create_session("root2", "cli")
- db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (t0 + 100, "root2"))
- db.append_message("root2", "user", "second conversation start")
- db._conn.execute(
- "UPDATE sessions SET ended_at=?, end_reason=? WHERE id=?",
- (t0 + 200, "compression", "root2"),
- )
- db.create_session("tip2", "cli", parent_session_id="root2")
- db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (t0 + 201, "tip2"))
- db.append_message("tip2", "user", "second continuation")
- db._conn.commit()
-
- batch_calls = []
- single_calls = []
- original_batch = db._get_session_rich_rows_batch
- original_single = db._get_session_rich_row
-
- def counting_batch(session_ids, **kwargs):
- batch_calls.append(list(session_ids))
- return original_batch(session_ids, **kwargs)
-
- def counting_single(session_id, **kwargs):
- single_calls.append(session_id)
- return original_single(session_id, **kwargs)
-
- monkeypatch.setattr(db, "_get_session_rich_rows_batch", counting_batch)
- monkeypatch.setattr(db, "_get_session_rich_row", counting_single)
-
- sessions = db.list_sessions_rich(source="cli", limit=20)
- assert len(sessions) >= 2 # sanity: both chains actually surfaced
-
- # Two compression roots resolved with exactly one batched call, and
- # zero single-row calls — not one single-row call per root.
- assert len(batch_calls) == 1
- assert set(batch_calls[0]) == {"tip1", "tip2"}
- assert single_calls == []
@@ -3506,14 +3401,6 @@ class TestExcludeSources:
-class TestResolveSessionByNameOrId:
- """Tests for the main.py helper that resolves names or IDs."""
-
- def test_resolve_by_id(self, db):
- db.create_session("test-id-123", "cli")
- session = db.get_session("test-id-123")
- assert session is not None
- assert session["id"] == "test-id-123"
@@ -3560,12 +3447,6 @@ class TestStateMeta:
class TestVacuum:
- def test_vacuum_runs_without_error(self, db):
- """VACUUM must succeed on a fresh DB (no rows to reclaim)."""
- db.create_session(session_id="s1", source="cli")
- db.append_message(session_id="s1", role="user", content="hi")
- # Should not raise, even though there's nothing significant to reclaim.
- db.vacuum()
def test_auto_maintenance_records_successful_vacuum(self, db, monkeypatch):
monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 3)
@@ -3764,19 +3645,6 @@ class TestVacuum:
class TestOptimizeFts:
- def test_optimize_returns_index_count(self, db):
- """A fresh DB has both FTS indexes; optimize merges both."""
- db.create_session(session_id="s1", source="cli")
- db.append_message(session_id="s1", role="user", content="hello world")
- statements = []
- db._conn.set_trace_callback(statements.append)
- try:
- assert db.optimize_fts() == 2
- finally:
- db._conn.set_trace_callback(None)
- optimize_sql = [sql for sql in statements if "'optimize'" in sql]
- assert len(optimize_sql) == 2
- assert not any("'merge'" in sql for sql in optimize_sql)
@@ -4823,7 +4691,6 @@ class TestApplyWalProbe:
@pytest.fixture(autouse=True)
def _assume_fixed_sqlite(self, monkeypatch):
"""These cases cover the fixed-SQLite WAL path (not the #69784 gate)."""
- import hermes_state
monkeypatch.setattr(
hermes_state_wal, "is_sqlite_wal_reset_vulnerable", lambda version_info=None: False
@@ -4909,32 +4776,6 @@ class TestApplyWalProbe:
- def test_returns_wal_not_delete_from_probe(self, tmp_path):
- """Early-return only on 'wal'; 'delete' or 'memory' must fall through to set-pragma."""
- import sqlite3
- from hermes_state_wal import apply_wal_with_fallback
-
- class _TracingConn(sqlite3.Connection):
- def __init__(self, *a, **kw):
- super().__init__(*a, **kw)
- self.executed = []
-
- def execute(self, sql, params=()):
- self.executed.append(sql)
- return super().execute(sql, params)
-
- # Fresh DB is in "delete" mode — probe returns "delete", must NOT early-return.
- db_path = tmp_path / "delete_mode.db"
- conn = _TracingConn(str(db_path))
- try:
- result = apply_wal_with_fallback(conn)
- finally:
- conn.close()
-
- assert result == "wal"
- assert any("journal_mode=WAL" in sql for sql in conn.executed), (
- "set-pragma must fire when probe returns 'delete'"
- )
class TestSessionArchive:
@@ -5406,12 +5247,6 @@ class TestCompactRows:
- def test_get_session_rich_row_compact_omits_system_prompt(self, db):
- self._create(db, "s1", system_prompt="should be gone")
- row = db._get_session_rich_row("s1", compact_rows=True)
- assert row is not None
- assert "system_prompt" not in row
- assert row["id"] == "s1"
def test_batch_compact_rows_omits_system_prompt_keeps_git_fields(self, db):
"""_get_session_rich_rows_batch(compact_rows=True) must apply the same
@@ -6109,16 +5944,6 @@ class TestInsightsToolCallIndex:
).fetchone()
return row["sql"] if row else None
- def test_index_created_on_fresh_db(self, tmp_path):
- db = SessionDB(db_path=tmp_path / "fresh.db")
- try:
- sql = self._index_defn(db._conn)
- assert sql is not None, "partial index missing on a fresh database"
- # Partial predicate must match the queried rows exactly.
- assert "role = 'assistant'" in sql
- assert "tool_calls IS NOT NULL" in sql
- finally:
- db.close()
def test_index_created_on_existing_db(self, tmp_path):
"""Reopening a DB that predates the index must create it (SCHEMA_SQL is
@@ -6139,18 +5964,6 @@ class TestInsightsToolCallIndex:
finally:
db2.close()
- def test_index_predicate_is_partial(self, db):
- """The index covers only the assistant tool-call rows Insights reads.
-
- Query-plan coverage (that the Insights queries actually select this
- index, for both scopes, without ANALYZE) lives with the queries in
- tests/agent/test_insights.py.
- """
- sql = self._index_defn(db._conn)
- assert sql is not None
- assert "WHERE" in sql
- assert "role = 'assistant'" in sql
- assert "tool_calls IS NOT NULL" in sql
class TestFtsRebuildFinishWithoutTrigram:
"""An FTS index that the runtime cannot maintain must not wedge the store.
@@ -6313,7 +6126,6 @@ class TestPerformancePragmasEndToEnd:
conn.close()
def _fresh_home(self, tmp_path, monkeypatch, config_text=None):
- import hermes_state
# Local venvs may bundle a WAL-reset-vulnerable SQLite (e.g. 3.46.0),
# which would silently disable WAL and skip the per-thread reader
diff --git a/tests/hermes_state/test_hermes_state_compression_busy_retry.py b/tests/hermes_state/test_hermes_state_compression_busy_retry.py
index 86c9ba62a52..33e69451af8 100644
--- a/tests/hermes_state/test_hermes_state_compression_busy_retry.py
+++ b/tests/hermes_state/test_hermes_state_compression_busy_retry.py
@@ -22,7 +22,7 @@ from pathlib import Path
import pytest
-from hermes_state import SessionCompressionInProgressError, SessionDB
+from hermes_state import SessionDB
from hermes_state_errors import CompressionSessionBusyError
@@ -74,15 +74,8 @@ def test_the_lock_owner_append_still_works(db: SessionDB) -> None:
assert any(r["content"] == "written by the compressor" for r in rows)
-def test_transient_error_is_a_subclass_of_the_original(db: SessionDB) -> None:
- """Existing `except CompressionSessionBusyError` handlers must still catch."""
- assert issubclass(SessionCompressionInProgressError, CompressionSessionBusyError)
-def test_no_lock_means_no_delay(db: SessionDB) -> None:
- started = time.monotonic()
- db.append_message("sess1", role="user", content="uncontended")
- assert time.monotonic() - started < 0.5
def test_a_lost_compression_lease_still_fails_fast(db: SessionDB) -> None:
diff --git a/tests/hermes_state/test_hermes_state_conn_lock_audit.py b/tests/hermes_state/test_hermes_state_conn_lock_audit.py
deleted file mode 100644
index 1b05f788b76..00000000000
--- a/tests/hermes_state/test_hermes_state_conn_lock_audit.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Lock audit for every call on the shared writer connection (#99349).
-
-``SessionDB._conn`` is opened with ``check_same_thread=False`` and shared
-across threads (``AsyncSessionDB`` offloads every method via
-``asyncio.to_thread``), so every *call* on it must hold ``self._lock``.
-A lock-free ``self._conn.execute(...)`` — even a pure SELECT — can run
-concurrently with ``close()`` deallocating the connection's pysqlite
-statement cache, which segfaults the interpreter (observed in the field:
-``_PyDict_GetItem_KnownHash`` via ``bounded_lru_cache_wrapper`` on one
-thread while ``pysqlite_connection_close`` tears the cache down on
-another). "Read-only" is not an exemption: the race is on the connection
-object, not the database file.
-
-Reads that must not contend on the writer lock go through
-``SessionDB._read_ctx()`` instead — it borrows a pooled read connection
-(exclusively checked out for the block) and its non-WAL fallback is the
-writer connection *under* ``self._lock``.
-
-This is an AST audit in the spirit of
-``tests/gateway/test_async_session_db.py``: it fails on the next
-``self._conn.<method>(...)`` call site added outside ``with self._lock:``.
-"""
-
-import ast
-from pathlib import Path
-
-# Functions allowed to touch self._conn without the lock: construction-time
-# code that runs before the instance is ever shared with another thread.
-_ALLOWED_UNLOCKED_FNS = frozenset({
- "__init__",
- "_connect_and_init",
- "_connect_and_init_with_lock_patience",
-})
-
-
-def _repo_root() -> Path:
- return Path(__file__).resolve().parents[2]
-
-
-def _nearest_enclosing_fn(tree: ast.AST) -> dict:
- """Map id(node) -> name of the nearest enclosing function ("<module>"
- at module level). Nested defs override their parents."""
- enclosing: dict = {}
-
- def visit(node: ast.AST, current: str) -> None:
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- current = node.name
- enclosing[id(node)] = current
- for child in ast.iter_child_nodes(node):
- visit(child, current)
-
- visit(tree, "<module>")
- return enclosing
-
-
-def _unlocked_conn_calls(tree: ast.AST):
- """Return (lineno, enclosing_fn, method) for each self._conn.<m>(...)
- call that is not lexically inside a ``with self._lock:`` block."""
- locked_ids = set()
- for node in ast.walk(tree):
- if isinstance(node, (ast.With, ast.AsyncWith)):
- for item in node.items:
- ctx = item.context_expr
- if (
- isinstance(ctx, ast.Attribute)
- and ctx.attr == "_lock"
- and isinstance(ctx.value, ast.Name)
- and ctx.value.id == "self"
- ):
- locked_ids.update(id(child) for child in ast.walk(node))
-
- enclosing = _nearest_enclosing_fn(tree)
-
- offending = []
- for node in ast.walk(tree):
- if not isinstance(node, ast.Call):
- continue
- func = node.func
- if not (
- isinstance(func, ast.Attribute)
- and isinstance(func.value, ast.Attribute)
- and func.value.attr == "_conn"
- and isinstance(func.value.value, ast.Name)
- and func.value.value.id == "self"
- ):
- continue
- if id(node) in locked_ids:
- continue
- fn = enclosing.get(id(node), "<module>")
- if fn in _ALLOWED_UNLOCKED_FNS:
- continue
- offending.append((node.lineno, fn, func.attr))
- return offending
-
-
-def test_every_conn_call_outside_construction_holds_the_lock():
- src = (_repo_root() / "hermes_state.py").read_text(encoding="utf-8")
- tree = ast.parse(src)
- offending = _unlocked_conn_calls(tree)
- assert not offending, (
- "self._conn.<method>() called without `with self._lock:` — this "
- "races SessionDB.close() inside pysqlite's statement cache and "
- "segfaults the process (#99349). Use `with self._read_ctx() as "
- "conn:` for reads, or take self._lock. Sites: "
- + ", ".join(
- f"line {lineno} in {fn}(): self._conn.{meth}(...)"
- for lineno, fn, meth in offending
- )
- )
diff --git a/tests/hermes_state/test_hermes_state_ids.py b/tests/hermes_state/test_hermes_state_ids.py
index 4e2389e9e1c..181970011a2 100644
--- a/tests/hermes_state/test_hermes_state_ids.py
+++ b/tests/hermes_state/test_hermes_state_ids.py
@@ -11,23 +11,8 @@ from datetime import datetime
import pytest
-import hermes_state_ids
from hermes_state_ids import SESSION_ID_PATTERN, new_session_id
-# (module, callable(mint) -> str) for each minting site; ``mint`` is the patched helper.
-SITES = [
- ("hermes_cli.foreign_sessions", None),
- ("agent.conversation_compression", None),
- ("hermes_cli.cli_commands_mixin", None),
- ("hermes_cli.cli_session_mixin", None),
- ("agent.agent_init", None),
- ("tui_gateway.server", lambda mod: mod._new_session_key()),
- ("gateway.session_lifecycle", lambda mod: mod._new_session_id(datetime(2026, 1, 2, 3, 4, 5))),
- ("hermes_state_portability", None),
- ("hermes_cli.cli_init_mixin", None),
-]
-
-
@pytest.mark.parametrize("hex_len,expected_re", [(6, r"^\d{8}_\d{6}_[0-9a-f]{6}$"), (8, r"^\d{8}_\d{6}_[0-9a-f]{8}$"),
(12, r"^\d{8}_\d{6}_[0-9a-f]{12}$")])
def test_minted_ids_are_what_salvage_classifies_as_session_ids(hex_len, expected_re):
@@ -36,13 +21,3 @@ def test_minted_ids_are_what_salvage_classifies_as_session_ids(hex_len, expected
assert re.fullmatch(expected_re, sid) and sid.startswith("20260102_030405_")
assert _is_session_id(sid)
assert SESSION_ID_PATTERN is importlib.import_module("hermes_cli.session_lost_and_found").SESSION_ID_PATTERN
-
-
[email protected]("module_name,call", SITES)
-def test_every_minting_site_imports_the_one_helper(module_name, call):
- mod = importlib.import_module(module_name)
- minted = [name for name in ("new_session_id", "mint_session_id")
- if getattr(mod, name, None) is hermes_state_ids.new_session_id]
- assert minted, f"{module_name} does not mint through hermes_state_ids.new_session_id"
- if call is not None:
- assert SESSION_ID_PATTERN.match(call(mod))
diff --git a/tests/hermes_state/test_hermes_state_readonly_preflight.py b/tests/hermes_state/test_hermes_state_readonly_preflight.py
index c532b16f6b5..263f201e0c9 100644
--- a/tests/hermes_state/test_hermes_state_readonly_preflight.py
+++ b/tests/hermes_state/test_hermes_state_readonly_preflight.py
@@ -121,7 +121,6 @@ class TestRefusalOutsideScope:
preflight_db_writability(db, db_label="custom.db")
msg = str(exc_info.value)
assert str(db) in msg
- assert "chmod u+rw" in msg
# Must NOT have silently chmod'd a file outside the home tree.
assert not os.access(db, os.W_OK)
finally:
@@ -139,7 +138,6 @@ class TestRefusalOutsideScope:
preflight_db_writability(db, db_label="custom.db")
msg = str(exc_info.value)
assert str(wal) in msg
- assert "Do NOT delete" in msg
finally:
os.chmod(wal, 0o644)
@@ -187,7 +185,6 @@ class TestSessionDBIntegration:
SessionDB(db_path)
msg = str(exc_info.value)
assert str(db_path) in msg
- assert "chmod" in msg
finally:
os.chmod(db_path, 0o644)
hermes_state._set_last_init_error(None)
diff --git a/tests/hermes_state/test_hermes_state_ux_messages.py b/tests/hermes_state/test_hermes_state_ux_messages.py
index 13c95032fee..01fefc956cc 100644
--- a/tests/hermes_state/test_hermes_state_ux_messages.py
+++ b/tests/hermes_state/test_hermes_state_ux_messages.py
@@ -1,36 +1,13 @@
"""Plain-language contracts for hermes_state user-facing errors (CLI UX message campaign, cluster D)."""
import hermes_state
-from hermes_state import SessionResumeTooLargeError, format_session_db_unavailable
+from hermes_state import format_session_db_unavailable
-def test_resume_too_large_names_export_and_config_commands():
- text = str(SessionResumeTooLargeError(4312, 4000))
- assert "4312" in text and "4000" in text
- assert "hermes sessions export" in text
- assert "hermes config set sessions.max_resume_messages 0" in text
- for jargon in ("lineage", "guard", "safe resume limit"):
- assert jargon not in text
-def test_resume_too_large_keeps_structured_fields():
- exc = SessionResumeTooLargeError(20_001, 20_000, scope="in its tip segment")
- assert (exc.message_count, exc.limit) == (20_001, 20_000)
- assert isinstance(exc, ValueError)
-def test_db_unavailable_points_to_doctor_without_sqlite_internals():
- hermes_state._set_last_init_error("OperationalError: database is locked")
- try:
- text = format_session_db_unavailable(details=True)
- finally:
- hermes_state._set_last_init_error(None)
- lead, *rest = text.splitlines()
- assert "session history" in lead
- assert "will not be saved" in lead.lower()
- for internal in ("sqlite.org", "WAL", "NFS/SMB/FUSE/ZFS"):
- assert internal not in lead
- assert rest and rest[0].startswith("Details: ") and "database is locked" in rest[0]
def test_db_unavailable_is_one_line_for_chat_surfaces_by_default():
@@ -44,23 +21,8 @@ def test_db_unavailable_is_one_line_for_chat_surfaces_by_default():
assert text.startswith("Cannot resume:")
-def test_db_unavailable_unknown_cause_on_network_drive_points_at_moving_not_doctor_fix():
- hermes_state._set_last_init_error("OperationalError: locking protocol")
- try:
- text = format_session_db_unavailable()
- finally:
- hermes_state._set_last_init_error(None)
- assert "network" in text
- assert "local disk" in text
- assert "hermes doctor --fix" not in text
-def test_db_unavailable_without_cause_still_names_doctor():
- hermes_state._set_last_init_error(None)
- text = format_session_db_unavailable(details=True)
- assert "hermes doctor" in text
- assert "will not be saved" in text.lower()
- assert "Details:" not in text
def test_db_unavailable_commands_are_pinned_to_the_failing_profile(monkeypatch, tmp_path):
diff --git a/tests/hermes_state/test_hermes_state_wal_fallback.py b/tests/hermes_state/test_hermes_state_wal_fallback.py
index 5ca78dcbbaf..59749f56afe 100644
--- a/tests/hermes_state/test_hermes_state_wal_fallback.py
+++ b/tests/hermes_state/test_hermes_state_wal_fallback.py
@@ -20,7 +20,7 @@ import pytest
import hermes_state
import hermes_state_wal
-from hermes_state import SessionDB, format_session_db_unavailable, get_last_init_error
+from hermes_state import SessionDB, get_last_init_error
from hermes_state_wal import WalUnsupportedError, apply_wal_with_fallback
@@ -585,41 +585,6 @@ class TestGetLastInitError:
assert "read-only filesystem" in cause
-class TestFormatSessionDbUnavailable:
- def test_bare_message_when_no_cause(self):
- """No init error recorded → generic message."""
- hermes_state._set_last_init_error(None)
- msg = format_session_db_unavailable()
- assert "hermes doctor" in msg
- assert "Details:" not in msg
-
- def test_adds_nfs_hint_for_locking_protocol(self):
- """Locking-protocol cause gets a network-drive pointer for the user."""
- hermes_state._set_last_init_error("OperationalError: locking protocol")
- msg = format_session_db_unavailable(details=True)
- # The raw sqlite phrase stays in the Details line; the user gets the network-drive cause and
- # a move-it action (`hermes doctor --fix` cannot repair a mount; a WAL-docs link is not
- # something a chat user can act on).
- lead, details = msg.splitlines()
- assert "network" in lead
- assert "local disk" in lead
- assert "hermes doctor --fix" not in lead
- assert details.startswith("Details: ") and "locking protocol" in details
- assert "sqlite.org" not in msg
-
- def test_known_bucket_keeps_table_action_and_appends_network_hint(self):
- """disk i/o error is a known bucket: its table action stays, the network hint is appended."""
- hermes_state._set_last_init_error("OperationalError: disk I/O error")
- msg = format_session_db_unavailable()
- assert "network drive" in msg
- assert "\n" not in msg
-
- def test_custom_prefix(self):
- """Callers can customize the prefix for context-specific messages."""
- hermes_state._set_last_init_error("OperationalError: locking protocol")
- msg = format_session_db_unavailable(prefix="Cannot /resume")
- assert msg.startswith("Cannot /resume:")
- assert "Details:" not in msg
class TestSessionDbUsesWalFallback:
diff --git a/tests/hermes_state/test_isolation_marker_env.py b/tests/hermes_state/test_isolation_marker_env.py
index d919bd486d2..85d5320ebbe 100644
--- a/tests/hermes_state/test_isolation_marker_env.py
+++ b/tests/hermes_state/test_isolation_marker_env.py
@@ -19,7 +19,6 @@ import subprocess
import sys
from pathlib import Path
-import hermes_state
import hermes_state_guard
REPO_ROOT = Path(__file__).resolve().parents[2]
@@ -67,13 +66,6 @@ def _minimal_env(**extra) -> dict:
return env
-def test_conftest_exports_the_marker():
- """The hermetic conftest must export the marker before tests run."""
- assert os.environ.get("HERMES_TEST_ISOLATION"), (
- "HERMES_TEST_ISOLATION must be exported by tests/conftest.py so "
- "subprocess children inherit a test-context signal that survives "
- "PYTEST_* scrubbing"
- )
def test_marker_alone_reports_test_context(monkeypatch):
diff --git a/tests/hermes_state/test_journal_mode_config.py b/tests/hermes_state/test_journal_mode_config.py
index b0b865c7e32..f1c4a37aeeb 100644
--- a/tests/hermes_state/test_journal_mode_config.py
+++ b/tests/hermes_state/test_journal_mode_config.py
@@ -35,7 +35,6 @@ def _disable_vulnerable_gate(monkeypatch: pytest.MonkeyPatch) -> None:
def _reset_configured_delete_override_warned_paths():
"""Reset the configured-delete-override warned-paths set so the
once-per-process-per-db_label dedup doesn't leak between tests."""
- import hermes_state
hermes_state_wal._delete_overridden_warned_paths.clear()
yield
@@ -86,10 +85,6 @@ def test_wal_probe_unknown_never_emits_set_pragma(monkeypatch, tmp_path, caplog)
sibling.close()
-def test_database_journal_mode_has_a_canonical_default():
- from hermes_cli.config import DEFAULT_CONFIG
-
- assert DEFAULT_CONFIG["database"]["journal_mode"] == "wal"
def test_resolve_journal_mode_uses_real_database_config(monkeypatch, tmp_path):
@@ -287,7 +282,7 @@ def test_real_db_openers_honor_configured_delete(monkeypatch, tmp_path):
from cron import executions
from gateway import delivery_ledger
from gateway.platforms.api_server import ResponseStore
- from hermes_cli import kanban_db, projects_db
+ from hermes_cli import projects_db
from hermes_cli import kanban_db_connect as kbc
from hermes_state import SessionDB
from plugins.memory.holographic.store import MemoryStore
diff --git a/tests/hermes_state/test_journal_mode_upgrade_warning.py b/tests/hermes_state/test_journal_mode_upgrade_warning.py
index 9341a8699f8..344bd2322a0 100644
--- a/tests/hermes_state/test_journal_mode_upgrade_warning.py
+++ b/tests/hermes_state/test_journal_mode_upgrade_warning.py
@@ -64,50 +64,12 @@ def _make_delete_db_with_content(path) -> None:
@pytest.fixture(autouse=True)
def _reset_dedup():
"""Order-independence: the warning is deduped per process per db_label."""
- import hermes_state
hermes_state_wal._journal_upgrade_warned_paths.clear()
yield
hermes_state_wal._journal_upgrade_warned_paths.clear()
-class TestTheContentProbe:
- """``_database_has_content`` is what keeps fresh installs quiet."""
-
- def test_a_brand_new_database_has_no_content(self, tmp_path):
- from hermes_state_wal import _database_has_content
-
- conn = sqlite3.connect(str(tmp_path / "new.db"))
- try:
- assert _database_has_content(conn) is False
- finally:
- conn.close()
-
- def test_a_database_with_a_table_has_content(self, tmp_path):
- from hermes_state_wal import _database_has_content
-
- path = tmp_path / "used.db"
- _make_delete_db_with_content(path)
- conn = sqlite3.connect(str(path))
- try:
- assert _database_has_content(conn) is True
- finally:
- conn.close()
-
- def test_an_unreadable_probe_answers_no_content(self, tmp_path):
- """Fail-quiet.
-
- Answering True on an error would emit the warning for a database we
- could not measure, which includes every fresh one.
- """
- from hermes_state_wal import _database_has_content
-
- conn = sqlite3.connect(":memory:")
- try:
- conn.close()
- assert _database_has_content(conn) is False
- finally:
- pass
class TestTheWarningFires:
@@ -133,32 +95,6 @@ class TestTheWarningFires:
assert "state.db" in blob
assert "delete" in blob.lower()
- def test_the_warning_names_the_setting_that_makes_it_stick(
- self, monkeypatch, tmp_path, caplog
- ):
- """The whole point.
-
- Telling an operator their mode changed, without telling them which
- lever survives an open, leaves them doing the same PRAGMA again.
- """
- from hermes_state_wal import apply_wal_with_fallback
-
- _configure_mode(monkeypatch, tmp_path, "wal")
- _disable_vulnerable_gate(monkeypatch)
- path = tmp_path / "existing-delete.db"
- _make_delete_db_with_content(path)
-
- conn = sqlite3.connect(str(path))
- try:
- with caplog.at_level("WARNING", logger="hermes_state"):
- apply_wal_with_fallback(conn, db_label="state.db")
- finally:
- conn.close()
-
- blob = "\n".join(r.getMessage() for r in caplog.records)
- assert "database.journal_mode" in blob, (
- "the warning must name the config key, not just report the change"
- )
def test_the_flip_still_happens(self, monkeypatch, tmp_path):
"""Log-only: WAL is still applied, and it still persists.
diff --git a/tests/hermes_state/test_live_db_isolation_guard.py b/tests/hermes_state/test_live_db_isolation_guard.py
index de7d11aec7b..af2094065db 100644
--- a/tests/hermes_state/test_live_db_isolation_guard.py
+++ b/tests/hermes_state/test_live_db_isolation_guard.py
@@ -77,13 +77,6 @@ class TestProductionPathRefused:
class TestHermeticPathsAllowed:
- def test_tmp_db_path_works(self, tmp_path):
- db = SessionDB(db_path=tmp_path / "state.db")
- try:
- db.create_session("iso-guard-session", "cli")
- assert db.get_session("iso-guard-session") is not None
- finally:
- db.close()
def test_tmp_hermes_home_default_resolution_works(self, tmp_path, monkeypatch):
"""Argless SessionDB() under a hermetic HERMES_HOME must succeed."""