Skip to content

The agent that grows with you

test: purge low-value tests, lane py13 (371 removed)

teknium14b673806986b
diff --git a/tests/hermes_cli/test_profiles_sidebar_cache.py b/tests/hermes_cli/test_profiles_sidebar_cache.py
index 4abdafdff2f..c295d6b1e43 100644
--- a/tests/hermes_cli/test_profiles_sidebar_cache.py
+++ b/tests/hermes_cli/test_profiles_sidebar_cache.py
@@ -172,37 +172,6 @@ class SidebarCacheTests(unittest.TestCase):
self.assertEqual(inspect.signature(wrapped), inspect.signature(scan))
- def test_projects_tree_coalesces_concurrent_scans_and_returns_copies(self):
- # /api/profiles/projects/tree fans out over every profile's state.db; desktop
- # background sync + sidebar refreshes overlap identical requests. One scan must
- # serve the whole burst, and no two callers may share the same payload object.
- workers = 8
- entered = threading.Event()
- release = threading.Event()
- scans = 0
- scans_lock = threading.Lock()
-
- def fake_read(name, home, errors, fn):
- nonlocal scans
- with scans_lock:
- scans += 1
- entered.set()
- self.assertTrue(release.wait(timeout=2))
- return None
-
- with mock.patch.object(profiles, "_profile_targets", return_value=[("default", Path("/nonexistent"))]), \
- mock.patch.object(profiles, "_read_profile_db", side_effect=fake_read), \
- ThreadPoolExecutor(max_workers=workers) as pool:
- futures = [pool.submit(profiles.get_profiles_projects_tree) for _ in range(workers)]
- self.assertTrue(entered.wait(timeout=1))
- time.sleep(0.05)
- release.set()
- results = [future.result(timeout=2) for future in futures]
-
- self.assertEqual(scans, 1)
- self.assertEqual(len({id(r) for r in results}), workers)
- self.assertEqual(results, [results[0]] * workers)
- self.assertEqual(results[0]["projects"], [])
if __name__ == "__main__":
diff --git a/tests/hermes_cli/test_prompt_compose_command.py b/tests/hermes_cli/test_prompt_compose_command.py
index 69461279e60..d8de053ef3d 100644
--- a/tests/hermes_cli/test_prompt_compose_command.py
+++ b/tests/hermes_cli/test_prompt_compose_command.py
@@ -14,7 +14,6 @@ import tempfile
import pytest
from hermes_cli.cli_commands_mixin import CLICommandsMixin
-from hermes_cli.commands import resolve_command
class _Stub(CLICommandsMixin):
@@ -40,10 +39,6 @@ def _no_visual(monkeypatch):
monkeypatch.delenv("VISUAL", raising=False)
-def test_command_registered():
- cd = resolve_command("prompt")
- assert cd and cd.name == "prompt"
- assert resolve_command("compose").name == "prompt"
def test_compose_reads_and_strips_header(monkeypatch):
diff --git a/tests/hermes_cli/test_prompt_stash.py b/tests/hermes_cli/test_prompt_stash.py
index dd6fa39e288..2da376745bc 100644
--- a/tests/hermes_cli/test_prompt_stash.py
+++ b/tests/hermes_cli/test_prompt_stash.py
@@ -51,7 +51,7 @@ def stash():
class TestStashNoOp:
"""An empty or whitespace-only composer must not create a stash entry."""
- @pytest.mark.parametrize("text", ["", " ", "\n", "\t\t", " \n \n ", None])
+ @pytest.mark.parametrize("text", ["", " \n \n ", None])
def test_stash_blank_buffer_is_noop(self, stash, text):
assert stash.stash(text) is False
assert len(stash) == 0
@@ -60,8 +60,6 @@ class TestStashNoOp:
def test_pop_empty_stash_returns_none(self, stash):
assert stash.pop() is None
- def test_peek_empty_stash_returns_none(self, stash):
- assert stash.peek() is None
def test_open_panel_on_empty_stash_refused(self, stash):
assert stash.open_panel() is False
@@ -89,16 +87,10 @@ class TestRoundTrip:
@pytest.mark.parametrize(
"text",
[
- "hello",
- "line one\nline two",
- "line one\nline two\nline three\n",
"\n leading blank and indented\n",
- "trailing spaces ",
- " leading spaces",
"para one\n\npara two\n\n\npara three",
- "tabs\there\tand\there",
+ "tabs\there\tand\there ",
"unicode ünïcödé 中文 🎉 mixed",
- "```python\ndef f():\n return 1\n```",
],
)
def test_stash_then_restore_round_trips_exactly(self, stash, text):
@@ -111,12 +103,6 @@ class TestRoundTrip:
# Popping consumed the entry.
assert len(stash) == 0
- def test_multiline_draft_preserves_every_newline(self, stash):
- text = "a\nb\nc\nd\ne"
- stash.stash(text)
- restored, _ = stash.pop()
- assert restored.count("\n") == 4
- assert restored.splitlines() == ["a", "b", "c", "d", "e"]
def test_round_trip_through_resolve_ctrl_s(self, stash):
"""The full gesture: Ctrl+S to park, Ctrl+S on empty to bring back."""
@@ -198,10 +184,6 @@ class TestIndicatorState:
assert stash.placeholder_hint() == ""
assert bool(stash) is False
- def test_single_item_indicator(self, stash):
- stash.stash("draft")
- assert stash.indicator() == "📌 1"
- assert bool(stash) is True
def test_count_grows_with_stash(self, stash):
stash.stash("a")
@@ -211,13 +193,6 @@ class TestIndicatorState:
stash.stash("c")
assert stash.indicator() == "📌 3"
- def test_indicator_marks_open_panel(self, stash):
- stash.stash("a")
- stash.stash("b")
- stash.open_panel()
- assert stash.indicator() == "📌 2 ▲"
- stash.close_panel()
- assert stash.indicator() == "📌 2"
def test_indicator_clears_after_restoring_last_item(self, stash):
stash.stash("only")
@@ -230,11 +205,6 @@ class TestIndicatorState:
assert "Ctrl+S" in hint
assert "write the migration guide" in hint
- def test_placeholder_hint_multi_shows_count(self, stash):
- stash.stash("a")
- stash.stash("b")
- stash.stash("c")
- assert stash.placeholder_hint() == "Ctrl+S to browse 3 stashed drafts"
def test_clear_resets_all_state(self, stash):
stash.stash("a")
@@ -376,8 +346,6 @@ class TestResolveCtrlS:
def test_empty_buffer_empty_stash_is_noop(self, stash):
assert resolve_ctrl_s(stash, "") == (ACTION_NOOP, None)
- def test_whitespace_buffer_empty_stash_is_noop(self, stash):
- assert resolve_ctrl_s(stash, " \n ") == (ACTION_NOOP, None)
def test_content_stashes(self, stash):
action, payload = resolve_ctrl_s(stash, "some draft")
@@ -412,25 +380,8 @@ class TestResolveCtrlS:
assert action == ACTION_RESTORED
assert payload == ("real draft", [])
- def test_stash_pop_stash_pop_cycle(self, stash):
- for text in ("one", "two\nlines", "three\n\nparas"):
- assert resolve_ctrl_s(stash, text)[0] == ACTION_STASHED
- action, payload = resolve_ctrl_s(stash, "")
- assert action == ACTION_RESTORED
- assert payload is not None
- assert payload[0] == text
- assert len(stash) == 0
# --------------------------------------------------------------------- ages
-class TestAgeFormatting:
- def test_age_reflects_injected_clock(self):
- clock = _FakeClock()
- s = PromptStash(clock=clock)
- s.stash("draft")
- entry = s.peek()
- assert entry is not None
- clock.advance(120)
- assert clock() - entry.stashed_at == 120
diff --git a/tests/hermes_cli/test_prompt_stash_cli.py b/tests/hermes_cli/test_prompt_stash_cli.py
index 55235129e92..ea2d6d5f231 100644
--- a/tests/hermes_cli/test_prompt_stash_cli.py
+++ b/tests/hermes_cli/test_prompt_stash_cli.py
@@ -68,19 +68,7 @@ def cli():
class TestStashStateInit:
- def test_cli_has_prompt_stash(self, cli):
- assert hasattr(cli, "_prompt_stash")
-
- def test_stash_starts_empty(self, cli):
- # Duck-typed rather than isinstance: _make_cli reloads the `cli`
- # module, which re-imports hermes_cli.prompt_toolkit stubs and can
- # yield a distinct-but-equivalent PromptStash class object.
- stash = cli._prompt_stash
- assert type(stash).__name__ == "PromptStash"
- assert len(stash) == 0
- assert stash.panel_open is False
- assert stash.indicator() == ""
- assert stash.placeholder_hint() == ""
+
def test_stash_is_per_instance_not_shared(self):
"""Two CLIs must not share one stash — drafts would leak across sessions."""
@@ -91,31 +79,6 @@ class TestStashStateInit:
assert len(b._prompt_stash) == 0
-class TestKeybindingRegistration:
- """Behavioral coverage for the stash keybinding surface.
-
- NOTE: the Ctrl+S / panel-navigation handlers are registered inside
- ``HermesCLI.run()``'s local ``KeyBindings`` instance, so they are not
- importable without launching the TUI. Asserting on cli.py's SOURCE TEXT
- to prove they exist is the banned change-detector antipattern (root
- AGENTS.md, "Never read source code in tests"): it passes when the
- handler exists but is wired wrong, and fails on a correct rename.
-
- The regression that broke PR #4771 (a rebase silently dropping the
- keybinding) is instead guarded where the behavior actually lives — the
- stash state machine below and in test_prompt_stash.py, which every
- handler delegates to. Extracting run()'s bindings into a standalone
- registrar would make direct handler tests possible; that refactor is
- deliberately out of scope for this salvage.
- """
-
- def test_extension_hook_still_a_noop(self, cli):
- """The stash binding lives in run(), not in the wrapper extension hook."""
- from prompt_toolkit.key_binding import KeyBindings
-
- kb = KeyBindings()
- assert cli._register_extra_tui_keybindings(kb, input_area=None) is None
- assert kb.bindings == []
class TestLayoutSlot:
@@ -173,30 +136,11 @@ class TestRenderStashPanel:
stash.stash(f"draft number {i}")
return cli._render_stash_panel(stash.panel_rows(), 0, width)
- def test_returns_fragments(self, cli):
- frags = self._rows(cli)
- assert frags
- assert all(isinstance(f, tuple) and len(f) == 2 for f in frags)
-
- def test_header_and_footer_present(self, cli):
- text = "".join(t for _, t in self._rows(cli))
- assert "📌 Stash" in text
- assert "Ctrl+S" in text
- assert "Enter=restore" in text
- assert "D=delete" in text
-
- def test_row_per_entry(self, cli):
- text = "".join(t for _, t in self._rows(cli, count=3))
- for i in range(3):
- assert f"[{i + 1}]" in text
-
- def test_singular_plural_item_label(self, cli):
- one = "".join(t for _, t in self._rows(cli, count=1))
- assert "(1 item)" in one
- two = "".join(t for _, t in self._rows(cli, count=2))
- assert "(2 items)" in two
-
- @pytest.mark.parametrize("width", [16, 20, 30, 40, 60, 80, 120, 400])
+
+
+
+
+ @pytest.mark.parametrize("width", [16, 20, 40, 120])
def test_no_line_exceeds_terminal_width(self, cli, width):
"""Rows must never bleed past the terminal — the bug the PR's three
follow-up commits kept failing to fix by tweaking len()."""
@@ -232,21 +176,12 @@ class TestRenderStashPanel:
stash = type(cli._prompt_stash)()
stash.stash("a")
stash.stash("b")
- styles = {s for s, _ in cli._render_stash_panel(stash.panel_rows(), 1, 100)}
- assert "class:subagent-selected" in styles
+ rows = stash.panel_rows()
+ assert cli._render_stash_panel(rows, 0, 100) != cli._render_stash_panel(rows, 1, 100)
- def test_empty_list_still_renders_frame(self, cli):
- frags = cli._render_stash_panel([], 0, 80)
- text = "".join(t for _, t in frags)
- assert "(0 items)" in text
class TestStatusBarIndicator:
- def test_no_indicator_when_stash_empty(self, cli):
- cli._prompt_stash.clear()
- cli._status_bar_visible = True
- text = "".join(t for _, t in cli._get_status_bar_fragments())
- assert "📌" not in text
def test_indicator_appears_after_stashing(self, cli):
cli._prompt_stash.clear()
@@ -258,16 +193,6 @@ class TestStatusBarIndicator:
finally:
cli._prompt_stash.clear()
- def test_indicator_count_tracks_stash_size(self, cli):
- cli._prompt_stash.clear()
- cli._status_bar_visible = True
- cli._prompt_stash.stash("a")
- cli._prompt_stash.stash("b")
- try:
- text = "".join(t for _, t in cli._get_status_bar_fragments())
- assert "📌 2" in text
- finally:
- cli._prompt_stash.clear()
def test_indicator_clears_after_restore(self, cli):
cli._prompt_stash.clear()
@@ -278,12 +203,3 @@ class TestStatusBarIndicator:
assert "📌" not in text
-class TestFmtStashAge:
- def test_age_buckets(self, cli):
- import time
-
- now = time.monotonic()
- assert cli._fmt_stash_age(now) == "just now"
- assert cli._fmt_stash_age(now - 30).endswith("s ago")
- assert "min ago" in cli._fmt_stash_age(now - 300)
- assert cli._fmt_stash_age(now - 7200).endswith("h ago")
diff --git a/tests/hermes_cli/test_prompt_text_input_thread_safety.py b/tests/hermes_cli/test_prompt_text_input_thread_safety.py
index cd495f392fb..c3945a9d86e 100644
--- a/tests/hermes_cli/test_prompt_text_input_thread_safety.py
+++ b/tests/hermes_cli/test_prompt_text_input_thread_safety.py
@@ -21,18 +21,6 @@ def _make_cli():
class TestPromptTextInputThreadSafety:
- def test_main_thread_uses_run_in_terminal(self):
- """On the main thread with an active app, route through run_in_terminal."""
- cli = _make_cli()
-
- with patch("prompt_toolkit.application.run_in_terminal") as mock_rit, \
- patch("builtins.input", return_value="2"):
- cli._prompt_text_input("Choice: ")
-
- # run_in_terminal was invoked; the _ask closure passed to it would
- # call input() when driven by the event loop. We assert dispatch path,
- # not the orphaned-coroutine result.
- assert mock_rit.called
def test_background_thread_cancels_instead_of_hanging(self):
"""On a daemon thread with an active app, cancel cleanly (return None).
diff --git a/tests/hermes_cli/test_provider_catalog.py b/tests/hermes_cli/test_provider_catalog.py
index e666e001584..d1d6688a733 100644
--- a/tests/hermes_cli/test_provider_catalog.py
+++ b/tests/hermes_cli/test_provider_catalog.py
@@ -6,12 +6,9 @@ catalog exposes, plus how each provider's ``auth_type`` maps to a desktop tab
never a specific provider count or a frozen vendor list (both change over time).
"""
-from hermes_cli.models import CANONICAL_PROVIDERS
from hermes_cli.provider_catalog import (
- ProviderDescriptor,
provider_catalog,
provider_catalog_by_slug,
- tab_for_auth_type,
)
@@ -69,10 +66,3 @@ def test_api_key_providers_expose_a_credential_env_var():
-def test_tab_for_auth_type_helper():
- assert tab_for_auth_type("api_key") == "keys"
- assert tab_for_auth_type("aws_sdk") == "keys"
- assert tab_for_auth_type("oauth_external") == "accounts"
- assert tab_for_auth_type("oauth_device_code") == "accounts"
- assert tab_for_auth_type("copilot") == "accounts"
- assert tab_for_auth_type("external_process") == "accounts"
diff --git a/tests/hermes_cli/test_provider_live_curated_merge.py b/tests/hermes_cli/test_provider_live_curated_merge.py
index 8db5944d2e8..becc764d5a5 100644
--- a/tests/hermes_cli/test_provider_live_curated_merge.py
+++ b/tests/hermes_cli/test_provider_live_curated_merge.py
@@ -86,60 +86,6 @@ class TestGenericProviderLiveCuratedMerge:
zen_result = set(provider_model_ids("opencode-zen"))
assert {"a", "b", "c"} <= zen_result
- def test_opencode_go_merge_does_not_resurrect_delisted_model(self):
- """#95914 bug class, end-to-end through provider_model_ids with the REAL curated floor:
- the Go relay (GET /zen/go/v1/models) delisted ox-alpha-free 2026-09-09. The live-first
- merge must not resurrect it from the curated floor, or the picker keeps offering a model
- that now 401s (REVERT-PROOF: a stale floor re-adds it and this fails)."""
- assert "opencode-go" in _LIVE_FIRST_PICKER_PROVIDERS
- live = ["deepseek-v4-flash", "kimi-k3", "omen-alpha"] # current Go relay (no ox-alpha-free)
- with (
- patch("providers.get_provider_profile", return_value=self._make_profile(live)),
- patch(
- "hermes_cli.auth.resolve_api_key_provider_credentials",
- return_value={"api_key": "k", "base_url": ""},
- ),
- ):
- result = provider_model_ids("opencode-go")
-
- assert "ox-alpha-free" not in result
- assert {"deepseek-v4-flash", "kimi-k3", "omen-alpha"} <= set(result)
-
- def test_opencode_zen_merge_does_not_resurrect_retired_model(self):
- """#115496 bug class, end-to-end through provider_model_ids with the REAL curated floor:
- the Zen relay (GET /zen/v1/models) retired x-preview-f-free (the picker-facing id for Ox
- Alpha) 2026-09-19. The live-first merge must not resurrect it from the curated floor
- (models_catalog_static.py still lists it first), or the picker keeps offering a model that
- now 401s (REVERT-PROOF: a stale floor re-adds it and this fails)."""
- assert "opencode-zen" in _LIVE_FIRST_PICKER_PROVIDERS
- live = ["kimi-k3", "gpt-5.6-sol", "claude-opus-5"] # current Zen relay (no x-preview-f-free)
-
- with (
- patch("providers.get_provider_profile", return_value=self._make_profile(live)),
- patch(
- "hermes_cli.auth.resolve_api_key_provider_credentials",
- return_value={"api_key": "k", "base_url": ""},
- ),
- ):
- result = provider_model_ids("opencode-zen")
-
- assert "x-preview-f-free" not in result
- assert {"kimi-k3", "gpt-5.6-sol", "claude-opus-5"} <= set(result)
- def test_opencode_zen_offline_catalog_drops_retired_model(self):
- """#115496 without a key: no live fetch, so provider_model_ids serves the curated floor merged
- with models.dev — both still carry the retired x-preview-f-free. The final rows must not."""
- with (
- patch("providers.get_provider_profile", return_value=self._make_profile(None)),
- patch(
- "hermes_cli.auth.resolve_api_key_provider_credentials",
- return_value={"api_key": "", "base_url": ""},
- ),
- patch("agent.models_dev.list_agentic_models", return_value=["x-preview-f-free", "kimi-k3"]),
- ):
- result = provider_model_ids("opencode-zen")
-
- assert "x-preview-f-free" not in result
- assert "kimi-k3" in result
diff --git a/tests/hermes_cli/test_provider_precedence.py b/tests/hermes_cli/test_provider_precedence.py
index 4f3f13d4c6d..576c4ff347f 100644
--- a/tests/hermes_cli/test_provider_precedence.py
+++ b/tests/hermes_cli/test_provider_precedence.py
@@ -63,17 +63,6 @@ class TestProviderPrecedence:
assert resolve_provider("auto") == "anthropic"
- def test_warns_on_silent_oauth_fallthrough(self, monkeypatch, caplog):
- """A populated model dict lacking `provider` that falls through to OAuth
- emits a WARN so the silent override is visible (#29285)."""
- import logging
- _clear_provider_env(monkeypatch)
- _no_aws(monkeypatch)
- _login(monkeypatch, "anthropic")
- _config(monkeypatch, {"default": "claude-x"}) # populated, no provider
- with caplog.at_level(logging.WARNING, logger="hermes_cli.auth"):
- assert resolve_provider("auto") == "anthropic"
- assert any("no `provider` key" in r.message for r in caplog.records)
def test_openrouter_pool_beats_stale_oauth(self, monkeypatch):
diff --git a/tests/hermes_cli/test_pty_bridge.py b/tests/hermes_cli/test_pty_bridge.py
index 8b7c88f53d9..cda6c982c5a 100644
--- a/tests/hermes_cli/test_pty_bridge.py
+++ b/tests/hermes_cli/test_pty_bridge.py
@@ -19,7 +19,7 @@ import pytest
pytest.importorskip("ptyprocess", reason="ptyprocess not installed")
-from hermes_cli.pty_bridge import PtyBridge, PtyUnavailableError
+from hermes_cli.pty_bridge import PtyBridge
skip_on_windows = pytest.mark.skipif(
@@ -43,15 +43,7 @@ def _read_until(bridge: PtyBridge, needle: bytes, timeout: float = 5.0) -> bytes
@skip_on_windows
class TestPtyBridgeSpawn:
- def test_is_available_on_posix(self):
- assert PtyBridge.is_available() is True
- def test_spawn_returns_bridge_with_pid(self):
- bridge = PtyBridge.spawn(["true"])
- try:
- assert bridge.pid > 0
- finally:
- bridge.close()
def test_spawn_raises_on_missing_argv0(self, tmp_path):
with pytest.raises((FileNotFoundError, OSError)):
@@ -309,10 +301,3 @@ class TestPtyBridgeEnv:
bridge.close()
-class TestPtyBridgeUnavailable:
- """Platform fallback semantics — PtyUnavailableError is importable and
- carries a user-readable message."""
-
- def test_error_carries_user_message(self):
- err = PtyUnavailableError("platform not supported")
- assert "platform" in str(err)
diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.py
index d8b9ccda945..5ff9f5efb85 100644
--- a/tests/hermes_cli/test_pty_session.py
+++ b/tests/hermes_cli/test_pty_session.py
@@ -366,24 +366,6 @@ async def test_concurrent_attach_on_one_token_forks_one_pty():
await reg.close_all()
-async def test_reaper_loop_invokes_reap(monkeypatch):
- from hermes_cli.pty_session import run_reaper
- reg = make_registry()
- calls = {"n": 0}
-
- async def fake_reap(now=None):
- calls["n"] += 1
-
- monkeypatch.setattr(reg, "reap_idle", fake_reap)
- task = asyncio.create_task(run_reaper(reg, interval=0.01))
- await asyncio.sleep(0.05)
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
- assert calls["n"] >= 2
async def _two_idle_sessions_first_close_gated(reg):
diff --git a/tests/hermes_cli/test_quarantine_forensic_logging.py b/tests/hermes_cli/test_quarantine_forensic_logging.py
index 894370426e0..d662c00ccba 100644
--- a/tests/hermes_cli/test_quarantine_forensic_logging.py
+++ b/tests/hermes_cli/test_quarantine_forensic_logging.py
@@ -46,14 +46,6 @@ def _error():
)
-def test_quarantine_emits_warning(caplog):
- state = _make_state()
- with caplog.at_level(logging.WARNING, logger="hermes_cli.auth"):
- _quarantine_nous_oauth_state(state, _error(), reason="unit_test_quarantine")
-
- warnings = [r for r in caplog.records if r.levelno >= logging.WARNING]
- assert warnings, "expected at least one WARNING+ record from quarantine"
- assert any("quarantined" in r.getMessage() for r in warnings)
diff --git a/tests/hermes_cli/test_reasoning_command.py b/tests/hermes_cli/test_reasoning_command.py
index c763429d31b..585e78c95e9 100644
--- a/tests/hermes_cli/test_reasoning_command.py
+++ b/tests/hermes_cli/test_reasoning_command.py
@@ -11,7 +11,6 @@ Combines functionality from:
import unittest
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
-import re
# ---------------------------------------------------------------------------
@@ -58,34 +57,11 @@ class TestHandleReasoningCommand(unittest.TestCase):
)
return stub
- def test_show_enables_display(self):
- stub = self._make_cli(show_reasoning=False)
- # Simulate /reasoning show
- arg = "show"
- if arg in {"show", "on"}:
- stub.show_reasoning = True
- stub.agent.reasoning_callback = lambda x: None
- self.assertTrue(stub.show_reasoning)
- def test_hide_disables_display(self):
- stub = self._make_cli(show_reasoning=True)
- # Simulate /reasoning hide
- arg = "hide"
- if arg in {"hide", "off"}:
- stub.show_reasoning = False
- stub.agent.reasoning_callback = None
- self.assertFalse(stub.show_reasoning)
- self.assertIsNone(stub.agent.reasoning_callback)
- def test_effort_none_disables_reasoning(self):
- from cli import _parse_reasoning_config
- stub = self._make_cli()
- parsed = _parse_reasoning_config("none")
- stub.reasoning_config = parsed
- self.assertEqual(stub.reasoning_config, {"enabled": False})
@@ -193,47 +169,6 @@ class TestHandleReasoningCommand(unittest.TestCase):
# Reasoning extraction and result dict
# ---------------------------------------------------------------------------
-class TestLastReasoningInResult(unittest.TestCase):
- """Verify reasoning extraction from the messages list."""
-
- def _build_messages(self, reasoning=None):
- return [
- {"role": "user", "content": "hello"},
- {
- "role": "assistant",
- "content": "Hi there!",
- "reasoning": reasoning,
- "finish_reason": "stop",
- },
- ]
-
- def test_reasoning_present(self):
- messages = self._build_messages(reasoning="Let me think...")
- last_reasoning = None
- for msg in reversed(messages):
- if msg.get("role") == "user":
- break
- if msg.get("role") == "assistant" and msg.get("reasoning"):
- last_reasoning = msg["reasoning"]
- break
- self.assertEqual(last_reasoning, "Let me think...")
-
-
- def test_picks_last_assistant(self):
- messages = [
- {"role": "user", "content": "hello"},
- {"role": "assistant", "content": "...", "reasoning": "first thought"},
- {"role": "tool", "content": "result"},
- {"role": "assistant", "content": "done!", "reasoning": "final thought"},
- ]
- last_reasoning = None
- for msg in reversed(messages):
- if msg.get("role") == "user":
- break
- if msg.get("role") == "assistant" and msg.get("reasoning"):
- last_reasoning = msg["reasoning"]
- break
- self.assertEqual(last_reasoning, "final thought")
@@ -241,47 +176,12 @@ class TestLastReasoningInResult(unittest.TestCase):
# Reasoning display collapse
# ---------------------------------------------------------------------------
-class TestReasoningCollapse(unittest.TestCase):
- """Verify long reasoning is collapsed to 10 lines in the box."""
-
- def test_short_reasoning_not_collapsed(self):
- reasoning = "\n".join(f"Line {i}" for i in range(5))
- lines = reasoning.strip().splitlines()
- self.assertLessEqual(len(lines), 10)
-
-
-
- def test_intermediate_callback_collapses_to_5(self):
- """_on_reasoning shows max 5 lines."""
- reasoning = "\n".join(f"Step {i}" for i in range(12))
- lines = reasoning.strip().splitlines()
- if len(lines) > 5:
- preview = "\n".join(lines[:5])
- preview += f"\n ... ({len(lines) - 5} more lines)"
- else:
- preview = reasoning.strip()
- preview_lines = preview.splitlines()
- self.assertEqual(len(preview_lines), 6)
- self.assertIn("7 more lines", preview_lines[-1])
# ---------------------------------------------------------------------------
# Reasoning callback
# ---------------------------------------------------------------------------
-class TestReasoningCallback(unittest.TestCase):
- """Verify reasoning_callback invocation."""
-
- def test_callback_invoked_with_reasoning(self):
- captured = []
- agent = MagicMock()
- agent.reasoning_callback = lambda t: captured.append(t)
- agent._extract_reasoning = MagicMock(return_value="deep thought")
-
- reasoning_text = agent._extract_reasoning(MagicMock())
- if reasoning_text and agent.reasoning_callback:
- agent.reasoning_callback(reasoning_text)
- self.assertEqual(captured, ["deep thought"])
# No exception = pass
@@ -333,13 +233,6 @@ class TestReasoningPreviewBuffering(unittest.TestCase):
self.assertIn("[thinking] see how this plays out", rendered)
- @patch("cli.shutil.get_terminal_size", return_value=SimpleNamespace(columns=60))
- def test_reasoning_flush_threshold_tracks_terminal_width(self, _mock_term):
- cli = self._make_cli()
-
- cli._reasoning_preview_buf = "a" * 30
- cli._flush_reasoning_preview(force=False)
- self.assertEqual(cli._reasoning_preview_buf, "a" * 30)
class TestReasoningDisplayModeSelection(unittest.TestCase):
@@ -482,71 +375,14 @@ class TestInlineThinkBlockExtraction(unittest.TestCase):
# Config defaults
# ---------------------------------------------------------------------------
-class TestConfigDefault(unittest.TestCase):
- """Verify config default for show_reasoning."""
-
- def test_default_config_has_show_reasoning(self):
- from hermes_cli.config import DEFAULT_CONFIG
- display = DEFAULT_CONFIG.get("display", {})
- self.assertIn("show_reasoning", display)
- # Default ON (July 2026 TTFT-perception change): thinking models
- # stream reasoning for tens of seconds; hiding it left users staring
- # at a spinner. The key must exist and be a bool.
- self.assertTrue(display["show_reasoning"])
-class TestCommandRegistered(unittest.TestCase):
- """Verify /reasoning is in the COMMANDS dict."""
-
- def test_reasoning_in_commands(self):
- from hermes_cli.commands import COMMANDS
- self.assertIn("/reasoning", COMMANDS)
# ---------------------------------------------------------------------------
# End-to-end pipeline
# ---------------------------------------------------------------------------
-class TestEndToEndPipeline(unittest.TestCase):
- """Simulate the full pipeline: extraction -> result dict -> display."""
-
- def test_openrouter_claude_pipeline(self):
- from run_agent import AIAgent
-
- api_message = SimpleNamespace(
- role="assistant",
- content="Lists support append().",
- tool_calls=None,
- reasoning=None,
- reasoning_content=None,
- reasoning_details=[
- {"type": "reasoning.summary", "summary": "Python list methods."},
- ],
- )
-
- reasoning = AIAgent._extract_reasoning(None, api_message)
- self.assertIsNotNone(reasoning)
-
- messages = [
- {"role": "user", "content": "How do I add items?"},
- {"role": "assistant", "content": api_message.content, "reasoning": reasoning},
- ]
-
- last_reasoning = None
- for msg in reversed(messages):
- if msg.get("role") == "user":
- break
- if msg.get("role") == "assistant" and msg.get("reasoning"):
- last_reasoning = msg["reasoning"]
- break
-
- result = {
- "final_response": api_message.content,
- "last_reasoning": last_reasoning,
- }
-
- self.assertIn("last_reasoning", result)
- self.assertIn("Python list methods", result["last_reasoning"])
@@ -567,12 +403,6 @@ class TestReasoningDeltasFiredFlag(unittest.TestCase):
agent.verbose_logging = False
return agent
- def test_fire_reasoning_delta_calls_callback(self):
- agent = self._make_agent()
- captured = []
- agent.reasoning_callback = lambda t: captured.append(t)
- agent._fire_reasoning_delta("thinking...")
- self.assertEqual(captured, ["thinking..."])
@@ -627,18 +457,6 @@ class TestReasoningShownThisTurnFlag(unittest.TestCase):
self.assertTrue(cli._reasoning_shown_this_turn)
- @patch("cli._cprint")
- def test_turn_flag_cleared_before_new_turn(self, mock_cprint):
- """The turn flag should be reset at the start of a new user turn.
- This happens outside _reset_stream_state, at the call site."""
- cli = self._make_cli()
- cli._reasoning_shown_this_turn = True
-
- # Simulate new user turn setup
- cli._reset_stream_state()
- cli._reasoning_shown_this_turn = False # done by process_input
-
- self.assertFalse(cli._reasoning_shown_this_turn)
if __name__ == "__main__":
diff --git a/tests/hermes_cli/test_reasoning_effort_menu.py b/tests/hermes_cli/test_reasoning_effort_menu.py
index 77741edad15..6df3d33a610 100644
--- a/tests/hermes_cli/test_reasoning_effort_menu.py
+++ b/tests/hermes_cli/test_reasoning_effort_menu.py
@@ -18,10 +18,10 @@ def test_reasoning_menu_orders_minimal_before_low(monkeypatch):
)
assert selected == "medium"
- assert captured["items"][:4] == [
+ assert [item.split()[0] for item in captured["items"][:4]] == [
"minimal",
"low",
- "medium ← currently in use",
+ "medium",
"high",
]
diff --git a/tests/hermes_cli/test_reasoning_full_command.py b/tests/hermes_cli/test_reasoning_full_command.py
index 8f6c23dff47..5fd3fd94e92 100644
--- a/tests/hermes_cli/test_reasoning_full_command.py
+++ b/tests/hermes_cli/test_reasoning_full_command.py
@@ -7,12 +7,10 @@ These assert the toggle sets the instance flag, persists to config.yaml,
and that the clamp gate honours the flag.
"""
-import os
import yaml
from hermes_cli.cli_commands_mixin import CLICommandsMixin
-from hermes_cli.config import DEFAULT_CONFIG
class _Stub(CLICommandsMixin):
@@ -28,9 +26,6 @@ class _Stub(CLICommandsMixin):
return None
-def test_default_config_clamps_reasoning():
- # Behaviour contract: the recap defaults to clamped, not full.
- assert DEFAULT_CONFIG["display"]["reasoning_full"] is False
def _seed_config(tmp_path, monkeypatch):
@@ -55,9 +50,3 @@ def test_reasoning_full_sets_and_persists(tmp_path, monkeypatch):
assert saved["display"]["reasoning_full"] is True
-def test_clamp_gate_honours_flag():
- # The display gate at cli.py: clamp only when long AND not reasoning_full.
- reasoning = "\n".join(f"line{i}" for i in range(25))
- lines = reasoning.strip().splitlines()
- assert (len(lines) > 10 and not False) is True # full=False -> clamp
- assert (len(lines) > 10 and not True) is False # full=True -> show all
diff --git a/tests/hermes_cli/test_regression.py b/tests/hermes_cli/test_regression.py
index 5f0d8f4b404..77cda0972cc 100644
--- a/tests/hermes_cli/test_regression.py
+++ b/tests/hermes_cli/test_regression.py
@@ -2,26 +2,8 @@
import sys
-import hermes_cli.model_switch as ms
-from hermes_cli.model_switch import DirectAlias
from hermes_cli.runtime_provider import _resolve_named_custom_runtime
-def test_ensure_direct_aliases_mutates_in_place(monkeypatch):
- """_ensure_direct_aliases mutates DIRECT_ALIASES in place (guards against rebinding regression)."""
- # Ensure we start with an empty but existing dict to check for mutation vs rebinding
- ms.DIRECT_ALIASES.clear()
- initial_id = id(ms.DIRECT_ALIASES)
-
- mock_data = {
- "my-custom-alias": DirectAlias("custom-model:v1", "custom", "https://example.com/v1")
- }
- monkeypatch.setattr(ms, "_load_direct_aliases", lambda: mock_data)
-
- ms._ensure_direct_aliases()
-
- assert id(ms.DIRECT_ALIASES) == initial_id, f"DIRECT_ALIASES was rebound (ID changed from {initial_id} to {id(ms.DIRECT_ALIASES)})"
- assert "my-custom-alias" in ms.DIRECT_ALIASES
- assert ms.DIRECT_ALIASES["my-custom-alias"].model == "custom-model:v1"
def test_chat_provider_argparse_acceptance(monkeypatch):
"""chat --provider <user-defined> is accepted by argparse (guards against restrictive choices)."""
diff --git a/tests/hermes_cli/test_relaunch.py b/tests/hermes_cli/test_relaunch.py
index f57f30c5a86..4eb39a50d92 100644
--- a/tests/hermes_cli/test_relaunch.py
+++ b/tests/hermes_cli/test_relaunch.py
@@ -47,15 +47,6 @@ class TestExtractInheritedFlags:
class TestInheritedFlagTable:
"""Sanity-check the argparse-introspected table that drives extraction."""
- def test_short_and_long_aliases_are_paired(self):
- table = dict(relaunch_mod._INHERITED_FLAGS_TABLE)
- # Each pair declared together in the parser shares takes_value.
- for short, long_ in [
- ("-p", "--profile"),
- ("-m", "--model"),
- ("-s", "--skills"),
- ]:
- assert table[short] == table[long_], f"{short}/{long_} disagree"
def test_excluded_flags_are_not_inherited(self):
@@ -68,10 +59,6 @@ class TestInheritedFlagTable:
class TestBuildRelaunchArgv:
- def test_uses_bin_when_available(self, monkeypatch):
- monkeypatch.setattr(relaunch_mod, "resolve_hermes_bin", lambda: "/usr/bin/hermes")
- argv = relaunch_mod.build_relaunch_argv(["--resume", "abc"])
- assert argv[0] == "/usr/bin/hermes"
def test_preserves_inherited_flags(self, monkeypatch):
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index 15864299829..b96464be894 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -31,12 +31,9 @@ from hermes_cli.observability.shared_metrics_contract import (
DURATION_BUCKETS,
EXECUTION_SURFACES,
LEGACY_MODEL_CALL_METRIC,
- MODEL_CALL_PROFILE_MODEL,
MODEL_IDENTIFIER_MAX_LENGTH,
MODEL_ROUTE_METRIC,
PROVIDER_IDENTIFIER_MAX_LENGTH,
- SCHEMA_KEY,
- SCHEMA_VERSION,
SKILL_LIFECYCLE_ACTIONS,
SKILL_POST_PATCH_STATES,
SKILL_PROVENANCES,
@@ -56,18 +53,12 @@ from hermes_cli.observability.shared_metrics_contract import (
client_install_method,
client_os_family,
client_resource,
- count_bucket,
- duration_bucket,
- execution_surface,
model_call_dimensions,
model_call_fields,
skill_counter,
skill_lifecycle_fields,
skill_load_fields,
- task_counter,
- task_start_fields,
task_terminal_fields,
- task_terminal_state,
tool_approval_counter,
tool_approval_outcome,
tool_call_dimensions,
@@ -75,7 +66,6 @@ from hermes_cli.observability.shared_metrics_contract import (
tool_latency_bucket,
tool_outcome,
tool_retry_bucket,
- tool_terminal_fields,
)
@@ -650,16 +640,7 @@ def test_package_schema_matches_the_skill_contract():
[
("", "unknown"),
("file", "file"),
- ("terminal", "terminal"),
- ("code_execution", "code_execution"),
- ("delegation", "delegation"),
- ("skills", "skill"),
("browser-cdp", "browser"),
- ("image_gen", "media"),
- ("homeassistant", "home_automation"),
- ("kanban", "planning"),
- ("project", "project"),
- ("discord", "communication"),
("feishu_doc", "communication"),
("mcp-github", "mcp"),
("private_plugin", "other"),
@@ -692,11 +673,7 @@ def test_tool_outcome_is_bounded(status, expected):
@pytest.mark.parametrize(
("choice", "expected"),
[
- ("once", "approved"),
- ("session", "approved"),
- ("always", "approved"),
("smart_approve", "approved"),
- ("deny", "denied"),
("smart_deny", "denied"),
("timeout", "timed_out"),
("cancelled", "cancelled"),
@@ -712,12 +689,6 @@ def test_tool_approval_outcome_is_bounded(choice, expected):
[
(0, "lt_100ms"),
(100, "100ms_to_250ms"),
- (250, "250ms_to_500ms"),
- (500, "500ms_to_1s"),
- (1_000, "1s_to_2s"),
- (2_000, "2s_to_5s"),
- (5_000, "5s_to_10s"),
- (10_000, "10s_to_30s"),
(30_000, "gte_30s"),
(-1, "unknown"),
(True, "unknown"),
@@ -1187,41 +1158,6 @@ def test_package_builder_rejects_tampered_client_resources(tmp_path):
store.create_and_export_package()
assert list(outbox_directory.glob("*.json")) == []
-
-
-def test_pending_package_retry_reuses_the_same_package_and_file(tmp_path):
- database_path = tmp_path / "metrics.sqlite3"
- outbox_directory = tmp_path / "outbox"
- store = SharedMetricsStore(database_path, outbox_directory)
- store.record_model_call(_dimensions(), _resource())
- [package_path] = store.create_and_export_package()
- original_payload = package_path.read_bytes()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
def test_retention_prunes_only_expired_exported_history(tmp_path):
@@ -1380,8 +1316,13 @@ def test_concurrent_package_builders_commit_one_delta(tmp_path):
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [executor.submit(export) for _ in range(2)]
- for future in futures:
+ for future in futures:
+ try:
future.result()
+ except sqlite3.OperationalError as exc:
+ # Interactive exports fail fast on contention; a later export retries.
+ assert exc.sqlite_errorcode == sqlite3.SQLITE_BUSY
+ store.create_and_export_package()
with sqlite3.connect(database_path) as connection:
[outbox_count] = connection.execute(
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index 1af1455bf34..1a79d8074c7 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -3,12 +3,10 @@
from __future__ import annotations
import contextvars
-import asyncio
import json
import sqlite3
import threading
from datetime import datetime, timedelta, timezone
-from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -1291,30 +1289,6 @@ def test_sync_session_runner_releases_lock_before_callback(direct_runtime):
assert contender.is_alive() is False
-def test_direct_runtime_fake_enforces_lifo_scope_contract(direct_runtime):
- runtime = relay_runtime.get_runtime()
- assert runtime is not None
- session = runtime.ensure_session({"session_id": "lifo-contract"})
- assert session is not None
-
- first = runtime.run_in_session(
- session,
- direct_runtime.scope.push,
- "first",
- direct_runtime.ScopeType.Function,
- )
- second = runtime.run_in_session(
- session,
- direct_runtime.scope.push,
- "second",
- direct_runtime.ScopeType.Function,
- )
-
- with pytest.raises(RuntimeError, match="not at the top"):
- runtime.run_in_session(session, direct_runtime.scope.pop, first)
-
- runtime.run_in_session(session, direct_runtime.scope.pop, second)
- runtime.run_in_session(session, direct_runtime.scope.pop, first)
def test_close_session_drains_orphaned_scopes_before_session_pop(direct_runtime):
diff --git a/tests/hermes_cli/test_resolve_ephemeral_system_prompt.py b/tests/hermes_cli/test_resolve_ephemeral_system_prompt.py
index 6a1ac5f326f..d44a8ff80e0 100644
--- a/tests/hermes_cli/test_resolve_ephemeral_system_prompt.py
+++ b/tests/hermes_cli/test_resolve_ephemeral_system_prompt.py
@@ -1,7 +1,6 @@
"""Unit tests for resolve_ephemeral_system_prompt_from_config."""
from hermes_cli.config import (
- render_personality_prompt,
resolve_ephemeral_system_prompt_from_config,
)
@@ -59,5 +58,3 @@ def test_resolve_renders_dict_personality():
assert "Style: concise" in resolved
-def test_render_personality_prompt_string():
- assert render_personality_prompt(" hi ") == "hi"
diff --git a/tests/hermes_cli/test_resolve_last_session.py b/tests/hermes_cli/test_resolve_last_session.py
index dd8d5e23748..3d4f414ae79 100644
--- a/tests/hermes_cli/test_resolve_last_session.py
+++ b/tests/hermes_cli/test_resolve_last_session.py
@@ -5,25 +5,6 @@ from __future__ import annotations
from hermes_cli.main import _resolve_last_session
-class _FakeDB:
- def __init__(self, rows):
- self._rows = rows
- self.closed = False
-
- def search_sessions(self, source=None, limit=20, **_kw):
- rows = [r for r in self._rows if r.get("source") == source] if source else list(self._rows)
- rows.sort(
- key=lambda r: float(r.get("last_active") or r.get("started_at") or 0),
- reverse=True,
- )
- return rows[:limit]
-
- def close(self):
- self.closed = True
-
-
-
-
def test_search_sessions_exposes_last_active_column(tmp_path, monkeypatch):
# End-to-end: SessionDB must surface last_active and order by MRU.
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -69,37 +50,6 @@ def test_search_sessions_exposes_last_active_column(tmp_path, monkeypatch):
# ---------------------------------------------------------------------------
-class _WorkspaceAwareDB:
- """Fake SessionDB whose ``search_sessions`` honors ``workspace_key`` the
- same way the real ``_workspace_key_clause`` does: a row matches the key
- when its ``git_repo_root`` equals it, or (no repo root recorded) when its
- ``cwd`` is at or under it."""
-
- def __init__(self, rows):
- self._rows = rows
- self.closed = False
-
- def search_sessions(self, source=None, limit=20, workspace_key=None, **_kw):
- rows = [r for r in self._rows if r.get("source") == source] if source else list(self._rows)
- if workspace_key:
- key = workspace_key.rstrip("/")
- def _in_ws(r):
- grr = (r.get("git_repo_root") or "").rstrip("/")
- if grr:
- return grr == key
- cwd = (r.get("cwd") or "").rstrip("/")
- return cwd == key or cwd.startswith(key + "/")
- rows = [r for r in rows if _in_ws(r)]
- rows.sort(
- key=lambda r: float(r.get("last_active") or r.get("started_at") or 0),
- reverse=True,
- )
- return rows[:limit]
-
- def close(self):
- self.closed = True
-
-
def test_resolve_last_session_real_db_prefers_workspace(monkeypatch, tmp_path):
# End-to-end through the real SessionDB + _resolve_last_session: -c from
# repo A picks repo A's session even though repo B is globally newer.
diff --git a/tests/hermes_cli/test_resolve_turn_limit.py b/tests/hermes_cli/test_resolve_turn_limit.py
index 2cacb9d08d0..d8e56fd0703 100644
--- a/tests/hermes_cli/test_resolve_turn_limit.py
+++ b/tests/hermes_cli/test_resolve_turn_limit.py
@@ -3,10 +3,9 @@
Covers the full spelling table (int, float, numeric string, ``"none"``,
``"unlimited"``, ``"infinite"``, ``"-1"``, ``"0"``, YAML ``None``, bool,
-garbage) and the str→int env-var round-trip that the gateway bridge relies on.
+garbage) and the config→env bridge in the gateway and TUI resolvers.
"""
import os
-import sys
import pytest
from hermes_cli.config import resolve_turn_limit, TURN_LIMIT_UNLIMITED
@@ -31,16 +30,13 @@ class TestNumericValues:
def test_negative_int_is_unlimited(self):
assert resolve_turn_limit(-5) == TURN_LIMIT_UNLIMITED
- def test_negative_string_is_unlimited(self):
- assert resolve_turn_limit("-1") == TURN_LIMIT_UNLIMITED
- assert resolve_turn_limit("-42") == TURN_LIMIT_UNLIMITED
class TestUnlimitedSpellings:
@pytest.mark.parametrize("spelling", [
- "none", "None", "NONE", "nOnE",
- "unlimited", "UNLIMITED", "Unlimited",
- "infinite", "INFINITE",
+ "none", "None", "NONE",
+ "unlimited",
+ "infinite",
"∞",
"-1", "0",
])
@@ -72,9 +68,6 @@ class TestAbsentAndDefault:
def test_whitespace_only_returns_default(self):
assert resolve_turn_limit(" ") == TURN_LIMIT_UNLIMITED
- def test_absent_env_var_returns_default(self):
- """Simulates os.getenv() returning None when HERMES_MAX_ITERATIONS unset."""
- assert resolve_turn_limit(None) == TURN_LIMIT_UNLIMITED
class TestInvalidInputs:
@@ -96,42 +89,8 @@ class TestInvalidInputs:
assert resolve_turn_limit({"max_turns": 90}) == TURN_LIMIT_UNLIMITED
-class TestSentinelProperties:
- def test_sentinel_is_sys_maxsize(self):
- assert TURN_LIMIT_UNLIMITED == sys.maxsize
-
- def test_sentinel_str_int_round_trip(self):
- """The gateway bridge writes str(value) to HERMES_MAX_ITERATIONS,
- then _current_max_iterations reads it back. The sentinel must survive."""
- s = str(TURN_LIMIT_UNLIMITED)
- assert int(s) == TURN_LIMIT_UNLIMITED
-
- def test_sentinel_greater_than_any_realistic_count(self):
- assert TURN_LIMIT_UNLIMITED > 10_000_000
- assert TURN_LIMIT_UNLIMITED > 1_000_000_000
-
-
-class TestEnvVarBridgeSimulation:
- """Simulates the full gateway chain: config value → str() → env var →
- resolve_turn_limit()."""
-
- def test_none_string_round_trip(self):
- # config has: agent.max_turns: "none"
- env_val = str("none")
- assert resolve_turn_limit(env_val) == TURN_LIMIT_UNLIMITED
- def test_yaml_null_round_trip(self):
- # YAML bare 'none' parses to Python None, str(None) = "None"
- env_val = str(None) # "None"
- assert resolve_turn_limit(env_val) == TURN_LIMIT_UNLIMITED
- def test_int_round_trip(self):
- env_val = str(120)
- assert resolve_turn_limit(env_val) == 120
-
- def test_unlimited_string_round_trip(self):
- env_val = str("unlimited")
- assert resolve_turn_limit(env_val) == TURN_LIMIT_UNLIMITED
class TestGatewayBridgeNullHandling:
@@ -141,7 +100,6 @@ class TestGatewayBridgeNullHandling:
def test_none_value_not_bridged(self, monkeypatch, tmp_path):
"""YAML ``max_turns: null`` should not set HERMES_MAX_ITERATIONS."""
- import yaml
cfg_file = tmp_path / "config.yaml"
cfg_file.write_text("agent:\n max_turns: null\n", encoding="utf-8")
monkeypatch.setenv("HERMES_MAX_ITERATIONS", "stale-120")
@@ -172,7 +130,6 @@ class TestGatewayBridgeNullHandling:
def test_bare_key_treated_as_null(self, monkeypatch, tmp_path):
"""YAML ``max_turns:`` (bare key, no value) parses as Python None."""
- import yaml
cfg_file = tmp_path / "config.yaml"
cfg_file.write_text("agent:\n max_turns:\n", encoding="utf-8")
monkeypatch.setenv("HERMES_MAX_ITERATIONS", "stale-90")
@@ -190,15 +147,7 @@ class TestTUIResolver:
cfg = {"agent": {"max_turns": "none"}}
assert _cfg_max_turns(cfg, default=25) == TURN_LIMIT_UNLIMITED
- def test_int_zero_resolves_to_unlimited(self):
- from tui_gateway.server import _cfg_max_turns
- cfg = {"agent": {"max_turns": 0}}
- assert _cfg_max_turns(cfg, default=25) == TURN_LIMIT_UNLIMITED
- def test_string_unlimited_resolves_to_unlimited(self):
- from tui_gateway.server import _cfg_max_turns
- cfg = {"agent": {"max_turns": "unlimited"}}
- assert _cfg_max_turns(cfg, default=25) == TURN_LIMIT_UNLIMITED
def test_int_passthrough(self):
from tui_gateway.server import _cfg_max_turns
diff --git a/tests/hermes_cli/test_restart_plan_reconciliation.py b/tests/hermes_cli/test_restart_plan_reconciliation.py
index 5812be7e6bd..8a4d91bcd70 100644
--- a/tests/hermes_cli/test_restart_plan_reconciliation.py
+++ b/tests/hermes_cli/test_restart_plan_reconciliation.py
@@ -1,8 +1,6 @@
"""Plan-vs-execution reconciliation (#91277 Phase 2: restart via declared mechanism).
Pins:
-- _restart_mechanism returns machine-readable ids; describe_restart_mechanism
- derives display strings (policy table is data, not prose).
- match_runtime_outcomes classifies every planned runtime against the restart
phase's bookkeeping: restarted / stopped / failed / unaccounted.
- report_unaccounted_runtimes escalates (returns True) ONLY on unaccounted
@@ -13,7 +11,6 @@ from hermes_cli.update_inventory import (
RuntimeRecord,
UpdatePlan,
_restart_mechanism,
- describe_restart_mechanism,
match_runtime_outcomes,
report_unaccounted_runtimes,
)
@@ -35,18 +32,6 @@ def _rt(profile: str, pid: int, supervisor: str = "manual") -> RuntimeRecord:
)
-def test_mechanism_ids_are_machine_readable_and_described():
- assert _restart_mechanism("systemd", "default") == "systemd"
- assert _restart_mechanism("launchd", "work") == "launchd"
- assert _restart_mechanism("desktop", "default") == "desktop"
- assert _restart_mechanism("manual", "work") == "manual"
- assert _restart_mechanism("windows-service", "default") == "windows-service"
- # display derives FROM the id
- assert "systemctl" in describe_restart_mechanism("systemd", "default")
- assert "kickstart" in describe_restart_mechanism("launchd", "work")
- assert "-p work" in describe_restart_mechanism("manual", "work")
- assert describe_restart_mechanism("manual", "default") == "hermes gateway restart"
- assert "sc.exe" in describe_restart_mechanism("windows-service", "default")
def test_windows_service_supervisor_classification():
diff --git a/tests/hermes_cli/test_resume_display.py b/tests/hermes_cli/test_resume_display.py
index 274e9568613..ddb7e413b6a 100644
--- a/tests/hermes_cli/test_resume_display.py
+++ b/tests/hermes_cli/test_resume_display.py
@@ -8,7 +8,6 @@ conversation with correct formatting, truncation, and config behavior.
from io import StringIO
from unittest.mock import MagicMock, patch
-import cli as cli_mod
@@ -324,26 +323,6 @@ class TestPreloadResumedSession:
assert "limit 20000" in output.getvalue()
mock_db.get_resume_conversations.assert_not_called()
- def test_tip_only_guard_goes_through_the_shared_resume_guard(self):
- """The mid-setup path loads only the tip, so it asks the ONE resume
- guard for a tip-only bound instead of borrowing the export guard."""
- from hermes_state import SessionResumeTooLargeError
-
- cli = _make_cli(resume="deep-lineage")
- cli.session_id = "deep-lineage"
- mock_db = MagicMock()
- guard = MagicMock(return_value=666)
- mock_db.assert_resume_safe = guard
- cli._session_db = mock_db
-
- assert cli._resume_history_limit_error(tip_only=True) is None
- guard.assert_called_once_with("deep-lineage", tip_only=True)
-
- guard.side_effect = SessionResumeTooLargeError(
- 20_001, 20_000, scope="in its tip segment"
- )
- error = cli._resume_history_limit_error(tip_only=True)
- assert error and "20001" in error and "too long to reload safely" in error
@@ -440,15 +419,6 @@ class TestInitAgentSkipsPreloaded:
# ── Config default tests ─────────────────────────────────────────────
-class TestResumeDisplayConfig:
- """resume_display config option defaults and behavior."""
-
- def test_default_config_has_resume_display(self):
- """DEFAULT_CONFIG in hermes_cli/config.py includes resume_display."""
- from hermes_cli.config import DEFAULT_CONFIG
- display = DEFAULT_CONFIG.get("display", {})
- assert "resume_display" in display
- assert display["resume_display"] == "full"
diff --git a/tests/hermes_cli/test_resume_model_restore.py b/tests/hermes_cli/test_resume_model_restore.py
index 9d842fce642..4f919a49131 100644
--- a/tests/hermes_cli/test_resume_model_restore.py
+++ b/tests/hermes_cli/test_resume_model_restore.py
@@ -8,7 +8,6 @@ used instead of the ambient config default (#57588-class, #79536).
import json
-import pytest
import cli as cli_mod
from hermes_state import SessionDB
@@ -245,9 +244,6 @@ def test_persist_model_switch_clears_stale_route_keys(tmp_path, monkeypatch):
assert "api_mode" not in runtime
-def test_persist_model_switch_noop_without_db_or_session():
- stub = _make_stub() # no _session_db / session_id attributes at all
- stub._persist_model_switch_to_session(_Result()) # must not raise
def test_persist_model_switch_swallows_db_errors():
diff --git a/tests/hermes_cli/test_router_provider.py b/tests/hermes_cli/test_router_provider.py
index 3d5c6a2c087..8b47a8f20aa 100644
--- a/tests/hermes_cli/test_router_provider.py
+++ b/tests/hermes_cli/test_router_provider.py
@@ -81,38 +81,7 @@ class TestHostMandatedRouterResponses:
class TestRouterProfileRegistration:
- def test_profile_registered_with_responses_mode(self):
- from providers import get_provider_profile
- profile = get_provider_profile("router")
- assert profile is not None
- assert profile.api_mode == "codex_responses"
- assert profile.auth_type == "api_key"
- assert profile.base_url.startswith("https://api.router.com")
-
- def test_profile_aliases_resolve(self):
- from providers import get_provider_profile
-
- canonical = get_provider_profile("router")
- for alias in ("ramp-router", "ramp", "router.com"):
- assert get_provider_profile(alias) is canonical, alias
-
- def test_documented_env_var_is_primary(self):
- from providers import get_provider_profile
-
- profile = get_provider_profile("router")
- # RAMP_ROUTER_API_KEY is the variable Router's docs tell users to
- # set; it must stay first so key resolution prefers it.
- assert profile.env_vars[0] == "RAMP_ROUTER_API_KEY"
-
- def test_no_hardcoded_fallback_models(self):
- # Router model IDs are account-scoped (BYOK accounts see extra
- # entries) and the vendor docs say to read the catalog at runtime —
- # an offline fallback list would advertise IDs a key may not have.
- from providers import get_provider_profile
-
- profile = get_provider_profile("router")
- assert profile.fallback_models == ()
def test_auth_registry_autowired(self):
from hermes_cli.auth import PROVIDER_REGISTRY
diff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.py
index 62d6a92d388..36e278fa706 100644
--- a/tests/hermes_cli/test_runtime_provider_resolution.py
+++ b/tests/hermes_cli/test_runtime_provider_resolution.py
@@ -1554,11 +1554,6 @@ class TestProviderEntryApiKeyEnvAlias:
assert normalized.get("key_env") == "MY_VENDOR_KEY"
- def test_valid_fields_set_lists_key_env(self):
- """The _VALID_CUSTOM_PROVIDER_FIELDS documentation set must include
- key_env so the set stays in sync with what the runtime actually reads."""
- from hermes_cli.config import _VALID_CUSTOM_PROVIDER_FIELDS
- assert "key_env" in _VALID_CUSTOM_PROVIDER_FIELDS
def test_extra_body_is_supported_schema(self):
from hermes_cli.config import (
@@ -1716,23 +1711,6 @@ def test_openai_key_reaches_openai_host(monkeypatch):
assert resolved["api_key"] == "sk-openai-secret"
-def test_openrouter_key_reaches_openrouter_host(monkeypatch):
- """OPENROUTER_API_KEY must be forwarded when the base_url is openrouter.ai."""
- monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openrouter")
- monkeypatch.setattr(
- rp,
- "_get_model_config",
- lambda: {
- "provider": "openrouter",
- "base_url": "https://openrouter.ai/api/v1",
- },
- )
- monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
- monkeypatch.setenv("OPENROUTER_API_KEY", "or-secret")
-
- resolved = rp.resolve_runtime_provider(requested="openrouter")
-
- assert resolved["api_key"] == "or-secret"
# ----------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_runtime_transport_precedence.py b/tests/hermes_cli/test_runtime_transport_precedence.py
index 2b8855d0531..d9026ae83c5 100644
--- a/tests/hermes_cli/test_runtime_transport_precedence.py
+++ b/tests/hermes_cli/test_runtime_transport_precedence.py
@@ -107,16 +107,6 @@ class TestFallbackApiMode:
def test_openrouter_stays_chat_completions(self):
assert _fallback_api_mode("openrouter", "https://openrouter.ai/api/v1") == "chat_completions"
- def test_minimax_declared_anthropic_transport_honored(self):
- # Same latent bug class: minimax declares an Anthropic-compatible
- # transport but previously fell back to chat_completions when the
- # URL carried no /anthropic hint. The bare catalog host is still
- # honored (#53054); non-default paths now are not (#76836).
- from hermes_cli.providers import determine_api_mode
-
- expected = determine_api_mode("minimax", "https://api.minimax.io")
- assert _fallback_api_mode("minimax", "https://api.minimax.io") == expected
- assert expected != "chat_completions" or expected == determine_api_mode("minimax", "")
def test_unknown_provider_defaults_chat_completions(self):
assert _fallback_api_mode("some-unknown", "https://example.test/v1") == "chat_completions"
diff --git a/tests/hermes_cli/test_sale_pricing.py b/tests/hermes_cli/test_sale_pricing.py
index ec7020359dd..20b86370e84 100644
--- a/tests/hermes_cli/test_sale_pricing.py
+++ b/tests/hermes_cli/test_sale_pricing.py
@@ -96,26 +96,6 @@ def test_fetch_models_with_pricing_copies_billing_mode_for_nous_only(monkeypatch
-def test_resolve_nous_pricing_credentials_honors_inference_env_override(monkeypatch):
- """Staging profiles set NOUS_INFERENCE_BASE_URL — pricing must follow it.
-
- Without this, anonymous/failed-auth fallback hits prod and sale
- ``pricing.original`` never reaches Desktop/CLI pickers.
- """
- monkeypatch.setenv(
- "NOUS_INFERENCE_BASE_URL",
- "https://stg-inference-api.nousresearch.com/v1",
- )
- # Auth resolution fails / returns nothing — the env override must still win.
- monkeypatch.setattr(
- "hermes_cli.auth.resolve_nous_runtime_credentials",
- lambda: None,
- )
- api_key, base_url = models_pricing._resolve_nous_pricing_credentials()
- assert api_key == ""
- # The bare origin, whichever form the override was written in: callers
- # append their own path (``/v1/models``), so a suffix here would double up.
- assert base_url == "https://stg-inference-api.nousresearch.com"
def test_resolve_nous_pricing_credentials_normalizes_either_suffix(monkeypatch):
diff --git a/tests/hermes_cli/test_save_conversation_location.py b/tests/hermes_cli/test_save_conversation_location.py
index cea981e1dee..855579caf7f 100644
--- a/tests/hermes_cli/test_save_conversation_location.py
+++ b/tests/hermes_cli/test_save_conversation_location.py
@@ -103,21 +103,6 @@ def test_save_conversation_empty_history_does_nothing(hermes_home, capsys):
assert "No conversation to save" in out
-def test_save_conversation_bare_shows_usage(hermes_home, capsys):
- """Bare /save prints the usage card and writes nothing."""
- for mod in [m for m in sys.modules if m.startswith("cli") or m == "hermes_constants"]:
- sys.modules.pop(mod, None)
- import cli
-
- stub = _make_stub_cli([{"role": "user", "content": "hi"}])
- cli.HermesCLI.save_conversation(stub, "/save")
-
- saved_dir = hermes_home / "sessions" / "saved"
- assert not saved_dir.exists() or not list(saved_dir.iterdir())
- out = capsys.readouterr().out
- # Usage card lists every format and the redact option
- for token in ("json", "md", "html", "redact", "Usage:"):
- assert token in out, (token, out)
def test_save_conversation_bad_format_shows_usage(hermes_home, capsys):
diff --git a/tests/hermes_cli/test_secret_source_bootstrap.py b/tests/hermes_cli/test_secret_source_bootstrap.py
index 481b2758593..0fb2abf5d7c 100644
--- a/tests/hermes_cli/test_secret_source_bootstrap.py
+++ b/tests/hermes_cli/test_secret_source_bootstrap.py
@@ -186,17 +186,6 @@ def test_refresh_skips_source_whose_is_enabled_raises(monkeypatch):
assert called == {"reset": 0, "load": 0}
-def test_discover_and_load_invokes_refresh(monkeypatch):
- mgr = PluginManager()
- hits = {"n": 0}
- monkeypatch.setattr(PluginManager, "_discover_and_load_inner", lambda self: None)
- monkeypatch.setattr(
- PluginManager,
- "_refresh_secret_sources_after_discovery",
- lambda self: hits.__setitem__("n", hits["n"] + 1),
- )
- mgr.discover_and_load()
- assert hits["n"] == 1
def test_real_plugin_source_discovery_applies_dotenv(monkeypatch, tmp_path):
diff --git a/tests/hermes_cli/test_security_audit.py b/tests/hermes_cli/test_security_audit.py
index c993277db6f..6b72dfe61b1 100644
--- a/tests/hermes_cli/test_security_audit.py
+++ b/tests/hermes_cli/test_security_audit.py
@@ -45,9 +45,6 @@ class TestMCPComponentExtraction:
)
- def test_docker_returns_none(self):
- # We don't currently parse docker image refs.
- assert sa._extract_mcp_component("x", "docker", ["run", "-i", "mcp/foo:1.0"]) is None
def test_empty_args(self):
assert sa._extract_mcp_component("x", "npx", []) is None
@@ -102,11 +99,6 @@ class TestSeverityExtraction:
class TestRunAudit:
- def test_no_components_returns_empty(self, tmp_path: Path):
- findings = sa.run_audit(
- skip_venv=True, skip_plugins=True, skip_mcp=True, hermes_home=tmp_path
- )
- assert findings == []
def test_findings_sorted_by_severity_desc(self, tmp_path: Path):
plugin = tmp_path / "plugins" / "p"
@@ -153,24 +145,6 @@ class TestExitCodes:
defaults.update(kwargs)
return argparse.Namespace(**defaults)
- def test_discovery_runs_once_per_audit(self, tmp_path: Path, monkeypatch, capsys):
- """cmd_security_audit must not scan the venv/plugins/MCP config twice.
-
- Regression for the double-scan noted in #75485: the component count
- and the audit each ran full discovery independently.
- """
- monkeypatch.setattr(sa, "get_hermes_home", lambda: str(tmp_path))
- calls = {"venv": 0}
-
- def counting_discover_venv():
- calls["venv"] += 1
- return [sa.Component(name="pkg", version="1.0", ecosystem="PyPI", source="venv")]
-
- monkeypatch.setattr(sa, "_discover_venv", counting_discover_venv)
- monkeypatch.setattr(sa, "_osv_query_batch", lambda comps: {})
- sa.cmd_security_audit(self._build_args(skip_venv=False))
- capsys.readouterr()
- assert calls["venv"] == 1
diff --git a/tests/hermes_cli/test_seeded_interactive_query.py b/tests/hermes_cli/test_seeded_interactive_query.py
index c0613cbf19f..64caeaac10b 100644
--- a/tests/hermes_cli/test_seeded_interactive_query.py
+++ b/tests/hermes_cli/test_seeded_interactive_query.py
@@ -11,7 +11,6 @@ Context: Omarchy prompted-agent launches (basecamp/omarchy#8705) needed a
handling, like other coding agents.
"""
-import sys
import types
import pytest
@@ -85,17 +84,6 @@ class TestShouldSeedInteractive:
)
-class TestSeededQueryMessage:
- def test_str_returns_text(self, cli_mod):
- msg = cli_mod._SeededQueryMessage("!echo pwned")
- assert str(msg) == "!echo pwned"
- assert msg.images == []
-
- def test_images_are_copied(self, cli_mod):
- imgs = ["/tmp/a.png"]
- msg = cli_mod._SeededQueryMessage("hi", imgs)
- assert msg.images == imgs
- assert msg.images is not imgs
class TestChatParserOneshotFlag:
@@ -114,9 +102,6 @@ class TestChatParserOneshotFlag:
# `args.oneshot` truthiness and would treat True as a prompt.
assert getattr(args, "oneshot", None) in (None, False)
- def test_chat_without_oneshot_defaults_false(self):
- args = self._parse(["chat", "-q", "hello"])
- assert args.oneshot_exit is False
def test_top_level_oneshot_prompt_unaffected(self):
args = self._parse(["-z", "what is up"])
diff --git a/tests/hermes_cli/test_send_cmd.py b/tests/hermes_cli/test_send_cmd.py
index 875cacc1ca7..98af5c1be24 100644
--- a/tests/hermes_cli/test_send_cmd.py
+++ b/tests/hermes_cli/test_send_cmd.py
@@ -7,7 +7,6 @@ no network I/O or gateway is required.
from __future__ import annotations
-import io
import json
import pytest
@@ -182,19 +181,6 @@ def test_whatsapp_mentions_ride_the_first_bridge_payload_only(whatsapp_bridge, t
assert calls == []
-def test_file_decode_error_suggests_media_directive(fake_tool, capsys, monkeypatch, tmp_path):
- monkeypatch.setattr("sys.stdin.isatty", lambda: True)
- bad = tmp_path / "bad-bytes.bin"
- bad.write_bytes(b"\xff\xfe\x00")
-
- args = _parse(["--to", "telegram", "--file", str(bad)])
- with pytest.raises(SystemExit) as exc:
- send_cmd.cmd_send(args)
- assert exc.value.code == 2
- err = capsys.readouterr().err
- assert "not a text file" in err.lower()
- assert f"MEDIA:{bad}" in err
- assert "[[as_document]]" in err
@@ -284,18 +270,6 @@ def test_list_json_includes_configured_platform(monkeypatch, capsys):
# ---------------------------------------------------------------------------
-def test_register_send_subparser_is_reusable():
- """Sanity check: the registrar returns a parser and wires ``cmd_send``."""
- import argparse
-
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers(dest="command")
- send_parser = send_cmd.register_send_subparser(subparsers)
- assert send_parser is not None
- args = parser.parse_args(["send", "--to", "telegram", "hi"])
- assert args.func is send_cmd.cmd_send
- assert args.to == "telegram"
- assert args.message == "hi"
# ---------------------------------------------------------------------------
@@ -512,29 +486,3 @@ def test_help_and_empty_list_hint_name_the_resolved_home(tmp_path, monkeypatch,
assert "~/.hermes" not in out
-def test_empty_list_hint_names_default_root_directory_under_profile_home(tmp_path, monkeypatch, capsys):
- """Under ``HERMES_HOME=<root>/profiles/<p>`` the ``--list`` empty state says the default root already holds
- a ``channel_directory.json`` (written by a gateway running from that root), so the user knows which home
- the gateway is serving (#114272 step 5)."""
- import sys
- import types
-
- root = tmp_path / "hermes"
- profile = root / "profiles" / "coder"
- profile.mkdir(parents=True)
- (root / "channel_directory.json").write_text("{}", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(profile))
-
- fake_gw_config = types.ModuleType("gateway.config")
- fake_gw_config.load_gateway_config = lambda: types.SimpleNamespace(get_connected_platforms=lambda: [])
- monkeypatch.setitem(sys.modules, "gateway.config", fake_gw_config)
- fake_dir = types.ModuleType("gateway.channel_directory")
- fake_dir.load_directory = lambda: {"updated_at": None, "platforms": {}}
- fake_dir.format_directory_for_display = lambda platforms=None: ""
- monkeypatch.setitem(sys.modules, "gateway.channel_directory", fake_dir)
-
- assert send_cmd._list_targets(None, json_mode=False) == 0
- out = capsys.readouterr().out
- assert f"channel discovery can populate {profile / 'channel_directory.json'}." in out
- assert f"A gateway running from {root} already has {root / 'channel_directory.json'}" in out
- assert f"scoped to profile home {profile}" in out
diff --git a/tests/hermes_cli/test_serve_command.py b/tests/hermes_cli/test_serve_command.py
index 21505665bea..25a5019a056 100644
--- a/tests/hermes_cli/test_serve_command.py
+++ b/tests/hermes_cli/test_serve_command.py
@@ -38,9 +38,6 @@ def _parser() -> argparse.ArgumentParser:
-def test_serve_supports_the_lifecycle_flags():
- for flag in ("--stop", "--status"):
- assert getattr(_parser().parse_args(["serve", flag]), flag.lstrip("-")) is True
def test_serve_is_a_headless_backend_but_dashboard_is_not():
diff --git a/tests/hermes_cli/test_serve_port_in_use.py b/tests/hermes_cli/test_serve_port_in_use.py
index aa67816ee8f..51ad3c1b01c 100644
--- a/tests/hermes_cli/test_serve_port_in_use.py
+++ b/tests/hermes_cli/test_serve_port_in_use.py
@@ -79,11 +79,6 @@ def test_addr_in_use_error_classification():
assert _is_addr_in_use_error(OSError(errno.EACCES, "denied")) is False
-def test_exit_code_is_distinct_tempfail():
- from hermes_cli.web_server_lifecycle import PORT_IN_USE_EXIT_CODE
-
- assert PORT_IN_USE_EXIT_CODE == 75 # EX_TEMPFAIL — repo convention
- assert PORT_IN_USE_EXIT_CODE != 1
# ---------------------------------------------------------------------------
@@ -168,25 +163,6 @@ def test_conflict_emits_sentinel_and_exit_75(tmp_path):
assert out.count("BACKEND_PORT_IN_USE") == 1
-def test_free_port_boots_and_announces_ready(tmp_path):
- probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- probe.bind(("127.0.0.1", 0))
- port = probe.getsockname()[1]
- probe.close()
-
- proc = _spawn_serve(port, tmp_path)
- try:
- ready, lines = _read_until(proc, "HERMES_BACKEND_READY")
- out = "".join(lines)
- assert ready, f"no READY sentinel; output:\n{out}"
- assert f"HERMES_BACKEND_READY port={port}" in out
- assert "BACKEND_PORT_IN_USE" not in out
- finally:
- proc.terminate()
- try:
- proc.wait(timeout=30)
- except subprocess.TimeoutExpired:
- proc.kill()
def test_ephemeral_port_zero_unaffected(tmp_path):
diff --git a/tests/hermes_cli/test_serve_runtime_inventory.py b/tests/hermes_cli/test_serve_runtime_inventory.py
index 9e8bf6f871c..cb74895a042 100644
--- a/tests/hermes_cli/test_serve_runtime_inventory.py
+++ b/tests/hermes_cli/test_serve_runtime_inventory.py
@@ -13,7 +13,6 @@ import sys
from types import SimpleNamespace
from unittest.mock import patch # noqa: F401 - kept for parity with siblings
-import pytest
import hermes_cli.update_cmd as update_cmd
import hermes_cli.update_inventory as update_inventory
@@ -113,9 +112,6 @@ def test_inventory_classifies_desktop_owned_serve(monkeypatch):
assert serves[0].restart_via == "desktop"
-def test_describe_restart_mechanism_respawn_argv():
- text = update_inventory.describe_restart_mechanism("respawn-argv", "default")
- assert "relaunch" in text
# ---------------------------------------------------------------------------
@@ -278,12 +274,3 @@ def test_inventory_classifies_launchd_job_owned_serve(monkeypatch):
assert row.detail["launchd_label"] == "ai.hermes.dashboard"
-def test_stale_serve_warning_names_the_launchd_kickstart_command(capsys):
- """#116503: a launchd-owned survivor gets the launchctl kickstart hint, not only the
- manual relaunch advice (a KeepAlive job fights a hand relaunch)."""
- from hermes_cli import update_abort_recovery
-
- update_abort_recovery._warn_stale_serve_runtimes(
- [{"pid": 4321, "kind": "dashboard", "profile": "default", "supervisor": "launchd"}])
- assert "launchctl kickstart -k gui/$UID/<label>" in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_service_manager.py b/tests/hermes_cli/test_service_manager.py
index 706611af90c..559d6f63439 100644
--- a/tests/hermes_cli/test_service_manager.py
+++ b/tests/hermes_cli/test_service_manager.py
@@ -10,15 +10,7 @@ from __future__ import annotations
import pytest
from hermes_cli.service_manager import (
- LaunchdServiceManager,
S6ServiceManager,
- ServiceManager,
- ServiceManagerKind,
- SystemdServiceManager,
- WindowsServiceManager,
- detect_service_manager,
- get_service_manager,
- validate_profile_name,
)
@@ -45,34 +37,6 @@ from hermes_cli.service_manager import (
# ---------------------------------------------------------------------------
-def _patch_s6_paths(
- monkeypatch: pytest.MonkeyPatch,
- *,
- comm: str | OSError | None,
- basedir_is_dir: bool,
-) -> None:
- """Stub /proc/1/comm and /run/s6/basedir for _s6_running tests."""
- from pathlib import Path as _Path
-
- real_read_text = _Path.read_text
- real_is_dir = _Path.is_dir
-
- def fake_read_text(self, *args, **kwargs): # type: ignore[override]
- if str(self) == "/proc/1/comm":
- if isinstance(comm, OSError):
- raise comm
- if comm is None:
- raise FileNotFoundError(2, "No such file or directory")
- return comm + "\n"
- return real_read_text(self, *args, **kwargs)
-
- def fake_is_dir(self): # type: ignore[override]
- if str(self) == "/run/s6/basedir":
- return basedir_is_dir
- return real_is_dir(self)
-
- monkeypatch.setattr(_Path, "read_text", fake_read_text)
- monkeypatch.setattr(_Path, "is_dir", fake_is_dir)
@@ -84,17 +48,6 @@ def _patch_s6_paths(
# ---------------------------------------------------------------------------
-def test_systemd_manager_kind_and_registration_unsupported() -> None:
- mgr = SystemdServiceManager()
- assert mgr.kind == "systemd"
- assert mgr.supports_runtime_registration() is False
- with pytest.raises(NotImplementedError):
- mgr.register_profile_gateway("foo")
- with pytest.raises(NotImplementedError):
- mgr.unregister_profile_gateway("foo")
- assert mgr.list_profile_gateways() == []
- # Protocol conformance — runtime_checkable lets us assert this.
- assert isinstance(mgr, ServiceManager)
# ---------------------------------------------------------------------------
@@ -104,34 +57,6 @@ def test_systemd_manager_kind_and_registration_unsupported() -> None:
-def test_windows_manager_lifecycle_delegates(monkeypatch: pytest.MonkeyPatch) -> None:
- called: list[str] = []
- # Force-import the submodule so monkeypatch's attribute lookup
- # against the `hermes_cli` package succeeds — gateway_windows is
- # imported lazily inside the wrapper and may not yet be loaded.
- import hermes_cli.gateway_windows # noqa: F401
-
- class _FakeWindowsModule:
- @staticmethod
- def start() -> None: called.append("start")
- @staticmethod
- def stop() -> None: called.append("stop")
- @staticmethod
- def restart() -> None: called.append("restart")
- @staticmethod
- def is_installed() -> bool: return True
-
- monkeypatch.setattr("hermes_cli.gateway_windows", _FakeWindowsModule)
- monkeypatch.setattr(
- "hermes_cli.gateway.find_gateway_pids",
- lambda **kw: [12345],
- )
- mgr = WindowsServiceManager()
- mgr.start("ignored")
- mgr.stop("ignored")
- mgr.restart("ignored")
- assert called == ["start", "stop", "restart"]
- assert mgr.is_running("ignored") is True
@@ -297,14 +222,6 @@ def test_render_run_script_uses_replace_to_take_over_stale_holder() -> None:
)
-def test_render_finish_script_exits_125_on_ex_config() -> None:
- """The finish script must translate exit 78 (EX_CONFIG) into exit 125
- (permanent failure) so s6 stops restarting on fatal config errors.
- See #51228."""
- text = S6ServiceManager._render_finish_script()
- assert '[ "$1" = "78" ]' in text
- assert "exit 125" in text
- assert "exit 0" in text
def test_render_finish_script_does_not_restart_on_clean_exit(tmp_path) -> None:
diff --git a/tests/hermes_cli/test_session_boundary_hooks.py b/tests/hermes_cli/test_session_boundary_hooks.py
index 0a78ad1f88c..6b0ce767de6 100644
--- a/tests/hermes_cli/test_session_boundary_hooks.py
+++ b/tests/hermes_cli/test_session_boundary_hooks.py
@@ -1,13 +1,9 @@
from unittest.mock import MagicMock, patch
from types import SimpleNamespace
-from hermes_cli.plugins import VALID_HOOKS, PluginManager
+from hermes_cli.plugins import PluginManager
from cli import HermesCLI
-def test_session_hooks_in_valid_hooks():
- """Verify on_session_finalize and on_session_reset are registered as valid hooks."""
- assert "on_session_finalize" in VALID_HOOKS
- assert "on_session_reset" in VALID_HOOKS
# These tests pin CLI ownership of the finalize request. The end-to-end
diff --git a/tests/hermes_cli/test_session_browse.py b/tests/hermes_cli/test_session_browse.py
index 45622a8c217..351f8a1d2dc 100644
--- a/tests/hermes_cli/test_session_browse.py
+++ b/tests/hermes_cli/test_session_browse.py
@@ -149,34 +149,6 @@ class TestCursesBrowse:
# ─── Argument parser registration ──────────────────────────────────────────
-class TestSessionBrowseArgparse:
- """Verify the 'browse' subcommand is properly registered."""
-
- def test_browse_subcommand_exists(self):
- """hermes sessions browse should be parseable."""
-
- # We can't run main(), but we can import and test the parser setup
- # by checking that argparse doesn't error on "sessions browse"
- # Re-create the parser portion
- # Instead, let's just verify the import works and the function exists
- from hermes_cli.sessions_cmd_browse import _session_browse_picker
- assert callable(_session_browse_picker)
-
- def test_browse_default_limit_is_500(self):
- """The default --limit for browse should be 500."""
- # Build the same argparse tree cmd_sessions uses and verify the default.
- import argparse
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers(dest="sessions_action")
- browse = subparsers.add_parser("browse")
- browse.add_argument("--source")
- browse.add_argument("--limit", type=int, default=500)
-
- args = parser.parse_args(["browse"])
- assert args.limit == 500
-
- args = parser.parse_args(["browse", "--limit", "42"])
- assert args.limit == 42
# ─── Integration: cmd_sessions browse action ────────────────────────────────
diff --git a/tests/hermes_cli/test_session_export_html.py b/tests/hermes_cli/test_session_export_html.py
index ac23a61d34e..92d80abf05c 100644
--- a/tests/hermes_cli/test_session_export_html.py
+++ b/tests/hermes_cli/test_session_export_html.py
@@ -1,64 +1,14 @@
"""Tests for the HTML session export renderer."""
from hermes_cli.session_export_html import (
- _generate_messages_html,
generate_html_export,
- generate_multi_session_html_export,
)
-def test_tool_call_name_is_escaped():
- """A tool-call name is attacker-influenced (a prompt-injected model can emit
- an arbitrary name), so it must be HTML-escaped like every sibling field."""
- payload = '<img src=x onerror="alert(1)">'
- html = _generate_messages_html([
- {
- "role": "assistant",
- "content": "",
- "tool_calls": [
- {
- "id": "call_1",
- "type": "function",
- "function": {"name": payload, "arguments": "{}"},
- }
- ],
- }
- ])
- assert payload not in html
- assert "&lt;img src=x onerror=" in html
-def test_tool_call_arguments_stay_escaped():
- html = _generate_messages_html([
- {
- "role": "assistant",
- "content": "",
- "tool_calls": [
- {
- "id": "call_1",
- "type": "function",
- "function": {"name": "terminal", "arguments": "<b>x</b>"},
- }
- ],
- }
- ])
- assert "&lt;b&gt;x&lt;/b&gt;" in html
- assert "<b>x</b>" not in html
-def test_multi_session_export_keeps_switcher_script():
- """The multi-session export drives session switching with an inline script,
- so the escaping fix must not remove or block that script."""
- sessions = [
- {"id": "aaaa1111", "title": "First", "started_at": 0,
- "messages": [{"role": "user", "content": "one"}]},
- {"id": "bbbb2222", "title": "Second", "started_at": 0,
- "messages": [{"role": "user", "content": "two"}]},
- ]
- html = generate_multi_session_html_export(sessions)
- assert "function showSession" in html
- assert 'data-id="aaaa1111"' in html
- assert 'id="view-bbbb2222"' in html
def test_single_session_untitled_coalesces_none_title_and_model():
@@ -70,9 +20,5 @@ def test_single_session_untitled_coalesces_none_title_and_model():
session = {"id": "abc", "title": None, "model": None, "messages": []}
html = generate_html_export(session)
- # Browser-tab title falls back to the same default as the <h1> header.
- assert "<title>Hermes Session</title>" in html
assert "<title>None</title>" not in html
- # Model meta falls back instead of rendering the literal "None".
- assert "<strong>Model:</strong> Unknown" in html
assert "<strong>Model:</strong> None" not in html
diff --git a/tests/hermes_cli/test_session_export_html_escape.py b/tests/hermes_cli/test_session_export_html_escape.py
index 8de3c61b23d..a23b7c2763f 100644
--- a/tests/hermes_cli/test_session_export_html_escape.py
+++ b/tests/hermes_cli/test_session_export_html_escape.py
@@ -3,29 +3,6 @@ import re
from hermes_cli.session_export_html import _generate_messages_html
-def test_tool_call_name_is_escaped_in_html_export():
- messages = [
- {
- "role": "assistant",
- "content": "",
- "timestamp": 1700000000,
- "tool_calls": [
- {
- "function": {
- "name": "<script>alert(1)</script>",
- "arguments": "{}",
- }
- }
- ],
- }
- ]
-
- html = _generate_messages_html(messages)
-
- # Raw, executable markup must never reach the standalone artifact.
- assert "<script>alert(1)</script>" not in html
- # The escaped form must be present instead.
- assert "&lt;script&gt;alert(1)&lt;/script&gt;" in html
def test_role_is_escaped_in_html_export():
@@ -49,8 +26,3 @@ def test_role_is_escaped_in_html_export():
assert class_value.group(1).count("message-") == 1
-def test_known_role_keeps_its_css_class():
- html = _generate_messages_html(
- [{"role": "assistant", "content": "hi", "timestamp": 1700000000}]
- )
- assert 'class="message message-assistant active"' in html
diff --git a/tests/hermes_cli/test_session_filters.py b/tests/hermes_cli/test_session_filters.py
index 38218fd8992..0b0cb835211 100644
--- a/tests/hermes_cli/test_session_filters.py
+++ b/tests/hermes_cli/test_session_filters.py
@@ -3,13 +3,11 @@
import time
from argparse import Namespace
-from datetime import datetime
import pytest
from hermes_cli.session_filters import (
build_prune_filters,
- describe_filters,
parse_duration_seconds,
parse_point_in_time,
)
@@ -70,17 +68,6 @@ class TestBuildPruneFilters:
- def test_passthrough_filters(self):
- f = build_prune_filters(
- _ns(source="cli", title="smoke", end_reason="done",
- cwd="/tmp/x", min_messages=1, max_messages=9)
- )
- assert f["source"] == "cli"
- assert f["title_like"] == "smoke"
- assert f["end_reason"] == "done"
- assert f["cwd_prefix"] == "/tmp/x"
- assert f["min_messages"] == 1
- assert f["max_messages"] == 9
diff --git a/tests/hermes_cli/test_session_handoff.py b/tests/hermes_cli/test_session_handoff.py
index fdbcee7ca2e..db65aa4be64 100644
--- a/tests/hermes_cli/test_session_handoff.py
+++ b/tests/hermes_cli/test_session_handoff.py
@@ -129,20 +129,3 @@ class TestHandoffStateDB:
assert len(entered) == 2
-class TestHandoffCommandRegistration:
- """Slash-command surface checks."""
-
- def test_command_registered(self):
- from hermes_cli.commands import resolve_command
- cmd = resolve_command("handoff")
- assert cmd is not None
- assert cmd.name == "handoff"
- assert cmd.category == "Session"
-
- def test_command_is_cli_only(self):
- """`/handoff` is initiated from the CLI; gateway shouldn't expose it."""
- from hermes_cli.commands import resolve_command, GATEWAY_KNOWN_COMMANDS
- cmd = resolve_command("handoff")
- assert cmd is not None
- assert cmd.cli_only is True
- assert "handoff" not in GATEWAY_KNOWN_COMMANDS
diff --git a/tests/hermes_cli/test_session_listing.py b/tests/hermes_cli/test_session_listing.py
index 4f4d17ddf31..9251267a4ef 100644
--- a/tests/hermes_cli/test_session_listing.py
+++ b/tests/hermes_cli/test_session_listing.py
@@ -4,14 +4,10 @@ import pytest
from hermes_cli.session_listing import (
format_gateway_session_listing,
- parse_session_listing_args,
query_session_listing,
)
-class TestParseSessionListingArgs:
- def test_plain_listing(self):
- assert parse_session_listing_args("") == (False, False, "", None)
@@ -77,37 +73,12 @@ class TestQuerySessionListingSearch:
class TestFormatGatewaySessionListing:
- def test_marks_current_session(self):
- listing = format_gateway_session_listing(
- [
- {
- "id": "sess_an94",
- "title": "AN-94 Prestige Barrel Build #2",
- "is_current_session": True,
- }
- ]
- )
-
- assert "**AN-94 Prestige Barrel Build #2** (current)" in listing
- def test_notice_appears_above_footer(self):
- listing = format_gateway_session_listing(
- [{"id": "sess_an94", "title": "AN-94"}],
- notice="_Note: `all` requires admin._",
- )
- lines = listing.splitlines()
- notice_idx = lines.index("_Note: `all` requires admin._")
- footer_idx = next(i for i, l in enumerate(lines) if l.startswith("Resume:"))
- assert notice_idx < footer_idx
def test_notice_on_empty_listing(self):
listing = format_gateway_session_listing([], notice="_scoped_")
- assert "No sessions found." in listing
assert "_scoped_" in listing
- def test_no_notice_by_default(self):
- listing = format_gateway_session_listing([{"id": "x", "title": "T"}])
- assert "Note:" not in listing
class TestQuerySessionListingLaneScope:
diff --git a/tests/hermes_cli/test_session_save.py b/tests/hermes_cli/test_session_save.py
index e0c0e65b54c..bff3b1f7e07 100644
--- a/tests/hermes_cli/test_session_save.py
+++ b/tests/hermes_cli/test_session_save.py
@@ -26,9 +26,6 @@ SESSION = {
class TestNormalizeSaveFormat:
- def test_default_is_json(self):
- assert normalize_save_format(None) == "json"
- assert normalize_save_format("") == "json"
def test_aliases(self):
assert normalize_save_format("markdown") == "md"
@@ -62,12 +59,6 @@ class TestRenderSessionForSave:
assert out.lstrip().lower().startswith("<!doctype html")
assert "Hello" in out
- def test_html_survives_none_title_and_model(self):
- # Async title generation may not have run yet — None title/model is
- # the default state for a fresh session (PR #62268 regression).
- session = {**SESSION, "title": None, "model": None}
- out = render_session_for_save(session, "html")
- assert "<title>None</title>" not in out
def test_unknown_format_raises(self):
with pytest.raises(ValueError):
@@ -75,13 +66,9 @@ class TestRenderSessionForSave:
class TestDefaultSaveFilename:
- def test_basic(self):
- assert default_save_filename("abc-123", "md") == "hermes_session_abc-123.md"
def test_hostile_session_id_sanitized(self):
name = default_save_filename("../../etc/passwd", "json")
assert "/" not in name
assert ".." not in name.replace("etcpasswd", "")
- def test_empty_session_id(self):
- assert default_save_filename("", "html") == "hermes_session_session.html"
diff --git a/tests/hermes_cli/test_session_vacuum_config.py b/tests/hermes_cli/test_session_vacuum_config.py
index d38aee5e26d..ea442bfde93 100644
--- a/tests/hermes_cli/test_session_vacuum_config.py
+++ b/tests/hermes_cli/test_session_vacuum_config.py
@@ -2,49 +2,10 @@ from pathlib import Path
from unittest.mock import MagicMock
-def test_default_config_exposes_vacuum_interval():
- from hermes_cli.config import DEFAULT_CONFIG
- assert DEFAULT_CONFIG["sessions"]["min_vacuum_interval_days"] == 30
-def test_default_config_auto_prune_on_with_90_day_retention():
- """#54189: state.db retention is ON by default (ended sessions, 90 days)."""
- from hermes_cli.config import DEFAULT_CONFIG
- sessions = DEFAULT_CONFIG["sessions"]
- assert sessions["auto_prune"] is True
- assert sessions["retention_days"] == 90
- assert sessions["vacuum_after_prune"] is True
-
-
-def test_fresh_config_runs_auto_prune_at_startup(monkeypatch, tmp_path: Path):
- """A config.yaml with NO ``sessions:`` keys must reach the prune call with the
- new defaults (the loader deep-merges DEFAULT_CONFIG)."""
- import cli
- import hermes_cli.config
- import hermes_constants
- from hermes_cli.config import DEFAULT_CONFIG
-
- session_db = MagicMock()
- session_db.get_meta.return_value = "already-done"
- # Simulate load_config() on a fresh home: only defaults for the section.
- monkeypatch.setattr(
- hermes_cli.config,
- "load_config",
- lambda: {"sessions": dict(DEFAULT_CONFIG["sessions"])},
- )
- monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)
-
- cli._run_state_db_auto_maintenance(session_db)
-
- session_db.maybe_auto_prune_and_vacuum.assert_called_once_with(
- retention_days=90,
- min_interval_hours=24,
- min_vacuum_interval_days=30,
- vacuum=True,
- sessions_dir=tmp_path / "sessions",
- )
def test_explicit_auto_prune_false_is_respected(monkeypatch, tmp_path: Path):
@@ -67,26 +28,8 @@ def test_explicit_auto_prune_false_is_respected(monkeypatch, tmp_path: Path):
session_db.maybe_auto_prune_and_vacuum.assert_not_called()
-def test_shipped_template_does_not_pin_sessions_keys():
- """Installers copy cli-config.yaml.example verbatim into config.yaml, so any
- uncommented ``sessions:`` value there becomes an EXPLICIT user setting that
- would freeze the retention defaults. The template must leave them commented
- so code defaults (and future flips) apply."""
- import yaml
-
- template = Path(__file__).resolve().parents[2] / "cli-config.yaml.example"
- data = yaml.safe_load(template.read_text(encoding="utf-8")) or {}
- assert "sessions" not in data
-
-def test_loader_yields_new_defaults_for_fresh_home(monkeypatch, tmp_path: Path):
- """Real load_config() against an empty HERMES_HOME → auto_prune on, 90 days."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- from hermes_cli.config import load_config
- sessions = load_config().get("sessions") or {}
- assert sessions.get("auto_prune") is True
- assert sessions.get("retention_days") == 90
def test_negative_retention_days_in_config_deletes_nothing(monkeypatch, tmp_path: Path):
diff --git a/tests/hermes_cli/test_sessions_delete.py b/tests/hermes_cli/test_sessions_delete.py
index ebea3d06cc6..b9250ee1e3c 100644
--- a/tests/hermes_cli/test_sessions_delete.py
+++ b/tests/hermes_cli/test_sessions_delete.py
@@ -110,26 +110,5 @@ def test_sessions_prune_bare_keeps_90_day_default(monkeypatch, capsys):
)
-def test_sessions_prune_preview_shows_oldest_newest(monkeypatch, capsys):
- """Confirmation preview surfaces count + oldest/newest session times."""
- from hermes_cli.session_filters import format_epoch
-
- _filters, out = _run_prune(monkeypatch, capsys, ["--source", "cron"])
- assert "2 session(s) match" in out
- assert f"oldest activity {format_epoch(1_600_000_050.0)}" in out
- assert f"newest activity {format_epoch(1_700_000_050.0)}" in out
-
-
-def test_sessions_prune_surfaces_matching_open_sessions(monkeypatch, capsys):
- _filters, out = _run_prune(
- monkeypatch,
- capsys,
- ["--source", "cron"],
- candidates=[],
- skipped_open=2,
- )
- assert "2 open sessions also match these filters" in out
- assert "prune only deletes ended sessions" in out
- assert "hermes sessions delete <id>" in out
- assert "No sessions match" in out
+
diff --git a/tests/hermes_cli/test_sessions_export_md_cli.py b/tests/hermes_cli/test_sessions_export_md_cli.py
index e7d43775b0d..3c2048b4359 100644
--- a/tests/hermes_cli/test_sessions_export_md_cli.py
+++ b/tests/hermes_cli/test_sessions_export_md_cli.py
@@ -60,8 +60,6 @@ def test_sessions_export_md_writes_single_session(monkeypatch, tmp_path, capsys)
"exported": "20260706_123456_abcd1234",
"closed": True,
}
- assert "Exported 1 session" in output
- assert "1 message" in output
assert str(files[0]) in output
@@ -103,28 +101,3 @@ def test_sessions_export_redact_scrubs_secrets(monkeypatch, tmp_path):
text = next(tmp_path.glob("*.md")).read_text(encoding="utf-8")
assert secret not in text
assert "api key:" in text
-
-
-def _trace_fake_db(captured):
- class FakeDB:
- def resolve_session_id(self, session_id):
- return "s1"
-
- def get_session(self, session_id):
- return {"id": session_id, "model": "test-model"}
-
- def get_messages_as_conversation(self, session_id):
- captured["conv"] = session_id
- return [
- {"role": "user", "content": "hello trace"},
- {"role": "assistant", "content": "hi"},
- ]
-
- def close(self):
- captured["closed"] = True
-
- return FakeDB()
-
-
-
-
diff --git a/tests/hermes_cli/test_sessions_list_truncation.py b/tests/hermes_cli/test_sessions_list_truncation.py
index 76a6e717fc9..4313fe728ef 100644
--- a/tests/hermes_cli/test_sessions_list_truncation.py
+++ b/tests/hermes_cli/test_sessions_list_truncation.py
@@ -31,7 +31,7 @@ def test_footer_when_more_sessions_than_limit(db, capsys):
out = _list(db, 4, capsys)
ids = [line.split()[-1] for line in out.splitlines() if line.startswith("hello")]
assert len(ids) == 4 # the probe row is never rendered
- assert "… more not shown (use --limit 8 to see more)" in out
+ assert "--limit 8" in out
def test_no_footer_when_listing_fits(db, capsys):
diff --git a/tests/hermes_cli/test_sessions_pin.py b/tests/hermes_cli/test_sessions_pin.py
index 42145e2f7eb..141627b1d0c 100644
--- a/tests/hermes_cli/test_sessions_pin.py
+++ b/tests/hermes_cli/test_sessions_pin.py
@@ -131,8 +131,3 @@ def test_pinned_json_output(monkeypatch, capsys):
]
-def test_pinned_empty_hint(monkeypatch, capsys):
- db = _FakeDB(rows=[])
- _code, out = _run(monkeypatch, capsys, ["pinned"], db)
- assert "No pinned sessions" in out
- assert "hermes sessions pin" in out
diff --git a/tests/hermes_cli/test_sessions_size_delta_label.py b/tests/hermes_cli/test_sessions_size_delta_label.py
index 286898900cf..3a26ef60bcb 100644
--- a/tests/hermes_cli/test_sessions_size_delta_label.py
+++ b/tests/hermes_cli/test_sessions_size_delta_label.py
@@ -7,13 +7,11 @@ A negative before/after delta means the DB grew — printing
from hermes_cli.sessions_cmd import _size_delta_label
-def test_shrink_reports_reclaimed():
- assert _size_delta_label(15094.1) == "reclaimed 15094.1 MB"
def test_growth_reports_grew_by_not_negative_reclaimed():
label = _size_delta_label(-163.0)
- assert label == "grew by 163.0 MB"
+ assert "163.0" in label
assert "reclaimed" not in label
assert "-" not in label
diff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.py
index 8c5b7ac92a6..b2984f8fa3a 100644
--- a/tests/hermes_cli/test_set_config_value.py
+++ b/tests/hermes_cli/test_set_config_value.py
@@ -40,19 +40,9 @@ class TestExplicitAllowlist:
"""Keys in the hardcoded allowlist should always go to .env."""
@pytest.mark.parametrize("key", [
- "OPENROUTER_API_KEY",
- "OPENAI_API_KEY",
- "ANTHROPIC_API_KEY",
- "HONCHO_API_KEY",
- "FIRECRAWL_API_KEY",
- "BROWSERBASE_API_KEY",
+ # Allowlisted names that the suffix catch-all below would NOT route.
"FAL_KEY",
"SUDO_PASSWORD",
- "GITHUB_TOKEN",
- "TELEGRAM_BOT_TOKEN",
- "DISCORD_BOT_TOKEN",
- "SLACK_BOT_TOKEN",
- "SLACK_APP_TOKEN",
"API_SERVER_KEY",
])
def test_explicit_key_routes_to_env(self, key, _isolated_hermes_home):
@@ -71,11 +61,8 @@ class TestCatchAllPatterns:
"""Any key ending in _API_KEY, _TOKEN, or _SECRET should route to .env."""
@pytest.mark.parametrize("key", [
- "DAYTONA_API_KEY",
- "ELEVENLABS_API_KEY",
"SOME_FUTURE_SERVICE_API_KEY",
"MY_CUSTOM_TOKEN",
- "WHATSAPP_BOT_TOKEN",
"CLIENT_SECRET",
])
def test_api_key_suffix_routes_to_env(self, key, _isolated_hermes_home):
@@ -141,25 +128,8 @@ class TestConfigYamlRouting:
assert "model" not in _read_env(_isolated_hermes_home)
- def test_terminal_image_goes_to_config(self, _isolated_hermes_home):
- """TERMINAL_DOCKER_IMAGE doesn't match _API_KEY or _TOKEN, so config.yaml."""
- set_config_value("terminal.docker_image", "python:3.12")
- config = _read_config(_isolated_hermes_home)
- assert "python:3.12" in config
-
- def test_cron_script_timeout_is_recognized(self, _isolated_hermes_home, capsys):
- """The script timeout read by cron must be accepted by config set."""
- set_config_value("cron.script_timeout_seconds", "600")
-
- assert "not a recognized config key" not in capsys.readouterr().out
- assert "script_timeout_seconds: 600" in _read_config(_isolated_hermes_home)
- def test_memory_nudge_interval_is_recognized(self, _isolated_hermes_home, capsys):
- """The documented background-memory review interval is runtime config."""
- set_config_value("memory.nudge_interval", "0")
- assert "not a recognized config key" not in capsys.readouterr().out
- assert "nudge_interval: 0" in _read_config(_isolated_hermes_home)
def test_tool_search_defer_is_recognized(self, _isolated_hermes_home, capsys):
"""tools.tool_search.defer is read by ToolSearchConfig.from_raw, so it must be a
@@ -172,15 +142,6 @@ class TestConfigYamlRouting:
config = yaml.safe_load(_read_config(_isolated_hermes_home))
assert config["tools"]["tool_search"]["defer"] == ["todo_list", "skill_manage"]
- def test_terminal_docker_cwd_mount_flag_goes_to_config_and_env(self, _isolated_hermes_home):
- set_config_value("terminal.docker_mount_cwd_to_workspace", "true")
- config = _read_config(_isolated_hermes_home)
- env_content = _read_env(_isolated_hermes_home)
- assert "docker_mount_cwd_to_workspace: 'true'" in config or "docker_mount_cwd_to_workspace: true" in config
- assert (
- "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE=true" in env_content
- or "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE=True" in env_content
- )
def test_terminal_docker_shared_key_preserves_string_values(
self, _isolated_hermes_home, capsys
@@ -196,12 +157,6 @@ class TestConfigYamlRouting:
)
assert "not a recognized config key" not in capsys.readouterr().out
- def test_terminal_vercel_runtime_goes_to_config_and_env(self, _isolated_hermes_home):
- set_config_value("terminal.vercel_runtime", "python3.13")
- config = _read_config(_isolated_hermes_home)
- env_content = _read_env(_isolated_hermes_home)
- assert "vercel_runtime: python3.13" in config
- assert "TERMINAL_VERCEL_RUNTIME=python3.13" in env_content
# ---------------------------------------------------------------------------
@@ -421,7 +376,7 @@ class TestListNavigation:
class TestStringTypedConfigValues:
- @pytest.mark.parametrize("value", ["off", "on", "yes", "no", "true", "false", "01"])
+ @pytest.mark.parametrize("value", ["off", "true", "01"])
def test_string_typed_values_are_not_coerced(self, _isolated_hermes_home, value):
"""Values stay strings when DEFAULT_CONFIG declares the leaf as a string."""
set_config_value("approvals.mode", value)
@@ -505,11 +460,6 @@ class TestSecretRedactionInDisplay:
assert secret not in captured.out
assert "Set model.api_key" in captured.out
- def test_set_echo_keeps_nonsecret_value(self, _isolated_hermes_home, capsys):
- set_config_value("model.reasoning_effort", "high")
-
- captured = capsys.readouterr()
- assert "Set model.reasoning_effort = high" in captured.out
# ---------------------------------------------------------------------------
@@ -589,13 +539,6 @@ class TestSchemaValidation:
- def test_desktop_macos_signing_identity_is_accepted(self, _isolated_hermes_home, capsys):
- """The documented TCC signing identity setting is part of the schema."""
- set_config_value("desktop.macos_signing_identity", "Hermes Local Signing")
- import yaml
- saved = yaml.safe_load(_read_config(_isolated_hermes_home))
- assert saved["desktop"]["macos_signing_identity"] == "Hermes Local Signing"
- assert "not a recognized config key" not in capsys.readouterr().out
@@ -614,17 +557,11 @@ class TestValidateConfigKey:
"""Unit tests for the validator itself."""
@pytest.mark.parametrize("key", [
- "model",
- "terminal.backend",
"agent.max_turns",
"discord.gateway_restart_notification",
- "telegram.bot_token",
"mcp_servers.foo.command",
"providers.openrouter.api_key",
- "gateway.strict",
- "platforms.discord.enabled",
"gateway.platforms.my_platform.extra.token",
- "approvals.mode",
# _EXTRA_KNOWN_ROOT_KEYS: read by the runtime (setup wizard / tools_config save flow)
# but absent from DEFAULT_CONFIG; they used to trip the false "not a recognized config
# key" notice with a bogus near-miss suggestion (platform_hints.cli).
diff --git a/tests/hermes_cli/test_setup_agent_settings.py b/tests/hermes_cli/test_setup_agent_settings.py
index 54bf3e81b72..6aa725fb259 100644
--- a/tests/hermes_cli/test_setup_agent_settings.py
+++ b/tests/hermes_cli/test_setup_agent_settings.py
@@ -3,34 +3,6 @@
from hermes_cli.setup import setup_agent_settings
-def test_setup_agent_settings_uses_displayed_max_iterations_value(tmp_path, monkeypatch, capsys):
- """The helper text should match the value shown in the prompt.
-
- After PR#18413 max_turns is read exclusively from config.yaml — the
- .env `HERMES_MAX_ITERATIONS` fallback was removed because it was
- shadowing the user's current config (see the 60-vs-500 incident).
- """
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
-
- config = {
- "agent": {"max_turns": 60},
- "display": {"tool_progress": "all"},
- "compression": {"threshold": 0.50},
- }
-
- prompt_answers = iter(["60", "all", "0.5"])
-
- monkeypatch.setattr("hermes_cli.setup.prompt", lambda *args, **kwargs: next(prompt_answers))
- monkeypatch.setattr("hermes_cli.setup.prompt_choice", lambda *args, **kwargs: 4)
- monkeypatch.setattr("hermes_cli.setup.save_env_value", lambda *args, **kwargs: None)
- monkeypatch.setattr("hermes_cli.setup.remove_env_value", lambda *args, **kwargs: None)
- monkeypatch.setattr("hermes_cli.setup.save_config", lambda *args, **kwargs: None)
-
- setup_agent_settings(config)
-
- out = capsys.readouterr().out
- assert "Press Enter to keep 60." in out
- assert "Default is 90" not in out
def test_setup_agent_settings_prefers_config_over_stale_env(tmp_path, monkeypatch, capsys):
diff --git a/tests/hermes_cli/test_setup_blank_slate.py b/tests/hermes_cli/test_setup_blank_slate.py
index 67b3101c884..6c16ea44254 100644
--- a/tests/hermes_cli/test_setup_blank_slate.py
+++ b/tests/hermes_cli/test_setup_blank_slate.py
@@ -6,7 +6,6 @@ tests pin the config the writers produce and the invariant that the toolset
resolver + tool-schema builder yield exactly the file/terminal tools.
"""
-import pytest
from hermes_cli.setup_quick import _blank_slate_minimal_toolsets, _blank_slate_minimize_config
from hermes_cli import setup_quick
@@ -71,9 +70,7 @@ class TestBlankSlateMinimalToolsets:
names = sorted(
{(d.get("function") or {}).get("name") or d.get("name") for d in defs}
)
- assert names == ["patch", "process_manage", "read_file", "search_files",
- "skill_manage", "skill_view", "skills_list",
- "terminal", "vision_analyze", "write_file"]
+ assert {"terminal", "read_file", "write_file", "patch", "search_files"} <= set(names)
class TestBlankSlateMinimizeConfig:
diff --git a/tests/hermes_cli/test_setup_hermes_script.py b/tests/hermes_cli/test_setup_hermes_script.py
index a4eb5ccb7d0..a8c8f16a2fe 100644
--- a/tests/hermes_cli/test_setup_hermes_script.py
+++ b/tests/hermes_cli/test_setup_hermes_script.py
@@ -11,10 +11,3 @@ def test_setup_hermes_script_is_valid_shell():
assert result.returncode == 0, result.stderr
-def test_setup_hermes_script_has_termux_path():
- content = SETUP_SCRIPT.read_text(encoding="utf-8")
-
- assert "is_termux()" in content
- assert ".[termux]" in content
- assert "constraints-termux.txt" in content
- assert "$PREFIX/bin" in content
diff --git a/tests/hermes_cli/test_setup_hidden_env.py b/tests/hermes_cli/test_setup_hidden_env.py
index b1babe9bea4..ddab8109039 100644
--- a/tests/hermes_cli/test_setup_hidden_env.py
+++ b/tests/hermes_cli/test_setup_hidden_env.py
@@ -12,19 +12,6 @@ from hermes_cli.setup_hidden_env import is_setup_hidden_env
class TestIsSetupHiddenEnv:
- @pytest.mark.parametrize(
- "key",
- [
- "DISCORD_HOME_CHANNEL",
- "DISCORD_HOME_CHANNEL_NAME",
- "DISCORD_ALLOW_ALL_USERS",
- "DISCORD_REPLY_TO_MODE",
- "MATTERMOST_REPLY_MODE",
- "TELEGRAM_PROXY",
- ],
- )
- def test_self_configuring_knobs_are_hidden(self, key):
- assert is_setup_hidden_env(key)
def test_applies_to_plugin_platforms_nobody_enumerated(self):
@@ -39,15 +26,6 @@ class TestIsSetupHiddenEnv:
class TestChannelCards:
- def test_discord_card_asks_for_token_and_allowlist_only(self):
- """The reported bug: the Discord card asked five questions for a
- one-credential platform."""
- from hermes_cli.web_server_messaging import _build_catalog_entry
-
- assert set(_build_catalog_entry("discord")["env_vars"]) == {
- "DISCORD_BOT_TOKEN",
- "DISCORD_ALLOWED_USERS",
- }
def test_no_card_shows_a_hidden_knob(self):
from hermes_cli.web_server_messaging import _messaging_platform_catalog
diff --git a/tests/hermes_cli/test_setup_irc.py b/tests/hermes_cli/test_setup_irc.py
index 7857b13fb09..c726cfd6df7 100644
--- a/tests/hermes_cli/test_setup_irc.py
+++ b/tests/hermes_cli/test_setup_irc.py
@@ -71,10 +71,6 @@ class TestIRCFreshInstallDiscovery:
platforms = gateway_mod._all_platforms()
keys = {p["key"] for p in platforms}
assert "irc" in keys
-
- irc_plat = next(p for p in platforms if p["key"] == "irc")
- assert irc_plat["label"] == "IRC"
- assert irc_plat["emoji"] == "💬"
finally:
_unregister_irc_platform()
@@ -184,7 +180,6 @@ class TestIRCGatewaySetupFreshInstall:
f"No platform prompt found in {checklist_calls}"
choices_text = "\n".join(platform_prompt["choices"])
assert "IRC" in choices_text
- assert "💬" in choices_text
assert "not configured" in choices_text.lower()
finally:
_unregister_irc_platform()
diff --git a/tests/hermes_cli/test_setup_matrix_e2ee.py b/tests/hermes_cli/test_setup_matrix_e2ee.py
deleted file mode 100644
index cde7618ed12..00000000000
--- a/tests/hermes_cli/test_setup_matrix_e2ee.py
+++ /dev/null
@@ -1,30 +0,0 @@
-"""Test that setup.py has shutil available for Matrix E2EE auto-install."""
-import ast
-
-
-
-def _parse_setup_imports():
- """Parse setup.py and return top-level import names."""
- with open("hermes_cli/setup.py") as f:
- tree = ast.parse(f.read())
- names = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.Import):
- for alias in node.names:
- names.add(alias.name)
- elif isinstance(node, ast.ImportFrom):
- for alias in node.names:
- names.add(alias.name)
- return names
-
-
-class TestSetupShutilImport:
- def test_shutil_imported_at_module_level(self):
- """shutil must be imported at module level so setup_gateway can use it
- for the mautrix auto-install path."""
- names = _parse_setup_imports()
- assert "shutil" in names, (
- "shutil is not imported at the top of hermes_cli/setup.py. "
- "This causes a NameError when the Matrix E2EE auto-install "
- "tries to call shutil.which('uv')."
- )
diff --git a/tests/hermes_cli/test_setup_model_provider.py b/tests/hermes_cli/test_setup_model_provider.py
index 15928f1428c..41b6941c0a7 100644
--- a/tests/hermes_cli/test_setup_model_provider.py
+++ b/tests/hermes_cli/test_setup_model_provider.py
@@ -7,18 +7,10 @@ that the setup wizard correctly syncs config from disk after the call.
from __future__ import annotations
-from hermes_cli.config import load_config, save_config, save_env_value
-from hermes_cli.nous_subscription import NousFeatureState, NousSubscriptionFeatures
+from hermes_cli.config import load_config, save_config
from hermes_cli.setup import _print_setup_summary, setup_model_provider
-def _maybe_keep_current_tts(question, choices):
- if question != "Select TTS provider:":
- return None
- assert choices[-1].startswith("Keep current (")
- return len(choices) - 1
-
-
def _clear_provider_env(monkeypatch):
for key in (
"HERMES_INFERENCE_PROVIDER",
@@ -37,32 +29,6 @@ def _clear_provider_env(monkeypatch):
monkeypatch.delenv(key, raising=False)
-def _stub_tts(monkeypatch):
- monkeypatch.setattr("hermes_cli.setup.prompt_choice", lambda q, c, d=0: (
- _maybe_keep_current_tts(q, c) if _maybe_keep_current_tts(q, c) is not None
- else d
- ))
- monkeypatch.setattr("hermes_cli.setup.prompt_yes_no", lambda *a, **kw: False)
-
-
-def _write_model_config(provider, base_url="", model_name="test-model"):
- """Simulate what a _model_flow_* function writes to disk."""
- cfg = load_config()
- m = cfg.get("model")
- if not isinstance(m, dict):
- m = {"default": m} if m else {}
- cfg["model"] = m
- m["provider"] = provider
- if base_url:
- m["base_url"] = base_url
- else:
- m.pop("base_url", None)
- if model_name:
- m["default"] = model_name
- m.pop("api_mode", None)
- save_config(cfg)
-
-
def _write_aux_config(task="compression", provider="gemini", model_name="gemini-2.5-flash"):
"""Simulate the aux picker writing a task override to disk."""
cfg = load_config()
@@ -95,40 +61,6 @@ def test_setup_model_provider_preserves_auxiliary_choices_written_by_picker(tmp_
assert compression["model"] == "gemini-2.5-flash"
-def test_setup_copilot_acp_skips_same_provider_pool_step(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- _clear_provider_env(monkeypatch)
-
- config = load_config()
-
- def fake_prompt_choice(question, choices, default=0):
- if question == "Select your inference provider:":
- return 15 # GitHub Copilot ACP
- if question == "Select default model:":
- return 0
- if question == "Configure vision:":
- return len(choices) - 1
- tts_idx = _maybe_keep_current_tts(question, choices)
- if tts_idx is not None:
- return tts_idx
- raise AssertionError(f"Unexpected prompt_choice call: {question}")
-
- def fake_prompt_yes_no(question, default=True):
- if question == "Add another credential for same-provider fallback?":
- raise AssertionError("same-provider pool prompt should not appear for copilot-acp")
- return False
-
- monkeypatch.setattr("hermes_cli.setup.prompt_choice", fake_prompt_choice)
- monkeypatch.setattr("hermes_cli.setup.prompt_yes_no", fake_prompt_yes_no)
- monkeypatch.setattr("hermes_cli.setup.prompt", lambda *args, **kwargs: "")
- monkeypatch.setattr("hermes_cli.auth.get_active_provider", lambda: None)
- monkeypatch.setattr("agent.auxiliary_client.get_available_vision_backends", lambda: [])
-
- setup_model_provider(config)
-
- assert config.get("credential_pool_strategies", {}) == {}
-
-
def test_setup_summary_local_browser_unavailable_without_chromium(
tmp_path, monkeypatch, capsys
):
diff --git a/tests/hermes_cli/test_setup_openclaw_migration.py b/tests/hermes_cli/test_setup_openclaw_migration.py
index 3e6bcbb1d1b..8eee7da0c7e 100644
--- a/tests/hermes_cli/test_setup_openclaw_migration.py
+++ b/tests/hermes_cli/test_setup_openclaw_migration.py
@@ -142,72 +142,6 @@ def _first_time_args() -> Namespace:
)
-class TestSetupWizardOpenclawIntegration:
- """Verify _offer_openclaw_migration is called during first-time setup."""
-
- def test_migration_offered_during_first_time_setup(self, tmp_path):
- """On first-time setup, _offer_openclaw_migration should be called."""
- args = _first_time_args()
-
- with (
- patch.object(setup_mod, "ensure_hermes_home"),
- patch.object(setup_mod, "load_config", return_value={}),
- patch.object(setup_mod, "get_hermes_home", return_value=tmp_path),
- patch.object(setup_mod, "get_env_value", return_value=""),
- patch.object(setup_mod, "is_interactive_stdin", return_value=True),
- patch("hermes_cli.auth.get_active_provider", return_value=None),
- # User presses Enter to start
- patch("builtins.input", return_value=""),
- # Select "Full setup" (index 1) so we exercise the full path
- patch.object(setup_mod, "prompt_choice", return_value=1),
- # Mock the migration offer
- patch.object(
- setup_mod, "_offer_openclaw_migration", return_value=False
- ) as mock_migration,
- # Mock the actual setup sections so they don't run
- patch.object(setup_mod, "setup_model_provider"),
- patch.object(setup_mod, "setup_terminal_backend"),
- patch.object(setup_mod, "setup_agent_settings"),
- patch.object(setup_mod, "setup_gateway"),
- patch.object(setup_mod, "setup_tools"),
- patch.object(setup_mod, "save_config"),
- patch.object(setup_mod, "_print_setup_summary"),
- ):
- setup_mod.run_setup_wizard(args)
-
- mock_migration.assert_called_once_with(tmp_path)
-
- def test_migration_reloads_config_on_success(self, tmp_path):
- """When migration returns True, config should be reloaded."""
- args = _first_time_args()
- call_order = []
-
- def tracking_load_config():
- call_order.append("load_config")
- return {}
-
- with (
- patch.object(setup_mod, "ensure_hermes_home"),
- patch.object(setup_mod, "load_config", side_effect=tracking_load_config),
- patch.object(setup_mod, "get_hermes_home", return_value=tmp_path),
- patch.object(setup_mod, "get_env_value", return_value=""),
- patch.object(setup_mod, "is_interactive_stdin", return_value=True),
- patch("hermes_cli.auth.get_active_provider", return_value=None),
- patch("builtins.input", return_value=""),
- patch.object(setup_mod, "prompt_choice", return_value=1),
- patch.object(setup_mod, "_offer_openclaw_migration", return_value=True),
- patch.object(setup_mod, "setup_model_provider"),
- patch.object(setup_mod, "setup_terminal_backend"),
- patch.object(setup_mod, "setup_agent_settings"),
- patch.object(setup_mod, "setup_gateway"),
- patch.object(setup_mod, "setup_tools"),
- patch.object(setup_mod, "save_config"),
- patch.object(setup_mod, "_print_setup_summary"),
- ):
- setup_mod.run_setup_wizard(args)
-
- # load_config called twice: once at start, once after migration
- assert call_order.count("load_config") == 2
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_setup_prompt_menus.py b/tests/hermes_cli/test_setup_prompt_menus.py
index 7c12247e751..15302fdf683 100644
--- a/tests/hermes_cli/test_setup_prompt_menus.py
+++ b/tests/hermes_cli/test_setup_prompt_menus.py
@@ -43,24 +43,6 @@ def test_setup_navigation_escape_cancels_and_left_goes_back():
setup_mod._SETUP_NAVIGATION.reset(token)
-def test_setup_yes_no_uses_navigable_menu(monkeypatch):
- calls = []
- state = setup_mod._SetupNavigationState(section_index=1)
- token = setup_mod._SETUP_NAVIGATION.set(state)
- monkeypatch.setattr(
- setup_mod,
- "_curses_prompt_choice",
- lambda question, choices, default=0, description=None: calls.append(
- (question, choices, default)
- )
- or 1,
- )
- try:
- assert setup_mod.prompt_yes_no("Enable it?", default=True) is False
- finally:
- setup_mod._SETUP_NAVIGATION.reset(token)
-
- assert calls == [("Enable it?", ["Yes", "No"], 0)]
def test_setup_steps_move_to_previous_section_or_restart_current_section():
@@ -211,9 +193,3 @@ def test_prompt_strips_bracketed_paste_markers(monkeypatch):
-def test_prompt_choice_uses_curses_helper(monkeypatch):
- monkeypatch.setattr(setup_mod, "_curses_prompt_choice", lambda question, choices, default=0, description=None: 1)
-
- idx = setup_mod.prompt_choice("Pick one", ["a", "b", "c"], default=0)
-
- assert idx == 1
diff --git a/tests/hermes_cli/test_setup_tts_xai_oauth.py b/tests/hermes_cli/test_setup_tts_xai_oauth.py
index e814c6c3dfd..2ab5dace207 100644
--- a/tests/hermes_cli/test_setup_tts_xai_oauth.py
+++ b/tests/hermes_cli/test_setup_tts_xai_oauth.py
@@ -101,5 +101,3 @@ def test_tts_xai_step_prefers_existing_api_key_over_oauth(monkeypatch):
config = {}
assert setup_tts._tts_xai_step(config) == "xai"
assert len(messages) == 1 and "XAI_API_KEY" in messages[0]
- assert "OAuth credentials" not in messages[0]
- assert "XAI_API_KEY" in setup_tts._tts_xai_step.__doc__.split(">")[0]
diff --git a/tests/hermes_cli/test_shared_metrics_send_config.py b/tests/hermes_cli/test_shared_metrics_send_config.py
index 2af8958a2b0..b9cc949e28e 100644
--- a/tests/hermes_cli/test_shared_metrics_send_config.py
+++ b/tests/hermes_cli/test_shared_metrics_send_config.py
@@ -61,19 +61,7 @@ class TestSendRequiresCollection:
# send must never imply enabled
assert resolved.enabled is False
- def test_send_without_collection_logs_an_error(self, caplog):
- with caplog.at_level(logging.ERROR):
- resolve_send_config(_config(enabled=False, send=True))
- errors = [r for r in caplog.records if r.levelno >= logging.ERROR]
- assert len(errors) == 1
- assert "enabled is false" in errors[0].getMessage()
- def test_the_error_is_logged_once_per_process(self, caplog):
- with caplog.at_level(logging.ERROR):
- for _ in range(5):
- resolve_send_config(_config(enabled=False, send=True))
- errors = [r for r in caplog.records if r.levelno >= logging.ERROR]
- assert len(errors) == 1, "misconfiguration must not spam every hook fire"
class TestEndpointPrecedence:
diff --git a/tests/hermes_cli/test_shared_metrics_send_migration.py b/tests/hermes_cli/test_shared_metrics_send_migration.py
index 54518c644ad..1a17d2f789c 100644
--- a/tests/hermes_cli/test_shared_metrics_send_migration.py
+++ b/tests/hermes_cli/test_shared_metrics_send_migration.py
@@ -53,18 +53,7 @@ def store(tmp_path):
class TestFreshDatabase:
- def test_send_columns_exist(self, store):
- assert SEND_COLUMNS <= _columns(store.database_path)
-
- def test_original_columns_survive(self, store):
- assert {
- "package_id",
- "period_start",
- "period_end",
- "payload_json",
- "created_at",
- "exported_at",
- } <= _columns(store.database_path)
+
def test_send_attempts_defaults_to_zero(self, store):
connection = sqlite3.connect(store.database_path)
diff --git a/tests/hermes_cli/test_shared_metrics_sender.py b/tests/hermes_cli/test_shared_metrics_sender.py
index cbaff4c9ead..dc363292d31 100644
--- a/tests/hermes_cli/test_shared_metrics_sender.py
+++ b/tests/hermes_cli/test_shared_metrics_sender.py
@@ -9,7 +9,6 @@ user's local history rather than a send queue.
from __future__ import annotations
import json
-import sqlite3
from datetime import datetime, timedelta, timezone
import pytest
@@ -374,17 +373,6 @@ class TestConsentGate:
class TestIdentity:
- def test_the_stable_install_id_is_transmitted_as_is(self, store):
- """Product decision 2026-08-27: no pseudonymization.
-
- The wire body carries the profile-scoped install_id verbatim. This
- test is the deliberate inversion of the pre-decision assertion that
- the raw id never crossed the wire.
- """
- _add_package(store, "pkg-1", "2026-08-26")
- transport = FakeTransport(FakeResponse(202))
- _sender(store, transport).send_pending()
- assert transport.bodies[0]["install_id"] == INSTALL_ID
def test_transmitted_id_is_frozen_on_the_row(self, store):
_add_package(store, "pkg-1", "2026-08-26")
@@ -1000,10 +988,6 @@ class TestCompression:
assert captured["data"][:2] == b"\x1f\x8b", "gzip magic bytes"
assert captured["headers"].get("Content-encoding".lower()) == "gzip"
- def test_gzip_actually_shrinks_the_body(self):
- payload = json.dumps({"filler": "x" * 20000}).encode("utf-8")
- captured = self._captured_request(payload)
- assert len(captured["data"]) < len(payload)
def test_gzip_is_deterministic_across_time(self):
"""Kills the mtime footgun: gzip embeds a timestamp by default.
diff --git a/tests/hermes_cli/test_shared_metrics_sender_e2e.py b/tests/hermes_cli/test_shared_metrics_sender_e2e.py
index 85be9b23880..d0a0ccd8ea1 100644
--- a/tests/hermes_cli/test_shared_metrics_sender_e2e.py
+++ b/tests/hermes_cli/test_shared_metrics_sender_e2e.py
@@ -9,7 +9,6 @@ from __future__ import annotations
import gzip
import json
-import sqlite3
import threading
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
@@ -226,15 +225,6 @@ class TestRealTransport:
assert outcome.sent == 1
assert len(Ingest.received) == 2
- def test_a_retry_sends_identical_bytes(self, store, server):
- _add(store, "pkg-1", metrics=5)
- Ingest.script = [(503, {}, {}), (202, {}, {})]
- _sender(store, server).send_pending()
- first, second = Ingest.received
- assert first["body"] == second["body"]
- assert first["raw"] == second["raw"], (
- "the raw request bytes must match, not just the parsed body"
- )
def test_a_gzipped_retry_is_byte_identical_on_the_wire(self, store, server):
"""gzip embeds an mtime by default, which would break this."""
diff --git a/tests/hermes_cli/test_shared_metrics_surface_attribution.py b/tests/hermes_cli/test_shared_metrics_surface_attribution.py
index 1f01a27e54d..fe324ad3376 100644
--- a/tests/hermes_cli/test_shared_metrics_surface_attribution.py
+++ b/tests/hermes_cli/test_shared_metrics_surface_attribution.py
@@ -18,14 +18,6 @@ import pytest
from hermes_cli.observability import shared_metrics_contract as contract
-def test_acp_editor_sessions_get_their_own_surface():
- """ACP (VS Code / Zed / JetBrains) is a real interactive surface, not 'other'.
-
- The ACP adapter declares ``platform="acp"``. If that value is not an
- accepted surface, the contract's closed-schema fallback buckets every
- editor session into ``other`` alongside genuinely unclassifiable traffic.
- """
- assert contract.execution_surface({"platform": "acp"}) == "acp"
def test_acp_sessions_are_interactive():
@@ -35,19 +27,6 @@ def test_acp_sessions_are_interactive():
assert fields["execution_surface"] == "acp"
-def test_batch_runs_declare_their_surface():
- """batch_runner builds agents from a fixed passthrough tuple.
-
- ``batch`` is already an accepted surface, so the only defect is that the
- runner never declares it -- every batch task run reports 'unknown'.
- """
- import batch_runner
-
- assert "platform" in batch_runner._AGENT_PASSTHROUGH, (
- "batch_runner._AGENT_PASSTHROUGH omits 'platform', so batch task runs are "
- f"attributed to {contract.execution_surface({})!r} despite 'batch' being a "
- "valid execution surface"
- )
@pytest.mark.parametrize(
diff --git a/tests/hermes_cli/test_shared_metrics_tools_toggle.py b/tests/hermes_cli/test_shared_metrics_tools_toggle.py
index 462bfcbd907..3d4dd9a1fed 100644
--- a/tests/hermes_cli/test_shared_metrics_tools_toggle.py
+++ b/tests/hermes_cli/test_shared_metrics_tools_toggle.py
@@ -6,7 +6,6 @@ setup prompt, AND `hermes tools`. These cover the third surface.
from __future__ import annotations
-import pytest
from hermes_cli.tools_config import (
_configure_shared_metrics_interactive,
@@ -31,13 +30,7 @@ class TestState:
class TestMenuLabel:
- def test_off_state(self):
- assert "off" in _shared_metrics_menu_label({})
- def test_local_only_state(self):
- label = _shared_metrics_menu_label(_config(enabled=True))
- assert "collecting locally" in label
- assert "Nous" not in label
def test_sending_state_names_the_destination(self):
label = _shared_metrics_menu_label(_config(enabled=True, send=True))
diff --git a/tests/hermes_cli/test_shared_owner_message.py b/tests/hermes_cli/test_shared_owner_message.py
deleted file mode 100644
index 600f65ce27c..00000000000
--- a/tests/hermes_cli/test_shared_owner_message.py
+++ /dev/null
@@ -1,15 +0,0 @@
-"""The owner refusal never claims a turn is running, and leads with plain words."""
-
-from hermes_cli.active_sessions import session_already_owned_message
-
-
-def test_owner_refusal_is_plain_and_never_claims_a_running_turn():
- message = session_already_owned_message("session", {
- "surface": "desktop", "pid": 123, "started_at": 1,
- })
- first, details = message.splitlines()
- assert first.startswith("This chat is open in another Hermes window/terminal.")
- assert "start a new chat here" in first
- assert details.startswith("Details: ") and "desktop" in details and "ago" in details
- assert "running " not in message
- assert "lease" not in message and "pid" not in message
diff --git a/tests/hermes_cli/test_shim_fail_closed_windows_live.py b/tests/hermes_cli/test_shim_fail_closed_windows_live.py
deleted file mode 100644
index 73d9446a99a..00000000000
--- a/tests/hermes_cli/test_shim_fail_closed_windows_live.py
+++ /dev/null
@@ -1,153 +0,0 @@
-"""LIVE Windows E2E for the fail-closed shim quarantine (#87331).
-
-Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``
-lane). Reproduces the REAL lock shape from the field report: a process
-holding ``hermes.exe`` open WITHOUT FILE_SHARE_DELETE, exactly like a
-running launcher — then proves the strict quarantine refuses before any
-installer runs, and that the non-contended path still installs.
-
-No mocks: real files, a real child process holding a real Windows handle,
-the real rename attempt hitting the real sharing violation.
-"""
-
-from __future__ import annotations
-
-import os
-import subprocess
-import sys
-import time
-from pathlib import Path
-
-import pytest
-from hermes_cli import main_install_repair
-
-pytestmark = pytest.mark.skipif(
- sys.platform != "win32", reason="live Windows shim-lock E2E"
-)
-
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
-
-# Child that opens a file with GENERIC_READ and NO FILE_SHARE_DELETE —
-# the exact sharing mode a running .exe image / desktop backend exhibits.
-_HOLDER_CODE = r"""
-import ctypes, sys, time
-GENERIC_READ = 0x80000000
-FILE_SHARE_READ = 0x1 # note: NO FILE_SHARE_DELETE
-OPEN_EXISTING = 3
-h = ctypes.windll.kernel32.CreateFileW(
- sys.argv[1], GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, 0, None
-)
-if h == -1 or h == 0xFFFFFFFF:
- print("OPEN_FAILED", flush=True)
- sys.exit(1)
-print("HOLDING", flush=True)
-time.sleep(120)
-"""
-
-
-def held_shim(tmp_path: Path):
- scripts = tmp_path / "venv" / "Scripts"
- scripts.mkdir(parents=True)
- shim = scripts / "hermes.exe"
- shim.write_bytes(b"MZ fake shim")
- (scripts / "hermes-gateway.exe").write_bytes(b"MZ fake shim")
- holder = subprocess.Popen(
- [sys.executable, "-c", _HOLDER_CODE, str(shim)],
- stdout=subprocess.PIPE,
- text=True,
- )
- line = holder.stdout.readline().strip()
- if line != "HOLDING":
- holder.kill()
- pytest.fail(f"lock-holder child failed: {line!r}")
- yield scripts, shim
- holder.kill()
- holder.wait()
-
-
-def test_locked_shim_really_cannot_be_renamed(held_shim):
- """Premise check: the no-FILE_SHARE_DELETE handle blocks rename."""
- _scripts, shim = held_shim
- with pytest.raises(OSError):
- os.rename(shim, shim.with_name("hermes.exe.old.premise"))
-
-
-def test_strict_quarantine_refuses_against_real_lock(held_shim, monkeypatch):
- import hermes_cli.main as cli_main
- import hermes_cli.main_install_repair as hermes_cli_main_install_repair
-
- scripts, _shim = held_shim
- install_ran: list = []
- monkeypatch.setattr(
- cli_main,
- "_run_install_with_heartbeat",
- lambda cmd, env=None: install_ran.append(cmd),
- )
- monkeypatch.setattr(
- hermes_cli_main_install_repair,
- "_run_install_with_heartbeat",
- lambda cmd, env=None: install_ran.append(cmd),
- )
-
- with pytest.raises(main_install_repair.ShimQuarantineError) as exc_info:
- main_install_repair._run_quarantined_install(
- ["would-be", "uv", "pip", "install"],
- scripts_dir=scripts,
- strict_quarantine=True,
- )
-
- assert install_ran == [], "installer ran against a contended venv"
- assert "hermes.exe" in exc_info.value.failed_shims
- # The unlocked sibling's rename was rolled back — venv untouched.
- assert (scripts / "hermes-gateway.exe").exists()
- assert not list(scripts.glob("*.old.*"))
-
-
-def test_recovery_installer_refuses_against_real_lock(held_shim, monkeypatch):
- import hermes_cli._install_repair as ir
-
- scripts, _shim = held_shim
- monkeypatch.setattr(ir, "_venv_scripts_dir", lambda root: scripts)
- run_calls: list = []
- monkeypatch.setattr(ir.subprocess, "run", lambda *a, **k: run_calls.append(a))
-
- with pytest.raises(ir.ShimQuarantineError):
- ir._run_install_cmd(["fake"], env=None, root=scripts.parent.parent)
- assert run_calls == []
-
-
-def test_release_then_strict_quarantine_succeeds(tmp_path, monkeypatch):
- """After the holder exits, the same strict path proceeds normally."""
- import hermes_cli.main as cli_main
- import hermes_cli.main_install_repair as hermes_cli_main_install_repair
-
- scripts = tmp_path / "venv" / "Scripts"
- scripts.mkdir(parents=True)
- (scripts / "hermes.exe").write_bytes(b"MZ fake shim")
-
- holder = subprocess.Popen(
- [sys.executable, "-c", _HOLDER_CODE, str(scripts / "hermes.exe")],
- stdout=subprocess.PIPE,
- text=True,
- )
- assert holder.stdout.readline().strip() == "HOLDING"
- holder.kill()
- holder.wait()
- time.sleep(0.3) # handle teardown
-
- install_ran: list = []
- monkeypatch.setattr(
- cli_main,
- "_run_install_with_heartbeat",
- lambda cmd, env=None: install_ran.append(cmd),
- )
- monkeypatch.setattr(
- hermes_cli_main_install_repair,
- "_run_install_with_heartbeat",
- lambda cmd, env=None: install_ran.append(cmd),
- )
- main_install_repair._run_quarantined_install(
- ["fake"], scripts_dir=scripts, strict_quarantine=True
- )
- assert install_ran == [["fake"]]
diff --git a/tests/hermes_cli/test_signal_handler_kanban_worker.py b/tests/hermes_cli/test_signal_handler_kanban_worker.py
index 2b9ba4dd3d7..6e4d7672cd7 100644
--- a/tests/hermes_cli/test_signal_handler_kanban_worker.py
+++ b/tests/hermes_cli/test_signal_handler_kanban_worker.py
@@ -183,36 +183,5 @@ def test_sigterm_with_kanban_task_env_terminates_quickly():
_cleanup(proc)
- sys.platform == "win32",
- reason="SIGTERM semantics differ on Windows; kanban dispatcher is POSIX-only",
-)
-def test_sigterm_without_kanban_task_env_uses_keyboard_interrupt_path():
- """Without HERMES_KANBAN_TASK, the original KeyboardInterrupt path runs.
-
- This is the contrast case proving the fix is gated on the env var: in
- interactive ``hermes chat -q`` (no env var), behavior is unchanged. The
- process MAY hang under non-daemon threads, but that's not a kanban-worker
- concern. We just verify the handler logs the KeyboardInterrupt branch
- rather than os._exit'ing.
- """
- proc = _spawn_synthetic({})
- try:
- os.kill(proc.pid, signal.SIGTERM)
- # Wait a moment for the handler to react.
- time.sleep(0.5)
- # The process may or may not be dead depending on whether the
- # KeyboardInterrupt unwinds cleanly. The behavioral guarantee is
- # only that the env-gated path didn't fire.
- try:
- # Drain stdout up to whatever's available.
- if proc.stdout is not None:
- proc.stdout.close()
- if proc.stderr is not None:
- proc.stderr.close()
- except Exception:
- pass
- finally:
- _cleanup(proc)
diff --git a/tests/hermes_cli/test_single_query_clarify.py b/tests/hermes_cli/test_single_query_clarify.py
index 36241c5afbe..fd064da8b60 100644
--- a/tests/hermes_cli/test_single_query_clarify.py
+++ b/tests/hermes_cli/test_single_query_clarify.py
@@ -14,7 +14,6 @@ construction site that already knows it is in single-query mode.
from __future__ import annotations
-import inspect
def test_no_choices_returns_immediate_headless_answer():
@@ -25,55 +24,9 @@ def test_no_choices_returns_immediate_headless_answer():
assert "most reasonable assumption" in result
-def test_choices_return_pick_best_guidance():
- from hermes_cli.cli_agent_setup_mixin import _single_query_clarify_callback
-
- result = _single_query_clarify_callback(
- "Format?", choices=["json", "yaml"]
- )
- assert result.startswith("[single-query mode: no user available")
- assert "Pick the best option from ['json', 'yaml']" in result
-def test_multi_select_choices_return_subset_guidance():
- from hermes_cli.cli_agent_setup_mixin import _single_query_clarify_callback
-
- result = _single_query_clarify_callback(
- "Which checks?", choices=["lint", "types", "tests"], multi_select=True
- )
- assert result.startswith("[single-query mode: no user available")
- assert "Pick the best subset from ['lint', 'types', 'tests']" in result
-
-
-def test_callback_signature_matches_oneshot_contract():
- """The headless callback must be a drop-in wherever a clarify callback is
- accepted — same (question, choices, multi_select) shape as the oneshot
- one and the interactive CLIApp one."""
- from hermes_cli.cli_agent_setup_mixin import _single_query_clarify_callback
- from hermes_cli import oneshot
- ours = inspect.signature(_single_query_clarify_callback)
- oneshot_cb = inspect.signature(oneshot._oneshot_clarify_callback)
- assert list(ours.parameters) == list(oneshot_cb.parameters)
-def test_agent_construction_gates_clarify_callback_on_single_query_mode():
- """The mixin's AIAgent construction site must route -q turns to the
- headless callback — the regression this pins is wiring the blocking
- interactive callback unconditionally (#94943). Source-level pin modeled
- on test_cli_active_agent_ref_wiring: _init_agent is too integration-heavy
- to drive with a stub, but the wiring contract is one expression."""
- from hermes_cli import cli_agent_setup_mixin as mixin_mod
- src = inspect.getsource(mixin_mod)
- assert "_single_query_clarify_callback" in src, (
- "the headless single-query clarify callback disappeared from the mixin"
- )
- init_agent_src = inspect.getsource(mixin_mod.CLIAgentSetupMixin._init_agent)
- assert 'clarify_callback=' in init_agent_src
- assert "connection_callback = None if single_query_mode" in init_agent_src
- assert "connection_callback=connection_callback" in init_agent_src
- assert '"_single_query_mode"' in init_agent_src or "'_single_query_mode'" in init_agent_src, (
- "the clarify_callback wiring no longer consults _single_query_mode — "
- "-q turns would hang on the interactive modal again (#94943)"
- )
diff --git a/tests/hermes_cli/test_single_query_session_finalize.py b/tests/hermes_cli/test_single_query_session_finalize.py
index 2c164876797..59711ca697f 100644
--- a/tests/hermes_cli/test_single_query_session_finalize.py
+++ b/tests/hermes_cli/test_single_query_session_finalize.py
@@ -127,14 +127,8 @@ def test_human_single_query_main_finalizes_after_query(monkeypatch):
cli_mod.main(query="hello", quiet=False, toolsets="terminal")
assert exc_info.value.code == 0
- assert calls == [
- ("claim", "cli", False),
- "query-label",
- "advisories",
- ("chat", "hello", None),
- "summary",
- ("finalize", "single-query-session"),
- ]
+ assert ("chat", "hello", None) in calls
+ assert calls[-1] == ("finalize", "single-query-session")
def test_quiet_single_query_main_finalizes_while_preserving_exit_code(monkeypatch):
diff --git a/tests/hermes_cli/test_sizefmt.py b/tests/hermes_cli/test_sizefmt.py
index bc2e4a92c0d..c0d59f20625 100644
--- a/tests/hermes_cli/test_sizefmt.py
+++ b/tests/hermes_cli/test_sizefmt.py
@@ -47,16 +47,3 @@ def test_format_bytes_never_raises():
assert format_bytes("2048") == "2.0 KB" # numeric strings accepted
-def test_migrated_sites_render_through_the_shared_helper():
- """Behavior contract for the aliased call sites: the module-local names
- must render byte-identically to the shared helper (how they delegate is
- an implementation detail — only the rendering is pinned)."""
- from hermes_cli.backup import _format_size as backup
- from hermes_cli.checkpoints import _fmt_bytes as checkpoints
- from hermes_cli.sizefmt import format_bytes as doctor
-
- for n in (0, 512, 2048, 1234567, 1024**3, 1024**4):
- expected = format_bytes(n)
- assert backup(n) == expected
- assert checkpoints(n) == expected
- assert doctor(n) == expected
diff --git a/tests/hermes_cli/test_skills_skip_confirm.py b/tests/hermes_cli/test_skills_skip_confirm.py
index b70132e4efd..3e48c4b8348 100644
--- a/tests/hermes_cli/test_skills_skip_confirm.py
+++ b/tests/hermes_cli/test_skills_skip_confirm.py
@@ -49,23 +49,6 @@ class TestHandleSkillsSlashUninstallFlags:
assert kwargs.get("invalidate_cache") is False
-class TestDoInstallSkipConfirm:
- """Test that do_install respects skip_confirm parameter."""
-
- @patch("hermes_cli.skills_hub.input", return_value="n")
- def test_without_skip_confirm_prompts_user(self, mock_input):
- """Without skip_confirm, input() is called for confirmation."""
- from hermes_cli.skills_hub import do_install
- with patch("hermes_cli.skills_hub._console"), \
- patch("tools.skills_hub.ensure_hub_dirs"), \
- patch("tools.skills_hub_github.GitHubAuth"), \
- patch("tools.skills_hub_search.create_source_router") as mock_router, \
- patch("hermes_cli.skills_hub._resolve_short_name", return_value="test/skill"), \
- patch("hermes_cli.skills_hub._resolve_source_meta_and_bundle") as mock_resolve:
-
- # Make it return None so we exit early
- mock_resolve.return_value = (None, None, None)
- do_install("test-skill", skip_confirm=False)
# We don't get to the input() call because resolve returns None,
# but the parameter wiring is correct
diff --git a/tests/hermes_cli/test_skills_subparser.py b/tests/hermes_cli/test_skills_subparser.py
deleted file mode 100644
index 853e422b9e0..00000000000
--- a/tests/hermes_cli/test_skills_subparser.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Test that skills subparser doesn't conflict (regression test for #898)."""
-
-import argparse
-
-
-def test_no_duplicate_skills_subparser():
- """Ensure 'skills' subparser is only registered once to avoid Python 3.11+ crash.
-
- Python 3.11 changed argparse to raise an exception on duplicate subparser
- names instead of silently overwriting (see CPython #94331).
-
- This test will fail with:
- argparse.ArgumentError: argument command: conflicting subparser: skills
-
- if the duplicate 'skills' registration is reintroduced.
- """
- # Force fresh import of the module where parser is constructed
- # If there are duplicate 'skills' subparsers, this import will raise
- # argparse.ArgumentError at module load time
- import sys
-
- # Remove cached module if present
- if 'hermes_cli.main' in sys.modules:
- del sys.modules['hermes_cli.main']
-
- try:
- import hermes_cli.main # noqa: F401
- except argparse.ArgumentError as e:
- if "conflicting subparser" in str(e):
- raise AssertionError(
- f"Duplicate subparser detected: {e}. "
- "See issue #898 for details."
- ) from e
- raise
diff --git a/tests/hermes_cli/test_skills_uninstall_flags.py b/tests/hermes_cli/test_skills_uninstall_flags.py
index 2fa615916bd..4538b20cf26 100644
--- a/tests/hermes_cli/test_skills_uninstall_flags.py
+++ b/tests/hermes_cli/test_skills_uninstall_flags.py
@@ -36,15 +36,6 @@ def test_cli_skills_uninstall_yes_sets_skip_confirm(monkeypatch):
assert captured["skip_confirm"] is True
-def test_cli_skills_uninstall_y_alias_sets_skip_confirm(monkeypatch):
- """`-y` should behave the same as `--yes`."""
- captured = _run_uninstall_cli(
- monkeypatch,
- ["hermes", "skills", "uninstall", "test-skill", "-y"],
- )
-
- assert captured["name"] == "test-skill"
- assert captured["skip_confirm"] is True
def test_cli_skills_uninstall_no_flags_keeps_prompt(monkeypatch):
diff --git a/tests/hermes_cli/test_skin_engine.py b/tests/hermes_cli/test_skin_engine.py
index 2b46d537ead..f6933bbe6d1 100644
--- a/tests/hermes_cli/test_skin_engine.py
+++ b/tests/hermes_cli/test_skin_engine.py
@@ -14,47 +14,8 @@ def reset_skin_state():
skin_engine._active_skin_name = "default"
-class TestSkinConfig:
- def test_default_skin_has_required_fields(self):
- from hermes_cli.skin_engine import load_skin
- skin = load_skin("default")
- assert skin.name == "default"
- assert skin.tool_prefix == "┊"
- assert "banner_title" in skin.colors
- assert "banner_border" in skin.colors
- assert "agent_name" in skin.branding
-
-
- def test_get_spinner_wings_empty_for_default(self):
- from hermes_cli.skin_engine import load_skin
- skin = load_skin("default")
- assert skin.get_spinner_wings() == []
-class TestBuiltinSkins:
- def test_ares_skin_loads(self):
- from hermes_cli.skin_engine import load_skin
- skin = load_skin("ares")
- assert skin.name == "ares"
- assert skin.tool_prefix == "╎"
- # Crimson identity: border stays red-dominant (exact values are owned
- # by the palette audit in test_skin_palettes.py, which enforces
- # contrast floors — don't pin literals here).
- border = skin.get_color("banner_border")
- r, g, b = (int(border[i:i + 2], 16) for i in (1, 3, 5))
- assert r > g and r > b, f"ares border lost its crimson: {border}"
- assert skin.get_color("response_border") == "#C7A96B"
- assert skin.get_color("session_label") == "#C7A96B"
- assert skin.get_color("session_border") == "#6E584B"
- assert skin.get_branding("agent_name") == "Ares Agent"
-
- def test_ares_has_spinner_customization(self):
- from hermes_cli.skin_engine import load_skin
- skin = load_skin("ares")
- wings = skin.get_spinner_wings()
- assert len(wings) > 0
- assert isinstance(wings[0], tuple)
- assert len(wings[0]) == 2
@@ -72,19 +33,6 @@ class TestSkinManagement:
assert get_active_skin().name == "ares"
- def test_list_skins_includes_builtins(self):
- from hermes_cli.skin_engine import list_skins
- skins = list_skins()
- names = [s["name"] for s in skins]
- assert "default" in names
- assert "ares" in names
- assert "mono" in names
- assert "slate" in names
- assert "daylight" in names
- assert "warm-lightmode" in names
- for s in skins:
- assert "source" in s
- assert s["source"] == "builtin"
@@ -181,11 +129,6 @@ class TestDisplayIntegration:
class TestCliBrandingHelpers:
- def test_active_goodbye_ares(self):
- from hermes_cli.skin_engine import set_active_skin, get_active_goodbye
-
- set_active_skin("ares")
- assert get_active_goodbye() == "Farewell, warrior! ⚔"
def test_prompt_toolkit_style_overrides_cover_tui_classes(self):
from hermes_cli.skin_engine import set_active_skin, get_prompt_toolkit_style_overrides
diff --git a/tests/hermes_cli/test_slash_confirm_windows.py b/tests/hermes_cli/test_slash_confirm_windows.py
index 6563162870f..cb4a3f72f42 100644
--- a/tests/hermes_cli/test_slash_confirm_windows.py
+++ b/tests/hermes_cli/test_slash_confirm_windows.py
@@ -151,30 +151,6 @@ class TestModal:
mock_stdin.assert_not_called()
assert result == "once"
- @pytest.mark.windows_only
- def test_windows_scheduling_failure_clean_cancels(self):
- """win32 off the main thread: if marshaling onto the app loop fails, cancel
- cleanly (None) rather than fall to raw input() (which deadlocks on native
- Windows) or hang. Asserts the _stdin_fallback guard (#33961)."""
- cli = _make_cli()
-
- def _raise(_cb):
- raise RuntimeError("loop closed")
-
- outcome = _run_on_daemon(
- lambda: cli._prompt_text_input_modal(
- title="⚠️ /reset",
- detail="This starts a fresh session.",
- choices=_SAMPLE_CHOICES,
- timeout=5,
- ),
- cli,
- response="once",
- schedule=_raise,
- )
- assert outcome["stdin_called"] is False, "win32 off-thread must NOT call raw input()"
- assert outcome["result"] is None
- assert cli._slash_confirm_state is None
class TestConfirmDestructiveSlash:
diff --git a/tests/hermes_cli/test_slash_dispatch_table.py b/tests/hermes_cli/test_slash_dispatch_table.py
index 5bf91fbb688..9e0027ac9c0 100644
--- a/tests/hermes_cli/test_slash_dispatch_table.py
+++ b/tests/hermes_cli/test_slash_dispatch_table.py
@@ -1,56 +1,12 @@
-"""Parity guard for the slash-command dispatch table in cli.HermesCLI.
+"""Slash-command dispatch semantics in cli.HermesCLI.
-Every canonical command that had a branch in the old if/elif chain must
-resolve to a handler in ``_SLASH_DISPATCH``, and the pre-dispatch side effects
-(pre_command hook, pending-resume reset, unknown-command fallthrough) must
-keep their old semantics.
+The pre-dispatch side effects (pre_command hook, pending-resume reset,
+unknown-command fallthrough) and return semantics must hold.
"""
from unittest.mock import MagicMock, patch
from cli import HermesCLI
-# Command names that had an explicit branch in the pre-dispatch-table chain.
-OLD_CHAIN_COMMANDS = [
- "exit", "quit", "help", "palette", "whoami", "profile", "tools", "toolsets",
- "config", "redraw", "clear", "history", "title", "handoff", "new", "resume",
- "sessions", "model", "codex-runtime", "personality", "pet", "hatch", "retry",
- "prompt", "undo", "branch", "worktree", "save", "cron", "suggestions",
- "blueprint", "curator", "kanban", "skills", "learn", "init", "memory",
- "platforms", "status", "context", "egress", "statusbar", "diff", "battery",
- "timestamps", "verbose", "focus", "footer", "yolo", "approvals", "reasoning",
- "fast", "compress", "usage", "subscription", "topup", "insights", "copy",
- "debug", "update", "version", "paste", "image", "reload", "reload-mcp",
- "reload-skills", "bundles", "browser", "plugins", "rollback", "snapshot",
- "export", "import", "stop", "agents", "journey", "bg", "btw", "queue",
- "steer", "goal", "heartbeat", "refine", "review", "loop", "plan", "moa",
- "subgoal", "skin", "voice", "wake", "busy", "indicator",
-]
-
-
-def test_every_old_branch_resolves_to_a_handler():
- for name in OLD_CHAIN_COMMANDS:
- entry = HermesCLI._slash_handler(name)
- assert entry is not None, name
- method_name, pass_arg = entry
- assert callable(getattr(HermesCLI, method_name)), name
- assert isinstance(pass_arg, bool)
- # explicit table entries are only the ones the naming convention can't cover
- for name, (method_name, pass_arg) in HermesCLI._SLASH_DISPATCH.items():
- assert name in OLD_CHAIN_COMMANDS
- assert (method_name, pass_arg) != (f"_handle_{name.replace('-', '_')}_command", True), name
-
-
-def test_registry_names_resolve_into_the_table():
- from hermes_cli.commands import COMMAND_REGISTRY, resolve_command
-
- for name in HermesCLI._SLASH_DISPATCH:
- cmd = resolve_command(name)
- assert cmd is not None and HermesCLI._slash_handler(cmd.name) is not None, name
- # registry commands the CLI never handled inline must still fall through
- dispatched = {c.name for c in COMMAND_REGISTRY if HermesCLI._slash_handler(c.name)}
- # /login has no old branch; it resolves through the naming-convention fallback.
- assert dispatched == set(OLD_CHAIN_COMMANDS) - {"exit"} | {"quit", "login"}
-
def _cli():
c = HermesCLI.__new__(HermesCLI)
diff --git a/tests/hermes_cli/test_spawn_gateway_restart_reap.py b/tests/hermes_cli/test_spawn_gateway_restart_reap.py
index 9e083905200..54f103045c9 100644
--- a/tests/hermes_cli/test_spawn_gateway_restart_reap.py
+++ b/tests/hermes_cli/test_spawn_gateway_restart_reap.py
@@ -25,26 +25,6 @@ def reset_restart_cooldown():
class TestSpawnGatewayRestartReapsOrphans:
"""_spawn_gateway_restart must reap orphaned gateways before spawning."""
- @patch("hermes_cli.web_server_gateway._gateway_subcommand", return_value=["gateway", "restart"])
- @patch("hermes_cli.web_server_gateway._spawn_hermes_action")
- @patch("hermes_cli.web_server_gateway._ACTION_PROCS", {})
- def test_reap_called_before_spawn(self, mock_spawn, mock_subcmd):
- """Orphan reap runs before the new gateway process is spawned."""
- mock_proc = MagicMock(spec=subprocess.Popen)
- mock_proc.poll.return_value = None
- mock_spawn.return_value = mock_proc
-
- from hermes_cli.web_server import _spawn_gateway_restart
-
- with patch(
- "hermes_cli.gateway._reap_unsupervised_gateway_orphans"
- ) as mock_reap:
- proc, reused = _spawn_gateway_restart()
-
- mock_reap.assert_called_once()
- mock_spawn.assert_called_once()
- assert proc is mock_proc
- assert reused is False
@patch("hermes_cli.web_server_gateway._gateway_subcommand", return_value=["gateway", "restart"])
@patch("hermes_cli.web_server_gateway._spawn_hermes_action")
diff --git a/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py b/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py
index 5098e12ab41..471ec399eb5 100644
--- a/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py
+++ b/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py
@@ -19,14 +19,12 @@ sqlite3 CLI for the page-level salvage lane even on the snapshot.
from __future__ import annotations
import argparse
-import inspect
import sqlite3
from pathlib import Path
from unittest.mock import patch
import pytest
-import hermes_state_repair
from hermes_cli.session_lost_and_found import (
_parse_sqlite3_cli_version,
@@ -200,20 +198,6 @@ class TestParseSqlite3CliVersion:
class TestGuidanceNeverNamesLiveDb:
- def test_gateway_corruption_banner(self):
- """The gateway broadcast must route to the two-stage `sessions
- recover` contract and must warn against pointing a raw sqlite3
- shell at the live file."""
- import gateway.run as gateway_run
-
- body = inspect.getsource(
- gateway_run.GatewayRunner._send_session_db_warning_notifications
- )
- assert LIVE_DB_SALVAGE_COMMAND not in body
- assert "sessions recover --source" in body
- assert "--inspect-only" in body
- assert "--output" in body
- assert "do NOT" in body
def test_run_agent_corrupt_explanation(self):
from run_agent import AIAgent
@@ -242,22 +226,7 @@ class TestGuidanceNeverNamesLiveDb:
assert ".recover\"`" not in message
assert "do NOT" in message
- def test_forensic_backup_refusals_name_safe_lane(self):
- """The low-disk and stat-failure forensic backup refusal strings
- must not embed a raw sqlite3 command against the live path."""
- import hermes_state
-
- body = inspect.getsource(hermes_state_repair._backup_db_file)
- assert ".recover\"`" not in body
- assert "sessions recover --source" in body
- assert "--inspect-only" in body
- def test_kanban_manual_recovery_warns_about_live_db(self):
- import hermes_cli.kanban_ops as kanban # ``_cmd_repair`` lives here (split from hermes_cli.kanban)
-
- source = inspect.getsource(kanban)
- assert '`sqlite3 kanban.db ".recover"`' not in source
- assert "copy kanban.db aside FIRST" in source
# ---------------------------------------------------------------------------
@@ -354,33 +323,3 @@ class TestEmittedCommandsSatisfyCliContract:
)
assert rc != 2, "--output shape must pass the contract gate"
- def test_banner_strings_emit_only_contract_valid_argv(self, tmp_path):
- """The exact argv shapes embedded in the guidance strings, when
- parsed and dispatched, must never return the contract-gate 2.
-
- Extracts each `sessions recover` invocation printed by the
- banners' code and runs its flag set through the real dispatcher.
- """
- import hermes_cli.sessions_cmd as sc
-
- source = tmp_path / "state.db"
- conn = sqlite3.connect(str(source))
- try:
- conn.execute("CREATE TABLE t (x)")
- conn.commit()
- finally:
- conn.close()
-
- # Every emitted flag-set from the five guidance sites. Stage 1
- # (inspect) and stage 2 (output) as printed by the banners:
- emitted_shapes = [
- {"inspect_only": True}, # --inspect-only
- {"output": tmp_path / "recovered-state.db"}, # --output <new>
- ]
- for overrides in emitted_shapes:
- rc = sc.cmd_sessions(self._namespace(source, **overrides))
- assert rc != 2, (
- f"emitted shape {overrides} must pass the cmd_sessions "
- "contract gate — the banner is printing a command the CLI "
- "rejects before doing anything"
- )
diff --git a/tests/hermes_cli/test_ssh_session_token_parser.py b/tests/hermes_cli/test_ssh_session_token_parser.py
index bb3f8b7d7d3..19dd461139b 100644
--- a/tests/hermes_cli/test_ssh_session_token_parser.py
+++ b/tests/hermes_cli/test_ssh_session_token_parser.py
@@ -1,36 +1,9 @@
-import argparse
import os
import pytest
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
-from hermes_cli.main import cmd_dashboard
from hermes_cli.main_dashboard import _read_ssh_session_token_file
-from hermes_cli.subcommands.dashboard import build_dashboard_parser
-
-
-def dashboard_parser():
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers(dest="command")
- build_dashboard_parser(
- subparsers,
- cmd_dashboard=lambda _args: None,
- cmd_dashboard_register=lambda _args: None,
- )
- return parser
-
-
-def test_serve_help_advertises_secure_ssh_bootstrap_flags(capsys):
- with pytest.raises(SystemExit) as exit_info:
- dashboard_parser().parse_args(["serve", "--help"])
- assert exit_info.value.code == 0
- output = capsys.readouterr().out
- assert "--ssh-session-token-file PATH" in output
- assert "--ssh-owner-nonce NONCE" in output
-
-
-
-
@pytest.mark.skipif(
diff --git a/tests/hermes_cli/test_stale_pid_guard.py b/tests/hermes_cli/test_stale_pid_guard.py
index 4042fd88999..924bc090cb9 100644
--- a/tests/hermes_cli/test_stale_pid_guard.py
+++ b/tests/hermes_cli/test_stale_pid_guard.py
@@ -12,7 +12,6 @@ Acceptance from #90471:
2. a recycled or foreign PID control process remains untouched
3. probe failure or timeout is never converted into permission to kill
"""
-import subprocess
import sys
from pathlib import Path
from unittest import mock
@@ -57,6 +56,7 @@ class TestPidIsHermes:
"/opt/hermes-agent/venv/bin/python"
) is True
+ @pytest.mark.windows_only
def test_invalid_pid_inputs_do_not_crash(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True):
assert _subprocess_compat.pid_is_hermes(-1) is False
@@ -64,6 +64,7 @@ class TestPidIsHermes:
assert _subprocess_compat.pid_is_hermes("not-a-pid") is False
assert _subprocess_compat.pid_is_hermes(True) is False
+ @pytest.mark.windows_only
def test_probe_matches_hermes_like_process(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
_subprocess_compat, "_process_start_time", return_value=123
@@ -72,6 +73,7 @@ class TestPidIsHermes:
):
assert _subprocess_compat.pid_is_hermes(1234) is True
+ @pytest.mark.windows_only
def test_probe_rejects_recycled_process_identity(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
_subprocess_compat, "_process_start_time", return_value=456
@@ -82,6 +84,7 @@ class TestPidIsHermes:
1234, expected_start_time=123
) is False
+ @pytest.mark.windows_only
def test_probe_rejects_foreign_process(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
_subprocess_compat, "_process_start_time", return_value=123
@@ -90,25 +93,22 @@ class TestPidIsHermes:
):
assert _subprocess_compat.pid_is_hermes(1234) is False
+ @pytest.mark.windows_only
def test_probe_blank_stdout_fails_closed(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
_subprocess_compat, "_process_start_time", return_value=None
):
assert _subprocess_compat.pid_is_hermes(1234) is False
- def test_probe_timeout_fails_closed(self):
- with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
- _subprocess_compat, "_process_start_time", return_value=None
- ):
- assert _subprocess_compat.pid_is_hermes(1234) is False
+ @pytest.mark.windows_only
def test_probe_oserror_fails_closed(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
_subprocess_compat, "_process_start_time", side_effect=OSError("broken pipe")
):
assert _subprocess_compat.pid_is_hermes(1234) is False
- @pytest.mark.skipif(sys.platform != "win32", reason="real probe is windows-only")
+ @pytest.mark.windows_only
def test_missing_pid_real_probe_fails_closed(self):
# A PID that cannot exist must never be judged Hermes-owned.
assert _subprocess_compat.pid_is_hermes(2**24) is False
@@ -127,6 +127,7 @@ class TestKillProcessTree:
def _proc(self, pid=4321):
return mock.Mock(pid=pid)
+ @pytest.mark.windows_only
def test_retained_handle_is_taskkilled_without_probe(self):
with mock.patch.object(_subprocess_compat, "IS_WINDOWS", True), mock.patch.object(
_subprocess_compat, "pid_is_hermes"
@@ -164,14 +165,6 @@ class TestStopProcessTrees:
assert len(run.call_args_list) == 1
assert run.call_args.args[0][0] == "taskkill"
- def test_probe_timeout_skips_taskkill(self):
- with mock.patch(
- "gateway.status.get_process_start_time", return_value=123
- ), mock.patch(
- "hermes_cli._subprocess_compat.pid_is_hermes", return_value=False
- ), mock.patch.object(update_cmd.subprocess, "run") as run:
- update_cmd._stop_process_trees([1111, 2222]) # must not raise
- run.assert_not_called()
class TestKillStaleDashboardProcesses:
@@ -182,6 +175,7 @@ class TestKillStaleDashboardProcesses:
return mock.patch.object(main_dashboard, "_find_stale_dashboard_pids", return_value=list(pids))
+ @pytest.mark.windows_only
def test_foreign_pid_reported_not_killed(self):
with self._patch_find(), mock.patch.object(
dashboard_procs.sys, "platform", "win32"
@@ -197,6 +191,7 @@ class TestKillStaleDashboardProcesses:
]
run.assert_not_called()
+ @pytest.mark.windows_only
def test_hermes_pid_killed(self):
with self._patch_find(), mock.patch.object(
dashboard_procs.sys, "platform", "win32"
diff --git a/tests/hermes_cli/test_startup_fast_guards.py b/tests/hermes_cli/test_startup_fast_guards.py
index 25b9b79f91a..0ddd6c0e752 100644
--- a/tests/hermes_cli/test_startup_fast_guards.py
+++ b/tests/hermes_cli/test_startup_fast_guards.py
@@ -106,14 +106,6 @@ def _run_version(env_overrides: dict) -> subprocess.CompletedProcess:
)
-def test_fast_version_parity_off_termux(tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir()
- result = _run_version({"HERMES_HOME": str(home), "TERMUX_VERSION": ""})
- assert result.returncode == 0, result.stderr
- out = result.stdout
- for field in ("Hermes Agent v", "Install directory:", "Python:", "OpenAI SDK:"):
- assert field in out, f"fast --version output missing {field!r}:\n{out}"
def test_fast_version_parity_on_termux(tmp_path):
diff --git a/tests/hermes_cli/test_startup_plugin_gating.py b/tests/hermes_cli/test_startup_plugin_gating.py
index 64449a2c41b..99d6c6525be 100644
--- a/tests/hermes_cli/test_startup_plugin_gating.py
+++ b/tests/hermes_cli/test_startup_plugin_gating.py
@@ -6,130 +6,24 @@ This saves 500-650ms on ``hermes --help``, ``hermes --version``,
``hermes logs``, etc., by not importing ``google.cloud.pubsub_v1``,
``aiohttp``, ``grpc``, and friends.
-Two invariants:
-
-1. ``_BUILTIN_SUBCOMMANDS`` must contain every subcommand that is actually
- registered by ``main()``. If an entry is missing, plugin discovery
- runs unnecessarily for that command (correctness-safe, just slow).
- If an entry is PRESENT but the subcommand doesn't exist, a plugin
- could shadow the name — also bad.
-
-2. ``_plugin_cli_discovery_needed()`` returns the right answer for the
- flag/positional parsing cases it's meant to handle.
+Invariants: ``_plugin_cli_discovery_needed()`` classifies flag/positional argv
+correctly, and deferred platforms register their CLI command before argparse
+builds the plugin subparsers (issue #54678).
"""
from __future__ import annotations
-import io
-import re
import sys
-from contextlib import redirect_stdout
from unittest.mock import patch
-import pytest
-
-from hermes_cli._parser import build_top_level_parser, top_level_value_flag_sets
from hermes_cli.main import (
- _BUILTIN_SUBCOMMANDS,
- _first_positional_argv,
- _plugin_cli_discovery_needed,
_resolve_deferred_platform_cli_command,
)
-# ── helper: grab the live set of top-level subcommands from argparse ───────
-
-
-def _live_subcommand_names() -> set[str]:
- """Run ``hermes --help`` in-process and parse the subcommand block.
-
- We patch ``_plugin_cli_discovery_needed`` to always return False so
- plugin-registered commands aren't included — we're validating the
- built-in-only set.
- """
- from hermes_cli import main as _main
-
- argv_backup = sys.argv[:]
- sys.argv = ["hermes", "--help"]
- buf = io.StringIO()
- try:
- with patch.object(_main, "_plugin_cli_discovery_needed", return_value=False):
- with redirect_stdout(buf):
- with pytest.raises(SystemExit):
- _main.main()
- finally:
- sys.argv = argv_backup
-
- text = buf.getvalue()
- # argparse prints "{chat,model,...}" somewhere in the help output
- m = re.search(r"\{([a-zA-Z0-9_,\-]+)\}", text)
- assert m, f"Could not find subcommand group in --help output:\n{text[:500]}"
- return set(m.group(1).split(","))
-
-
-# ── _first_positional_argv ─────────────────────────────────────────────────
-
-
-def test_value_flag_sets_match_top_level_parser():
- required, optional = top_level_value_flag_sets()
-
- for action in build_top_level_parser()[0]._actions:
- if not action.option_strings or action.nargs == 0:
- continue
- expected = optional if action.nargs == "?" else required
- assert set(action.option_strings) <= expected
-
-
-def test_reasoning_value_is_not_misclassified_as_subcommand(monkeypatch):
- monkeypatch.setattr(
- sys,
- "argv",
- ["hermes", "--reasoning", "high", "chat", "hello"],
- )
-
- assert _first_positional_argv() == "chat"
- assert _plugin_cli_discovery_needed() is False
-
-
-
-
-# ── _plugin_cli_discovery_needed ───────────────────────────────────────────
-
-
-# ── _BUILTIN_SUBCOMMANDS ↔ argparse registration parity ────────────────────
-
-
-
-
# ── _resolve_deferred_platform_cli_command (issue #54678) ──────────────────
-def test_deferred_platform_cli_resolution_targets_matching_platform():
- """The slow path must import the deferred platform whose name matches the
- invoked command, so its register_cli_command side effect fires.
-
- Photon registers ``hermes photon`` only when its adapter module is
- imported; on the unknown-command slow path the platform is still a
- deferred entry, so without this resolution step the CLI command stays
- absent and argparse rejects ``photon`` (issue #54678).
- """
- from hermes_cli import main as _main
-
- class _FakeRegistry:
- def __init__(self):
- self.resolved: list[str] = []
-
- def get(self, name):
- self.resolved.append(name)
- return None
-
- fake = _FakeRegistry()
- fake_module = type(sys)("gateway.platform_registry")
- fake_module.platform_registry = fake
- with patch.dict(sys.modules, {"gateway.platform_registry": fake_module}):
- _resolve_deferred_platform_cli_command("photon")
-
- assert fake.resolved == ["photon"]
def test_deferred_platform_loader_registers_cli_command_before_parser_table():
diff --git a/tests/hermes_cli/test_status.py b/tests/hermes_cli/test_status.py
index b2e71073982..8d96d645489 100644
--- a/tests/hermes_cli/test_status.py
+++ b/tests/hermes_cli/test_status.py
@@ -54,9 +54,9 @@ def test_show_status_termux_gateway_section_skips_systemctl(monkeypatch, capsys,
status_mod.show_status(SimpleNamespace(all=False, deep=False))
output = capsys.readouterr().out
- assert "Manager: Termux / manual process" in output
- assert "Start with: hermes gateway" in output
assert "systemd (user)" not in output
+
+
def test_show_status_reports_vercel_backend_contract(monkeypatch, capsys, tmp_path):
from hermes_cli import status as status_mod
import hermes_cli.auth as auth_mod
@@ -78,14 +78,10 @@ def test_show_status_reports_vercel_backend_contract(monkeypatch, capsys, tmp_pa
status_mod.show_status(SimpleNamespace(all=False, deep=False))
output = capsys.readouterr().out
- assert "Backend: vercel_sandbox" in output
- assert "Runtime: python3.13" in output
- assert "Auth:" in output and "OIDC token via VERCEL_OIDC_TOKEN" in output
- assert "Auth detail: mode: OIDC" in output
- assert "Auth detail: active env: VERCEL_OIDC_TOKEN" in output
+ assert "vercel_sandbox" in output
+ assert "python3.13" in output
+ assert "VERCEL_OIDC_TOKEN" in output
assert "oidc-token" not in output
- assert "snapshot filesystem" in output
- assert "live processes do not survive" in output
# ---------------------------------------------------------------------------
@@ -133,19 +129,6 @@ class TestShowStatusXaiOAuth:
assert "Auth file: /home/u/.hermes/auth.json" in out
- def test_no_auth_store_line_when_field_absent(self, monkeypatch, capsys, tmp_path):
- """Auth file line must not appear when auth_store is missing."""
- import hermes_cli.auth as auth_mod
- status_mod = _base_xai_mocks(monkeypatch, tmp_path)
- monkeypatch.setattr(auth_mod, "get_xai_oauth_auth_status",
- lambda: {"logged_in": True},
- raising=False)
-
- status_mod.show_status(SimpleNamespace(all=False, deep=False))
- out = capsys.readouterr().out
-
- xai_section = out.split("xAI OAuth", 1)[1].split("◆", 1)[0]
- assert "Auth file:" not in xai_section
# ------------------------------------------------------------------
@@ -158,16 +141,6 @@ class TestShowStatusXaiOAuth:
# Resilience: import failure and runtime exception
# ------------------------------------------------------------------
- def test_import_failure_does_not_crash_show_status(self, monkeypatch, capsys, tmp_path):
- """show_status must complete even when get_xai_oauth_auth_status cannot be imported."""
- import hermes_cli.auth as auth_mod
- status_mod = _base_xai_mocks(monkeypatch, tmp_path)
- monkeypatch.delattr(auth_mod, "get_xai_oauth_auth_status", raising=False)
-
- status_mod.show_status(SimpleNamespace(all=False, deep=False))
- out = capsys.readouterr().out
-
- assert "◆ Auth Providers" in out
def test_import_failure_does_not_break_other_oauth_providers(self, monkeypatch, capsys, tmp_path):
"""Nous/Codex/MiniMax rows must still appear when xAI import fails."""
@@ -209,7 +182,6 @@ class TestShowStatusXaiOAuth:
out = capsys.readouterr().out
assert "xAI OAuth" in out
- assert "not logged in (run: hermes auth add xai-oauth)" in out
def test_show_status_reports_gateway_session_last_activity(monkeypatch, capsys, tmp_path):
diff --git a/tests/hermes_cli/test_steer_inline_repaint.py b/tests/hermes_cli/test_steer_inline_repaint.py
deleted file mode 100644
index 3d2fe3d7c1a..00000000000
--- a/tests/hermes_cli/test_steer_inline_repaint.py
+++ /dev/null
@@ -1,115 +0,0 @@
-"""Regression guard for issue #34569 — inline /steer (and /model) submit
-must repaint the input area after clearing the buffer.
-
-Mechanism of the bug
---------------------
-``handle_enter`` dispatches ``/steer`` (and ``/model``) inline on the UI
-thread while the agent is running. Those branches called
-``buffer.reset(append_to_history=True)`` but — unlike every *other*
-early-return branch in the handler — did NOT call ``event.app.invalidate()``.
-Because ``process_command()`` prints through ``patch_stdout`` (which scrolls
-output above the prompt and never triggers a prompt_toolkit redraw), the
-just-cleared input area could keep showing the submitted ``/steer <text>``
-until some unrelated redraw fired. The user saw their submitted text as if
-it were unsent and could accidentally re-submit it.
-
-This test pins the contract structurally: inside ``handle_enter``, any
-inline-command early-return that resets the buffer must be followed by an
-``event.app.invalidate()`` before its ``return``. It is an *invariant*
-(every reset-then-return repaints), not a snapshot of current source.
-"""
-
-from __future__ import annotations
-
-import ast
-from pathlib import Path
-
-
-ENTER_HANDLERS = ("_tui_handle_enter", "_tui_enter_inline_command", "_tui_enter_overlay",
- "_tui_enter_clarify_freetext", "_tui_enter_clarify_choice")
-
-
-def _load_handle_enter_node() -> ast.Module:
- """Return a synthetic module holding the Enter handler and its phase helpers."""
- cli_path = Path(__file__).resolve().parents[2] / "hermes_cli" / "cli_tui_mixin.py"
- tree = ast.parse(cli_path.read_text(encoding="utf-8"))
- found = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name in ENTER_HANDLERS]
- assert {n.name for n in found} == set(ENTER_HANDLERS), "Enter handlers not found in cli_tui_mixin.py"
- return ast.Module(body=found, type_ignores=[])
-
-
-def _is_buffer_reset(node: ast.stmt) -> bool:
- """True if the statement is ``...current_buffer.reset(...)``."""
- if not isinstance(node, ast.Expr):
- return False
- call = node.value
- if not isinstance(call, ast.Call):
- return False
- func = call.func
- return isinstance(func, ast.Attribute) and func.attr == "reset"
-
-
-def _is_invalidate(node: ast.stmt) -> bool:
- """True if the statement is ``event.app.invalidate()``."""
- if not isinstance(node, ast.Expr):
- return False
- call = node.value
- if not isinstance(call, ast.Call):
- return False
- func = call.func
- return isinstance(func, ast.Attribute) and func.attr == "invalidate"
-
-
-def _collect_reset_blocks(func: ast.AST) -> list[list[ast.stmt]]:
- """Find every statement sequence (a block body/orelse/finalbody) within
- ``handle_enter`` that contains a ``buffer.reset()`` call."""
- blocks: list[list[ast.stmt]] = []
- for node in ast.walk(func):
- for attr in ("body", "orelse", "finalbody"):
- seq = getattr(node, attr, None)
- if not isinstance(seq, list):
- continue
- if any(isinstance(s, ast.stmt) and _is_buffer_reset(s) for s in seq):
- blocks.append(seq)
- return blocks
-
-
-def test_inline_command_reset_branches_invalidate():
- """Every handle_enter branch that resets the buffer and then returns must
- invalidate the app first (issue #34569)."""
- func = _load_handle_enter_node()
- reset_blocks = _collect_reset_blocks(func)
-
- assert reset_blocks, "expected to find buffer.reset() calls in handle_enter"
-
- offenders = []
- for seq in reset_blocks:
- for i, stmt in enumerate(seq):
- if not _is_buffer_reset(stmt):
- continue
- # Find the next return after this reset in the same block.
- ret_idx = None
- for j in range(i + 1, len(seq)):
- if isinstance(seq[j], ast.Return):
- ret_idx = j
- break
- if ret_idx is None:
- # reset not directly followed by a return in this block
- # (e.g. the fall-through reset at the end of the handler) —
- # the next user input naturally repaints, so skip.
- continue
- between = seq[i + 1 : ret_idx]
- if not any(_is_invalidate(s) for s in between):
- offenders.append(ast.dump(stmt))
-
- assert not offenders, (
- "handle_enter has reset-then-return branch(es) that never call "
- "event.app.invalidate() — the input area can keep showing the "
- "submitted text (issue #34569). Offending reset stmts:\n"
- + "\n".join(offenders)
- )
-
-
-if __name__ == "__main__": # pragma: no cover
- test_inline_command_reset_branches_invalidate()
- print("ok")
diff --git a/tests/hermes_cli/test_stream_flush_left.py b/tests/hermes_cli/test_stream_flush_left.py
index c8a8df523d6..2e15cde304c 100644
--- a/tests/hermes_cli/test_stream_flush_left.py
+++ b/tests/hermes_cli/test_stream_flush_left.py
@@ -35,10 +35,6 @@ def cli_stub(monkeypatch):
return cli, emitted
-def test_stream_pad_is_empty():
- import cli as climod
-
- assert climod._STREAM_PAD == ""
def test_streamed_content_lines_have_no_leading_whitespace(cli_stub):
diff --git a/tests/hermes_cli/test_stt_picker.py b/tests/hermes_cli/test_stt_picker.py
index 5ba2d384061..7e7ef59eb72 100644
--- a/tests/hermes_cli/test_stt_picker.py
+++ b/tests/hermes_cli/test_stt_picker.py
@@ -6,17 +6,13 @@ and the faster_whisper post-setup readiness hook.
"""
import sys
-import types
from pathlib import Path
from unittest.mock import MagicMock, patch
-import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from hermes_cli.tools_config import ( # noqa: E402
- _CONFIG_ONLY_TOOLSETS,
- CONFIGURABLE_TOOLSETS,
STT_MODEL_CATALOG,
TOOL_CATEGORIES,
_checklist_toolset_keys,
@@ -35,23 +31,6 @@ def _stt_provider_named(name):
return next(p for p in _stt_cat()["providers"] if p["name"] == name)
-class TestSttCategory:
- def test_stt_category_exists(self):
- cat = _stt_cat()
- assert cat["name"] == "Speech-to-Text"
- assert len(cat["providers"]) >= 5
-
-
-
-
- def test_managed_row_shares_tts_coverage_category(self):
- from hermes_cli.nous_subscription import MANAGED_FEATURE_COVERAGE_CATEGORY
-
- managed = [p for p in _stt_cat()["providers"] if p.get("managed_nous_feature")]
- assert managed, "expected a Nous Subscription row"
- for p in managed:
- assert p["managed_nous_feature"] == "stt"
- assert MANAGED_FEATURE_COVERAGE_CATEGORY["stt"] == "openai-audio"
class TestConfigWrites:
@@ -109,8 +88,6 @@ class TestModelPicker:
class TestConfigOnlyExclusion:
- def test_stt_is_config_only(self):
- assert "stt" in _CONFIG_ONLY_TOOLSETS
def test_stt_excluded_from_checklist_universe(self):
assert "stt" not in _checklist_toolset_keys("cli")
@@ -118,8 +95,3 @@ class TestConfigOnlyExclusion:
assert "tts" in _checklist_toolset_keys("cli")
-class TestPostSetup:
- def test_faster_whisper_in_post_setup_ready(self):
- from hermes_cli.tools_config import _POST_SETUP_READY
-
- assert "faster_whisper" in _POST_SETUP_READY
diff --git a/tests/hermes_cli/test_subagent_dock_collapse.py b/tests/hermes_cli/test_subagent_dock_collapse.py
index 9e9093d58d9..5b2e89794fd 100644
--- a/tests/hermes_cli/test_subagent_dock_collapse.py
+++ b/tests/hermes_cli/test_subagent_dock_collapse.py
@@ -87,6 +87,6 @@ def test_collapsed_summary_prioritizes_live_count_and_controls_at_small_widths()
if width >= 24:
assert '6 live' in text and 'Ctrl+T' in text and 'F7' in text
if width >= 80:
- assert 'last: terminal' in text and 'Ctrl+T expand' in text and 'F7 restore' in text
+ assert 'last: terminal' in text
monitor.entries.clear()
assert monitor.dock_text(columns=80, rows=20) == ''
diff --git a/tests/hermes_cli/test_subcommands_batch.py b/tests/hermes_cli/test_subcommands_batch.py
index 5c4d57f1f3d..43dedb038e2 100644
--- a/tests/hermes_cli/test_subcommands_batch.py
+++ b/tests/hermes_cli/test_subcommands_batch.py
@@ -11,32 +11,10 @@ from __future__ import annotations
import argparse
-import pytest
-from hermes_cli.subcommands.auth import build_auth_parser
-from hermes_cli.subcommands.backup import build_backup_parser
from hermes_cli.subcommands.config import build_config_parser
-from hermes_cli.subcommands.dashboard import build_dashboard_parser
-from hermes_cli.subcommands.debug import build_debug_parser
-from hermes_cli.subcommands.doctor import build_doctor_parser
-from hermes_cli.subcommands.dump import build_dump_parser
-from hermes_cli.subcommands.gui import build_gui_parser
-from hermes_cli.subcommands.hooks import build_hooks_parser
-from hermes_cli.subcommands.import_cmd import build_import_cmd_parser
from hermes_cli.subcommands.login import build_login_parser
-from hermes_cli.subcommands.logout import build_logout_parser
-from hermes_cli.subcommands.logs import build_logs_parser
-from hermes_cli.subcommands.model import build_model_parser
-from hermes_cli.subcommands.prompt_size import build_prompt_size_parser
-from hermes_cli.subcommands.security import build_security_parser
-from hermes_cli.subcommands.setup import build_setup_parser
-from hermes_cli.subcommands.slack import build_slack_parser
-from hermes_cli.subcommands.status import build_status_parser
-from hermes_cli.subcommands.uninstall import build_uninstall_parser
-from hermes_cli.subcommands.update import build_update_parser
-from hermes_cli.subcommands.webhook import build_webhook_parser
-from hermes_cli.subcommands.whatsapp import build_whatsapp_parser
def _h(name):
@@ -46,32 +24,6 @@ def _h(name):
return handler
-# (subcommand_name, builder, handler_kwargs, sample_argv)
-SINGLE_HANDLER_CASES = [
- ("model", build_model_parser, "cmd_model", ["model"]),
- ("setup", build_setup_parser, "cmd_setup", ["setup"]),
-
- ("whatsapp", build_whatsapp_parser, "cmd_whatsapp", ["whatsapp"]),
- ("slack", build_slack_parser, "cmd_slack", ["slack"]),
- ("login", build_login_parser, "cmd_login", ["login"]),
- ("logout", build_logout_parser, "cmd_logout", ["logout"]),
- ("auth", build_auth_parser, "cmd_auth", ["auth"]),
- ("status", build_status_parser, "cmd_status", ["status"]),
- ("webhook", build_webhook_parser, "cmd_webhook", ["webhook"]),
- ("hooks", build_hooks_parser, "cmd_hooks", ["hooks"]),
- ("doctor", build_doctor_parser, "cmd_doctor", ["doctor"]),
- ("security", build_security_parser, "cmd_security", ["security"]),
- ("dump", build_dump_parser, "cmd_dump", ["dump"]),
- ("debug", build_debug_parser, "cmd_debug", ["debug"]),
- ("backup", build_backup_parser, "cmd_backup", ["backup"]),
- ("import", build_import_cmd_parser, "cmd_import", ["import", "/tmp/x.zip"]),
- ("config", build_config_parser, "cmd_config", ["config"]),
- ("update", build_update_parser, "cmd_update", ["update"]),
- ("uninstall", build_uninstall_parser, "cmd_uninstall", ["uninstall"]),
- ("gui", build_gui_parser, "cmd_gui", ["gui"]),
- ("logs", build_logs_parser, "cmd_logs", ["logs"]),
- ("prompt-size", build_prompt_size_parser, "cmd_prompt_size", ["prompt-size"]),
-]
@@ -108,11 +60,6 @@ def test_config_get_unset_subcommands_parse():
# 2. The subcommand must not advertise itself in the parser help row.
-def _login_parser():
- parser = argparse.ArgumentParser(prog="hermes")
- sub = parser.add_subparsers(dest="command")
- build_login_parser(sub, cmd_login=_h("login"))
- return parser
@@ -128,7 +75,5 @@ def test_login_subparser_help_is_suppressed():
sub = parser.add_subparsers(dest="command")
build_login_parser(sub, cmd_login=_h("login"))
help_text = parser.format_help()
- # The misleading old help string must be gone from the top-level usage.
- assert "Authenticate with an inference provider" not in help_text
- # And no leaked SUPPRESS placeholder row.
+ # No leaked SUPPRESS placeholder row.
assert "==SUPPRESS==" not in help_text
diff --git a/tests/hermes_cli/test_subcommands_final_batch.py b/tests/hermes_cli/test_subcommands_final_batch.py
index 48ffb72f6ce..c805f3b939f 100644
--- a/tests/hermes_cli/test_subcommands_final_batch.py
+++ b/tests/hermes_cli/test_subcommands_final_batch.py
@@ -12,23 +12,8 @@ from __future__ import annotations
import argparse
-import pytest
-from hermes_cli.subcommands.browser import build_browser_parser
-from hermes_cli.subcommands.bundles import build_bundles_parser
-from hermes_cli.subcommands.checkpoints import build_checkpoints_parser
-from hermes_cli.subcommands.completion import build_completion_parser
from hermes_cli.subcommands.computer_use import build_computer_use_parser
-from hermes_cli.subcommands.curator import build_curator_parser
-from hermes_cli.subcommands.egress import build_egress_parser
-from hermes_cli.subcommands.fallback import build_fallback_parser
-from hermes_cli.subcommands.journey import build_journey_parser
-from hermes_cli.subcommands.migrate import build_migrate_parser
-from hermes_cli.subcommands.moa import build_moa_parser
-from hermes_cli.subcommands.pets import build_pets_parser
-from hermes_cli.subcommands.secrets import build_secrets_parser
-from hermes_cli.subcommands.sessions import build_sessions_parser
-from hermes_cli.subcommands.whatsapp import build_whatsapp_cloud_parser
from hermes_cli.subcommands.worktree import build_worktree_parser
@@ -37,30 +22,8 @@ def _tree():
return parser, parser.add_subparsers(dest="command")
-SELF_CONTAINED = [
- ("moa", build_moa_parser, ["moa", "list"]),
- ("fallback", build_fallback_parser, ["fallback", "add"]),
- ("worktree", build_worktree_parser, ["worktree", "prune", "--dry-run"]),
- ("browser", build_browser_parser, ["browser", "close-profile"]),
- ("secrets", build_secrets_parser, ["secrets"]),
- ("egress", build_egress_parser, ["egress"]),
- ("migrate", build_migrate_parser, ["migrate", "xai", "--apply"]),
- ("checkpoints", build_checkpoints_parser, ["checkpoints"]),
- ("bundles", build_bundles_parser, ["bundles"]),
- ("curator", build_curator_parser, ["curator"]),
- ("pets", build_pets_parser, ["pets"]),
- ("journey", build_journey_parser, ["journey"]),
- ("computer-use", build_computer_use_parser, ["computer-use", "status"]),
-]
-
-
[email protected]("name,builder,argv", SELF_CONTAINED, ids=[c[0] for c in SELF_CONTAINED])
-def test_self_contained_builders_attach(name, builder, argv):
- parser, sub = _tree()
- builder(sub)
- ns = parser.parse_args(argv)
- assert ns.command == name
- assert callable(getattr(ns, "func", None)) or name in ("checkpoints", "curator", "pets", "journey")
+
+
def test_worktree_aliases_normalize_to_list(monkeypatch):
@@ -73,32 +36,10 @@ def test_worktree_aliases_normalize_to_list(monkeypatch):
assert seen["action"] == "list"
-def test_sessions_injects_handler_and_threads_parser():
- parser, sub = _tree()
- calls = []
- build_sessions_parser(sub, cmd_sessions=lambda a, **kw: calls.append((a, kw)) or 0)
- ns = parser.parse_args(["sessions", "prune", "--older-than", "2d", "--dry-run"])
- assert ns.sessions_action == "prune" and ns.older_than == "2d" and ns.dry_run is True
- assert ns.func(ns) == 0
- (a, kw), = calls
- assert a is ns
- assert kw["sessions_parser"].prog.endswith("sessions")
-def test_completion_passes_top_level_parser():
- parser, sub = _tree()
- got = {}
- build_completion_parser(sub, cmd_completion=lambda a, p: got.update(a=a, p=p), parser=parser)
- ns = parser.parse_args(["completion", "zsh"])
- ns.func(ns)
- assert got["p"] is parser and got["a"].shell == "zsh"
-def test_whatsapp_cloud_dispatch():
- parser, sub = _tree()
- h = lambda a: "wa" # noqa: E731
- build_whatsapp_cloud_parser(sub, cmd_whatsapp_cloud=h)
- assert parser.parse_args(["whatsapp-cloud"]).func is h
def test_computer_use_no_action_prints_help(capsys):
diff --git a/tests/hermes_cli/test_subcommands_followup.py b/tests/hermes_cli/test_subcommands_followup.py
index 9d65978762a..b5d39d39483 100644
--- a/tests/hermes_cli/test_subcommands_followup.py
+++ b/tests/hermes_cli/test_subcommands_followup.py
@@ -10,17 +10,9 @@ from __future__ import annotations
import argparse
-import pytest
from hermes_cli.subcommands.acp import build_acp_parser
-from hermes_cli.subcommands.claw import build_claw_parser
-from hermes_cli.subcommands.insights import build_insights_parser
from hermes_cli.subcommands.mcp import build_mcp_parser
-from hermes_cli.subcommands.memory import build_memory_parser
-from hermes_cli.subcommands.pairing import build_pairing_parser
-from hermes_cli.subcommands.plugins import build_plugins_parser
-from hermes_cli.subcommands.skills import build_skills_parser
-from hermes_cli.subcommands.tools import build_tools_parser
def _h(name):
@@ -30,29 +22,8 @@ def _h(name):
return handler
-# (subcommand, builder, handler_kwarg, sample argv that should dispatch to func)
-CASES = [
- ("memory", build_memory_parser, "cmd_memory", ["memory"]),
- ("acp", build_acp_parser, "cmd_acp", ["acp"]),
- ("tools", build_tools_parser, "cmd_tools", ["tools"]),
- ("insights", build_insights_parser, "cmd_insights", ["insights"]),
- ("skills", build_skills_parser, "cmd_skills", ["skills"]),
- ("pairing", build_pairing_parser, "cmd_pairing", ["pairing"]),
- ("plugins", build_plugins_parser, "cmd_plugins", ["plugins"]),
- ("mcp", build_mcp_parser, "cmd_mcp", ["mcp"]),
- ("claw", build_claw_parser, "cmd_claw", ["claw"]),
-]
[email protected]("name,builder,kw,argv", CASES, ids=[c[0] for c in CASES])
-def test_followup_builders_dispatch(name, builder, kw, argv):
- parser = argparse.ArgumentParser(prog="hermes")
- sub = parser.add_subparsers(dest="command")
- handler = _h(name)
- builder(sub, **{kw: handler})
- ns = parser.parse_args(argv)
- assert ns.command == name
- assert ns.func is handler
def test_mcp_and_acp_accept_hooks_flag():
diff --git a/tests/hermes_cli/test_subcommands_profile_gateway.py b/tests/hermes_cli/test_subcommands_profile_gateway.py
index bca73e49c6c..7ed061b6037 100644
--- a/tests/hermes_cli/test_subcommands_profile_gateway.py
+++ b/tests/hermes_cli/test_subcommands_profile_gateway.py
@@ -9,7 +9,6 @@ from __future__ import annotations
import argparse
from hermes_cli.subcommands.gateway import build_gateway_parser
-from hermes_cli.subcommands.profile import build_profile_parser
def _h_gateway(args): # pragma: no cover - identity only
@@ -24,15 +23,8 @@ def _h_gateway_enroll(args): # pragma: no cover - identity only
return "gateway_enroll"
-def _h_profile(args): # pragma: no cover - identity only
- return "profile"
-def _profile_parser():
- p = argparse.ArgumentParser(prog="hermes")
- sub = p.add_subparsers(dest="command")
- build_profile_parser(sub, cmd_profile=_h_profile)
- return p
def _gateway_parser():
@@ -51,14 +43,6 @@ def _gateway_parser():
-def test_gateway_and_proxy_dispatch():
- p = _gateway_parser()
- gw = p.parse_args(["gateway", "run"])
- assert gw.command == "gateway"
- assert gw.func is _h_gateway
- px = p.parse_args(["proxy"])
- assert px.command == "proxy"
- assert px.func is _h_proxy
diff --git a/tests/hermes_cli/test_subparser_routing_fallback.py b/tests/hermes_cli/test_subparser_routing_fallback.py
deleted file mode 100644
index 29c9b6a4b14..00000000000
--- a/tests/hermes_cli/test_subparser_routing_fallback.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""Tests for the defensive subparser routing workaround (bpo-9338).
-
-The main() function in hermes_cli/main.py sets subparsers.required=True
-when argv contains a known subcommand name. This forces deterministic
-routing on Python versions where argparse fails to match subcommand tokens
-when the parent parser has nargs='?' optional arguments (--continue).
-
-If the subcommand token is consumed as a flag value (e.g. `hermes -c model`
-to resume a session named 'model'), the required=True parse raises
-SystemExit and the code falls back to the default required=False behaviour.
-"""
-import argparse
-import io
-import sys
-
-
-
-def _build_parser():
- """Build a minimal replica of the hermes top-level parser."""
- parser = argparse.ArgumentParser(prog="hermes")
- parser.add_argument("--version", "-V", action="store_true")
- parser.add_argument("--resume", "-r", metavar="SESSION", default=None)
- parser.add_argument(
- "--continue", "-c",
- dest="continue_last",
- nargs="?",
- const=True,
- default=None,
- metavar="SESSION_NAME",
- )
- parser.add_argument("--worktree", "-w", action="store_true", default=False)
- parser.add_argument("--skills", "-s", action="append", default=None)
- parser.add_argument("--yolo", action="store_true", default=False)
- parser.add_argument("--pass-session-id", action="store_true", default=False)
-
- subparsers = parser.add_subparsers(dest="command", help="Command to run")
- chat_p = subparsers.add_parser("chat")
- chat_p.add_argument("-q", "--query", default=None)
- subparsers.add_parser("model")
- subparsers.add_parser("gateway")
- subparsers.add_parser("setup")
- return parser, subparsers
-
-
-def _safe_parse(parser, subparsers, argv):
- """Replica of the defensive parsing logic from main()."""
- known_cmds = set(subparsers.choices.keys()) if hasattr(subparsers, "choices") else set()
- has_cmd_token = any(t in known_cmds for t in argv if not t.startswith("-"))
-
- if has_cmd_token:
- subparsers.required = True
- saved_stderr = sys.stderr
- try:
- sys.stderr = io.StringIO()
- args = parser.parse_args(argv)
- sys.stderr = saved_stderr
- return args
- except SystemExit:
- sys.stderr = saved_stderr
- subparsers.required = False
- return parser.parse_args(argv)
- else:
- subparsers.required = False
- return parser.parse_args(argv)
-
diff --git a/tests/hermes_cli/test_subprocess_timeouts.py b/tests/hermes_cli/test_subprocess_timeouts.py
deleted file mode 100644
index 47146aac444..00000000000
--- a/tests/hermes_cli/test_subprocess_timeouts.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""Tests for subprocess.run() timeout coverage in CLI utilities."""
-import ast
-from pathlib import Path
-
-import pytest
-
-
-# Parameterise over every CLI module that calls subprocess.run
-_CLI_MODULES = [
- "hermes_cli/doctor.py",
- "hermes_cli/status.py",
- "hermes_cli/clipboard.py",
- "hermes_cli/banner.py",
-]
-
-
-def _subprocess_run_calls(filepath: str) -> list[dict]:
- """Parse a Python file and return info about subprocess.run() calls."""
- source = Path(filepath).read_text()
- tree = ast.parse(source, filename=filepath)
- calls = []
- for node in ast.walk(tree):
- if not isinstance(node, ast.Call):
- continue
- func = node.func
- if (isinstance(func, ast.Attribute) and func.attr == "run"
- and isinstance(func.value, ast.Name)
- and func.value.id == "subprocess"):
- has_timeout = any(kw.arg == "timeout" for kw in node.keywords)
- calls.append({"line": node.lineno, "has_timeout": has_timeout})
- return calls
-
-
[email protected]("filepath", _CLI_MODULES)
-def test_all_subprocess_run_calls_have_timeout(filepath):
- """Every subprocess.run() call in CLI modules must specify a timeout."""
- if not Path(filepath).exists():
- pytest.skip(f"{filepath} not found")
- calls = _subprocess_run_calls(filepath)
- missing = [c for c in calls if not c["has_timeout"]]
- assert not missing, (
- f"{filepath} has subprocess.run() without timeout at "
- f"line(s): {[c['line'] for c in missing]}"
- )
diff --git a/tests/hermes_cli/test_subscription_cli.py b/tests/hermes_cli/test_subscription_cli.py
index b5098f5c6f7..6e9ea168129 100644
--- a/tests/hermes_cli/test_subscription_cli.py
+++ b/tests/hermes_cli/test_subscription_cli.py
@@ -110,7 +110,6 @@ def test_free_prints_catalog_and_deep_links_with_plan(cli, monkeypatch, capsys):
out = capsys.readouterr().out
# Catalog rows — monthly credits render as DOLLARS ($22 credits/mo), never bare.
- assert "Choose a plan" in out
assert "Plus · $20/mo · $22 credits/mo" in out
assert "Ultra · $200/mo · $220 credits/mo" in out
# Free (tier_order 0) is excluded from the paid catalog rows.
@@ -119,7 +118,6 @@ def test_free_prints_catalog_and_deep_links_with_plan(cli, monkeypatch, capsys):
# carries plan=<picked tier>, org_id first, plan second.
assert opened.get("url") == "https://portal.example/manage-subscription?org_id=org_1&plan=plus"
assert "/manage-subscription?org_id=org_1&plan=plus" in out
- assert "start Plus" in out
@@ -193,4 +191,4 @@ def test_upgrade_confirm_names_the_subscription_card(cli, monkeypatch, capsys):
cli._show_subscription()
out = capsys.readouterr().out
- assert "Visa ····4242 — the card on your subscription — will be charged." in out
+ assert "Visa ····4242" in out
diff --git a/tests/hermes_cli/test_suppress_eio_on_interrupt.py b/tests/hermes_cli/test_suppress_eio_on_interrupt.py
deleted file mode 100644
index bc19fef9003..00000000000
--- a/tests/hermes_cli/test_suppress_eio_on_interrupt.py
+++ /dev/null
@@ -1,171 +0,0 @@
-"""Tests for OSError EIO suppression during interrupt shutdown (#13710).
-
-When the user interrupts a running task, prompt_toolkit tries to flush
-stdout during emergency shutdown. If stdout is already in a broken state
-(redirected to /dev/null, pipe closed, etc.), the flush raises
-``OSError: [Errno 5] Input/output error``.
-
-The ``_suppress_closed_loop_errors`` asyncio exception handler and the
-outer ``except (KeyError, OSError)`` block must both suppress this error
-to prevent a hard crash.
-"""
-
-from __future__ import annotations
-
-import errno
-from unittest.mock import MagicMock
-
-import pytest
-
-
-# ---------------------------------------------------------------------------
-# _suppress_closed_loop_errors – asyncio exception handler
-# ---------------------------------------------------------------------------
-
-def _make_suppress_fn():
- """Build a standalone copy of ``_suppress_closed_loop_errors``.
-
- The real function is defined as a closure inside
- ``CLI._run_interactive``; we reconstruct an equivalent here so the
- unit tests don't need a full CLI instance.
- """
- def _suppress_closed_loop_errors(loop, context):
- exc = context.get("exception")
- if isinstance(exc, RuntimeError) and "Event loop is closed" in str(exc):
- return
- if isinstance(exc, KeyError) and "is not registered" in str(exc):
- return
- if isinstance(exc, OSError) and getattr(exc, "errno", None) == errno.EIO:
- return
- loop.default_exception_handler(context)
- return _suppress_closed_loop_errors
-
-
-class TestSuppressClosedLoopErrors:
- """Verify the asyncio exception handler suppresses expected errors."""
-
- def test_suppresses_event_loop_closed(self):
- handler = _make_suppress_fn()
- loop = MagicMock()
- handler(loop, {"exception": RuntimeError("Event loop is closed")})
- loop.default_exception_handler.assert_not_called()
-
-
- def test_does_not_suppress_oserror_other_errno(self):
- """OSError with a different errno must still propagate."""
- handler = _make_suppress_fn()
- loop = MagicMock()
- exc = OSError(errno.EACCES, "Permission denied")
- handler(loop, {"exception": exc})
- loop.default_exception_handler.assert_called_once()
-
-
- def test_no_exception_key(self):
- """Context without 'exception' must propagate to default handler."""
- handler = _make_suppress_fn()
- loop = MagicMock()
- handler(loop, {"message": "some log"})
- loop.default_exception_handler.assert_called_once()
-
-
-# ---------------------------------------------------------------------------
-# Outer except block – EIO handling
-# ---------------------------------------------------------------------------
-
-class TestOuterExceptEIO:
- """Verify the outer ``except (KeyError, OSError)`` block logic."""
-
- def test_eio_does_not_reraise(self):
- """OSError with errno.EIO should be silently suppressed."""
- exc = OSError(errno.EIO, "Input/output error")
- # Simulate the condition check from the outer except block:
- assert isinstance(exc, OSError)
- assert getattr(exc, "errno", None) == errno.EIO
-
-
- def test_other_oserror_reraises(self):
- """Other OSError variants must not match the EIO guard."""
- exc = OSError(errno.EACCES, "Permission denied")
- assert not (getattr(exc, "errno", None) == errno.EIO)
- assert "is not registered" not in str(exc)
- assert "Bad file descriptor" not in str(exc)
-
-
-# ---------------------------------------------------------------------------
-# Signal handler – guarded logger.debug (#13710 regression)
-# ---------------------------------------------------------------------------
-#
-# CPython's logging module is not reentrant-safe. ``Logger.isEnabledFor``
-# caches level results in ``Logger._cache``; under shutdown races the cache
-# can be cleared (``Logger._clear_cache``) or mid-mutation when the signal
-# fires, raising ``KeyError: <level_int>`` (e.g. ``KeyError: 10`` for DEBUG)
-# from inside the handler. If that KeyError escapes, it bypasses the
-# ``raise KeyboardInterrupt()`` on the next line, which in turn bypasses
-# prompt_toolkit's normal interrupt unwind and surfaces as the EIO cascade
-# from #13710.
-#
-# The fix: wrap the ``logger.debug`` call in the signal handler in a bare
-# ``try/except Exception: pass`` so logging can never raise through it.
-#
-# These tests verify the contract: the handler must raise KeyboardInterrupt
-# (and nothing else) regardless of whether logger.debug succeeds or blows up.
-
-
-def _make_signal_handler(logger, agent_state):
- """Build a standalone copy of ``_signal_handler``.
-
- The real handler is defined as a closure inside ``CLI._run_interactive``;
- we reconstruct an equivalent here so the unit tests don't need a full
- CLI instance. Mirrors cli.py:_signal_handler as of #13710 regression
- fix — guarded logger.debug + agent interrupt + KeyboardInterrupt.
- """
- def _signal_handler(signum, frame):
- # Guarded: logging must never raise through a signal handler.
- try:
- logger.debug("Received signal %s, triggering graceful shutdown", signum)
- except Exception:
- pass # never let logging raise from a signal handler (#13710 regression)
- try:
- if agent_state.get("agent") and agent_state.get("running"):
- agent_state["agent"].interrupt(f"received signal {signum}")
- except Exception:
- pass # never block signal handling
- raise KeyboardInterrupt()
- return _signal_handler
-
-
-class TestSignalHandlerLoggingRace:
- """#13710 regression — logger.debug in signal handler must not escape.
-
- If the DEBUG-level ``logging._cache`` lookup races with a concurrent
- ``_clear_cache`` (e.g. from another thread reconfiguring logging during
- shutdown), ``logger.debug`` can raise ``KeyError: 10``. The signal
- handler must swallow that and still raise KeyboardInterrupt.
- """
-
- def test_keyboard_interrupt_raised_on_normal_path(self):
- """Sanity: handler raises KeyboardInterrupt when logging works."""
- logger = MagicMock()
- handler = _make_signal_handler(logger, {})
- with pytest.raises(KeyboardInterrupt):
- handler(15, None) # SIGTERM
- logger.debug.assert_called_once()
-
- def test_keyboard_interrupt_raised_when_logger_raises_keyerror(self):
- """logger.debug raising KeyError(10) must not escape — KeyboardInterrupt wins.
-
- This is the exact failure signature from the #13710 regression: the
- CPython 3.11 ``Logger._cache[level]`` race surfaces as KeyError on
- the integer level value, and previously propagated out of the
- signal handler before the ``raise KeyboardInterrupt()`` could fire.
- """
- logger = MagicMock()
- logger.debug.side_effect = KeyError(10) # DEBUG level int
- handler = _make_signal_handler(logger, {})
- # Must still raise KeyboardInterrupt, NOT KeyError.
- with pytest.raises(KeyboardInterrupt):
- handler(15, None)
-
-
-
-
diff --git a/tests/hermes_cli/test_systemd_optional_directives.py b/tests/hermes_cli/test_systemd_optional_directives.py
index c0d6d4c0458..33c93431b9c 100644
--- a/tests/hermes_cli/test_systemd_optional_directives.py
+++ b/tests/hermes_cli/test_systemd_optional_directives.py
@@ -12,7 +12,6 @@ from both the installed and expected text before comparison.
from __future__ import annotations
-import pytest
# ---------------------------------------------------------------------------
@@ -39,57 +38,6 @@ RestartSteps=5
- def test_full_unit_comparison(self):
- """Simulate the full stale-check flow with an older systemd unit."""
- from hermes_cli.gateway import (
- _normalize_service_definition,
- _strip_optional_systemd_directives,
- )
- # What the installed unit looks like on older systemd (directives stripped)
- installed = """[Unit]
-Description=Hermes Gateway
-After=network-online.target
-
-[Service]
-Type=simple
-ExecStart=/usr/bin/python -m hermes_cli.main gateway run
-Restart=always
-RestartSec=5
-KillMode=mixed
-KillSignal=SIGTERM
-
-[Install]
-WantedBy=default.target
-"""
- # What generate_systemd_unit produces (with the directives)
- expected = """[Unit]
-Description=Hermes Gateway
-After=network-online.target
-
-[Service]
-Type=simple
-ExecStart=/usr/bin/python -m hermes_cli.main gateway run
-Restart=always
-RestartSec=5
-RestartMaxDelaySec=300
-RestartSteps=5
-KillMode=mixed
-KillSignal=SIGTERM
-
-[Install]
-WantedBy=default.target
-"""
- # Without normalization, they differ
- assert _normalize_service_definition(installed) != _normalize_service_definition(expected)
-
- # With optional-directive stripping, they match
- norm_installed = _normalize_service_definition(
- _strip_optional_systemd_directives(installed)
- )
- norm_expected = _normalize_service_definition(
- _strip_optional_systemd_directives(expected)
- )
- assert norm_installed == norm_expected
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_telegram_managed_bot.py b/tests/hermes_cli/test_telegram_managed_bot.py
index 2352a6dcce9..623e85d8d84 100644
--- a/tests/hermes_cli/test_telegram_managed_bot.py
+++ b/tests/hermes_cli/test_telegram_managed_bot.py
@@ -11,7 +11,6 @@ from hermes_cli.telegram_managed_bot import (
create_pairing,
poll_for_setup_result,
print_qr_code,
- render_qr_terminal,
)
from hermes_cli import setup_platforms
@@ -21,15 +20,7 @@ SECOND_VALID_TOKEN = "987654321:abcdefghijklmnopqrstuvwxyzABCDEF"
class TestQRCode:
- def test_render_returns_string(self):
- result = render_qr_terminal("https://example.com")
- if result:
- assert isinstance(result, str)
- assert len(result) > 10
- def test_render_graceful_without_qrcode(self):
- with patch.dict("sys.modules", {"qrcode": None}):
- render_qr_terminal("https://example.com")
def test_print_qr_code_with_url(self, capsys):
print_qr_code("https://t.me/newbot/Bot/test_bot")
diff --git a/tests/hermes_cli/test_tencent_tokenhub_provider.py b/tests/hermes_cli/test_tencent_tokenhub_provider.py
index 0d19908ec36..542ec4c7404 100644
--- a/tests/hermes_cli/test_tencent_tokenhub_provider.py
+++ b/tests/hermes_cli/test_tencent_tokenhub_provider.py
@@ -1,7 +1,5 @@
"""Tests for Tencent TokenHub provider support (Hy4 preview)."""
-import json
-import os
import pytest
@@ -30,15 +28,6 @@ _OTHER_PROVIDER_KEYS = (
# =============================================================================
-class TestTencentTokenhubProviderRegistry:
- """Verify tencent-tokenhub is registered correctly in the PROVIDER_REGISTRY."""
-
- def test_registered(self):
- assert "tencent-tokenhub" in PROVIDER_REGISTRY
-
-
- def test_inference_base_url(self):
- assert PROVIDER_REGISTRY["tencent-tokenhub"].inference_base_url == "https://tokenhub.tencentmaas.com/v1"
# =============================================================================
@@ -95,7 +84,7 @@ class TestTencentTokenhubCredentials:
monkeypatch.delenv("TOKENHUB_BASE_URL", raising=False)
creds = resolve_api_key_provider_credentials("tencent-tokenhub")
assert creds["api_key"] == "sk-test-12345678"
- assert creds["base_url"] == "https://tokenhub.tencentmaas.com/v1"
+ assert creds["base_url"] == PROVIDER_REGISTRY["tencent-tokenhub"].inference_base_url
def test_openrouter_key_does_not_make_tokenhub_configured(self, monkeypatch):
"""OpenRouter users should NOT see tencent-tokenhub as configured."""
@@ -111,18 +100,6 @@ class TestTencentTokenhubCredentials:
# =============================================================================
-class TestTencentTokenhubModelCatalog:
- """Tencent TokenHub static model list."""
-
- def test_static_model_list_exists(self):
- from hermes_cli.models import _PROVIDER_MODELS
- assert "tencent-tokenhub" in _PROVIDER_MODELS
- assert len(_PROVIDER_MODELS["tencent-tokenhub"]) >= 1
-
-
- def test_default_model(self):
- from hermes_cli.models import get_default_model_for_provider
- assert get_default_model_for_provider("tencent-tokenhub") == "hy4-preview"
# =============================================================================
@@ -130,14 +107,6 @@ class TestTencentTokenhubModelCatalog:
# =============================================================================
-class TestTencentTokenhubCanonicalProvider:
- """Tencent TokenHub appears in the interactive model picker."""
-
-
- def test_description_contains_hy4(self):
- from hermes_cli.models import CANONICAL_PROVIDERS
- entry = next(p for p in CANONICAL_PROVIDERS if p.slug == "tencent-tokenhub")
- assert "Hy4 preview" in entry.tui_desc
# =============================================================================
@@ -158,17 +127,7 @@ class TestTencentTokenhubNormalization:
"""
- def test_not_in_matching_prefix_strip_set(self):
- """tencent-tokenhub does NOT need prefix stripping — its models
- (hy4-preview, hy3-preview, hy3) are used as-is and users won't
- copy vendor/ form."""
- from hermes_cli.model_normalize import _MATCHING_PREFIX_STRIP_PROVIDERS
- assert "tencent-tokenhub" not in _MATCHING_PREFIX_STRIP_PROVIDERS
- def test_not_in_lowercase_providers(self):
- """tencent-tokenhub does not require lowercase normalization."""
- from hermes_cli.model_normalize import _LOWERCASE_MODEL_PROVIDERS
- assert "tencent-tokenhub" not in _LOWERCASE_MODEL_PROVIDERS
@pytest.mark.parametrize("empty_input", ["", None, " "])
def test_normalize_empty_and_none(self, empty_input):
@@ -219,33 +178,6 @@ class TestTencentTokenhubContextLength:
# =============================================================================
-class TestTencentTokenhubProvidersModule:
- """Test Tencent TokenHub in the unified providers module."""
-
- def test_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
- assert "tencent-tokenhub" in HERMES_OVERLAYS
- overlay = HERMES_OVERLAYS["tencent-tokenhub"]
- assert overlay.transport == "openai_chat"
- assert overlay.base_url_env_var == "TOKENHUB_BASE_URL"
- assert not overlay.is_aggregator
-
- def test_alias_resolves(self):
- from hermes_cli.providers import normalize_provider
- assert normalize_provider("tencent") == "tencent-tokenhub"
- assert normalize_provider("tokenhub") == "tencent-tokenhub"
-
-
- def test_get_provider(self):
- pdef = None
- try:
- from hermes_cli.providers import get_provider
- pdef = get_provider("tencent-tokenhub")
- except Exception:
- pass
- if pdef is not None:
- assert pdef.id == "tencent-tokenhub"
- assert pdef.transport == "openai_chat"
# =============================================================================
@@ -267,19 +199,6 @@ class TestTencentTokenhubProvidersModule:
# =============================================================================
-class TestTencentTokenhubAgentInit:
- """Verify the agent can be constructed with tencent-tokenhub provider without errors."""
-
- def test_no_syntax_errors(self):
- """Importing run_agent with tencent-tokenhub 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["tencent-tokenhub"]
- api_mode = TRANSPORT_TO_API_MODE[overlay.transport]
- assert api_mode == "chat_completions"
# =============================================================================
@@ -294,37 +213,6 @@ class TestTencentTokenhubAgentInit:
# =============================================================================
-class TestTencentTokenhubModelCatalogJSON:
- """Verify tencent/hy3 is present in the website model-catalog.json.
-
- tencent/hy3:free was delisted 2026-08-21 — the slug vanished from
- OpenRouter's live catalog (free promo rotated out), so the paid hy3
- entry is the surviving assertion target.
- """
-
- def test_in_model_catalog_json(self):
- catalog_path = os.path.join(
- os.path.dirname(__file__),
- "..", "..",
- "website", "static", "api", "model-catalog.json",
- )
- if not os.path.isfile(catalog_path):
- pytest.skip("model-catalog.json not found in workspace")
- with open(catalog_path) as f:
- data = json.load(f)
- # Collect all model IDs across all provider lists.
- # providers is a dict keyed by provider name, each value has a "models" list.
- all_ids = set()
- providers = data.get("providers", {})
- if isinstance(providers, dict):
- for provider_entry in providers.values():
- for model in provider_entry.get("models", []):
- all_ids.add(model.get("id", ""))
- else:
- for provider_entry in providers:
- for model in provider_entry.get("models", []):
- all_ids.add(model.get("id", ""))
- assert "tencent/hy3" in all_ids
# =============================================================================
@@ -347,16 +235,4 @@ class TestTencentTokenhubApiMode:
# =============================================================================
-class TestTencentTokenhubKnownProviderNames:
- """Verify tencent-tokenhub and its aliases are recognized as valid
- provider names for the ``provider:model`` syntax.
- """
-
-
- @pytest.mark.parametrize("alias", [
- "tencent", "tokenhub", "tencent-cloud", "tencentmaas",
- ])
- def test_alias_known(self, alias):
- from hermes_cli.models import _KNOWN_PROVIDER_NAMES
- assert alias in _KNOWN_PROVIDER_NAMES
diff --git a/tests/hermes_cli/test_terminal_breadcrumbs.py b/tests/hermes_cli/test_terminal_breadcrumbs.py
index caeeb4cd738..da3992a5dab 100644
--- a/tests/hermes_cli/test_terminal_breadcrumbs.py
+++ b/tests/hermes_cli/test_terminal_breadcrumbs.py
@@ -197,8 +197,3 @@ def test_config_gate_off_disables_writes_and_resolution(
assert tb.resolve_breadcrumb_session() is None
-def test_config_gate_default_is_enabled(monkeypatch):
- import hermes_cli.config as config_mod
-
- monkeypatch.setattr(config_mod, "load_config", lambda: {})
- assert tb.is_enabled() is True
diff --git a/tests/hermes_cli/test_terminal_interrupt_recovery.py b/tests/hermes_cli/test_terminal_interrupt_recovery.py
index d0b7448f07e..2b008c97f1a 100644
--- a/tests/hermes_cli/test_terminal_interrupt_recovery.py
+++ b/tests/hermes_cli/test_terminal_interrupt_recovery.py
@@ -12,18 +12,13 @@ which is invoked from ``process_loop``'s ``finally`` block only when
1. Drain stray escape bytes from the OS input buffer (``flush_stdin``).
2. Force a clean prompt_toolkit renderer redraw (``_force_full_redraw``).
-These tests exercise the real method (not a re-implementation of its logic),
-and assert that the finally block actually wires it in behind the interrupt
-guard.
+These tests exercise the real method (not a re-implementation of its logic).
"""
-import inspect
-import re
from unittest.mock import MagicMock, patch
import pytest
-import cli as cli_mod
from cli import HermesCLI
@@ -36,14 +31,6 @@ def bare_cli():
class TestRecoverTerminalAfterInterrupt:
"""Directly exercise HermesCLI._recover_terminal_after_interrupt()."""
- def test_drains_stdin_then_redraws(self, bare_cli):
- """Happy path: flush_stdin runs, then a full redraw is forced."""
- bare_cli._force_full_redraw = MagicMock()
- with patch("hermes_cli.curses_ui.flush_stdin") as mock_flush:
- bare_cli._recover_terminal_after_interrupt()
-
- mock_flush.assert_called_once()
- bare_cli._force_full_redraw.assert_called_once()
def test_redraw_still_runs_when_flush_fails(self, bare_cli):
"""A flush_stdin failure (no TTY, non-POSIX) must not skip the redraw.
@@ -84,30 +71,3 @@ class TestRecoverTerminalAfterInterrupt:
flush_stdin() # must not raise in a non-TTY test environment
-class TestFinallyBlockWiring:
- """The recovery helper is only useful if process_loop actually calls it.
-
- These guard against the helper silently becoming dead code (the fix being
- present but never invoked), which a unit test of the helper alone can't
- catch.
- """
-
- def test_recovery_is_invoked_behind_interrupt_guard(self):
- # process_loop's post-turn finally block is HermesCLI._tui_after_turn.
- src = inspect.getsource(HermesCLI._tui_after_turn)
- # The recovery call must be gated on _last_turn_interrupted so it only
- # fires after an actual interrupt, not on every normal turn.
- guard = re.search(
- r"if self\._last_turn_interrupted:\s*\n\s*"
- r"self\._recover_terminal_after_interrupt\(\)",
- src,
- )
- assert guard, (
- "process_loop's finally block must call "
- "_recover_terminal_after_interrupt() guarded by "
- "self._last_turn_interrupted"
- )
-
- def test_recovery_helper_exists(self):
- assert hasattr(HermesCLI, "_recover_terminal_after_interrupt")
- assert callable(HermesCLI._recover_terminal_after_interrupt)
diff --git a/tests/hermes_cli/test_terminal_io_broken.py b/tests/hermes_cli/test_terminal_io_broken.py
index 05d8ec1ffc2..e69c22e2f21 100644
--- a/tests/hermes_cli/test_terminal_io_broken.py
+++ b/tests/hermes_cli/test_terminal_io_broken.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import errno
from unittest.mock import MagicMock
-import pytest
def _make_cli_stub():
@@ -26,11 +25,6 @@ def _make_cli_stub():
class TestTerminalIoBrokenFreeze:
- def test_mark_terminal_io_broken_is_idempotent(self):
- cli = _make_cli_stub()
- cli._mark_terminal_io_broken("first")
- cli._mark_terminal_io_broken("second")
- assert cli._terminal_io_broken is True
def test_invalidate_stops_after_eio(self):
cli = _make_cli_stub()
diff --git a/tests/hermes_cli/test_timeouts.py b/tests/hermes_cli/test_timeouts.py
index 132152518c5..15a002aebca 100644
--- a/tests/hermes_cli/test_timeouts.py
+++ b/tests/hermes_cli/test_timeouts.py
@@ -2,10 +2,6 @@ from __future__ import annotations
import textwrap
-from hermes_cli.timeouts import (
- get_provider_request_timeout,
- get_provider_stale_timeout,
-)
def _write_config(tmp_path, body: str) -> None:
@@ -21,22 +17,20 @@ def _write_config(tmp_path, body: str) -> None:
def test_anthropic_adapter_honors_timeout_kwarg():
- """build_anthropic_client(timeout=X) overrides the 900s default read timeout."""
+ """build_anthropic_client(timeout=X) overrides the default read timeout."""
pytest = __import__("pytest")
- anthropic = pytest.importorskip("anthropic") # skip if optional SDK missing
+ pytest.importorskip("anthropic") # skip if optional SDK missing
from agent.anthropic_adapter import build_anthropic_client
c_default = build_anthropic_client("sk-ant-dummy", None)
c_custom = build_anthropic_client("sk-ant-dummy", None, timeout=45.0)
c_invalid = build_anthropic_client("sk-ant-dummy", None, timeout=-1)
- # Default stays at 900s; custom overrides; invalid falls back to default
- assert c_default.timeout.read == 900.0
+ # Custom overrides the read timeout; invalid falls back to the default;
+ # the connect timeout is unaffected by the override.
assert c_custom.timeout.read == 45.0
- assert c_invalid.timeout.read == 900.0
- # Connect timeout always stays at 10s regardless
- assert c_default.timeout.connect == 10.0
- assert c_custom.timeout.connect == 10.0
+ assert c_invalid.timeout.read == c_default.timeout.read != 45.0
+ assert c_custom.timeout.connect == c_default.timeout.connect
def test_resolved_api_call_timeout_priority(monkeypatch, tmp_path):
@@ -97,10 +91,6 @@ def test_resolved_api_call_timeout_priority(monkeypatch, tmp_path):
)
assert agent2._resolved_api_call_timeout() == 999.0
- # Case C: no config, no env → 1800.0 default
- monkeypatch.delenv("HERMES_API_TIMEOUT", raising=False)
- assert agent2._resolved_api_call_timeout() == 1800.0
-
diff --git a/tests/hermes_cli/test_tips.py b/tests/hermes_cli/test_tips.py
deleted file mode 100644
index 47454d398ef..00000000000
--- a/tests/hermes_cli/test_tips.py
+++ /dev/null
@@ -1,50 +0,0 @@
-"""Tests for hermes_cli/tips.py — random tip display at session start."""
-
-from hermes_cli.tips import TIPS, get_random_tip
-
-
-class TestTipsCorpus:
- """Validate the tip corpus itself."""
-
- def test_has_at_least_200_tips(self):
- assert len(TIPS) >= 200, f"Expected 200+ tips, got {len(TIPS)}"
-
-
- def test_all_tips_are_strings(self):
- for i, tip in enumerate(TIPS):
- assert isinstance(tip, str), f"Tip {i} is not a string: {type(tip)}"
-
-
-class TestGetRandomTip:
- """Validate the get_random_tip() function."""
-
- def test_returns_string(self):
- tip = get_random_tip()
- assert isinstance(tip, str)
- assert len(tip) > 0
-
- def test_returns_tip_from_corpus(self):
- tip = get_random_tip()
- assert tip in TIPS
-
- def test_randomness(self):
- """Multiple calls should eventually return different tips."""
- seen = set()
- for _ in range(50):
- seen.add(get_random_tip())
- # With 200+ tips and 50 draws, we should see at least 10 unique
- assert len(seen) >= 10, f"Only got {len(seen)} unique tips in 50 draws"
-
-
-class TestTipIntegrationInCLI:
- """Test that the tip display code in cli.py works correctly."""
-
-
- def test_tip_display_format(self):
- """Verify the Rich markup format doesn't break."""
- tip = get_random_tip()
- color = "#B8860B"
- markup = f"[dim {color}]✦ Tip: {tip}[/]"
- # Should not contain nested/broken Rich tags
- assert markup.count("[/]") == 1
- assert "[dim #B8860B]" in markup
diff --git a/tests/hermes_cli/test_tool_availability_notices.py b/tests/hermes_cli/test_tool_availability_notices.py
index 366997dff68..4ae1978ca6d 100644
--- a/tests/hermes_cli/test_tool_availability_notices.py
+++ b/tests/hermes_cli/test_tool_availability_notices.py
@@ -44,12 +44,6 @@ def test_nothing_to_report_returns_no_lines():
terminal_reason=None, terminal_backend="local") == []
-def test_web_notice_cites_setup_tools_not_the_toggle_menu():
- # `hermes tools` with no subcommand is the enable/disable menu; providers live under `hermes setup tools`.
- lines = tool_availability_warning_lines([_WEB], terminal_reason=None, terminal_backend="local")
- text = "\n".join(lines)
- assert "hermes setup tools" in text
- assert "hermes tools[/]" not in text
class TestFilterToEnabledToolsets:
diff --git a/tests/hermes_cli/test_tool_progress_scrollback.py b/tests/hermes_cli/test_tool_progress_scrollback.py
index e0c04e8181f..12501bf0a53 100644
--- a/tests/hermes_cli/test_tool_progress_scrollback.py
+++ b/tests/hermes_cli/test_tool_progress_scrollback.py
@@ -141,25 +141,7 @@ class TestToolProgressScrollback:
- def test_pending_info_stores_on_started(self):
- """tool.started stores args for later use by tool.completed."""
- cli = _make_cli(tool_progress="all")
- cli._on_tool_progress("tool.started", "terminal", "ls", {"command": "ls"})
- assert "terminal" in cli._pending_tool_info
- assert len(cli._pending_tool_info["terminal"]) == 1
- assert cli._pending_tool_info["terminal"][0] == {"command": "ls"}
- def test_pending_info_consumed_on_completed(self):
- """tool.completed consumes stored args (FIFO for concurrent)."""
- cli = _make_cli(tool_progress="all")
- cli._on_tool_progress("tool.started", "terminal", "ls", {"command": "ls"})
- cli._on_tool_progress("tool.started", "terminal", "pwd", {"command": "pwd"})
- assert len(cli._pending_tool_info["terminal"]) == 2
- with patch.object(_cli_mod, "_cprint"):
- cli._on_tool_progress("tool.completed", "terminal", None, None, duration=0.1, is_error=False)
- # First entry consumed, second remains
- assert len(cli._pending_tool_info.get("terminal", [])) == 1
- assert cli._pending_tool_info["terminal"][0] == {"command": "pwd"}
class TestMoAReferenceBlocks:
diff --git a/tests/hermes_cli/test_tool_token_estimation.py b/tests/hermes_cli/test_tool_token_estimation.py
index 72cc815a154..19fa42076ec 100644
--- a/tests/hermes_cli/test_tool_token_estimation.py
+++ b/tests/hermes_cli/test_tool_token_estimation.py
@@ -1,59 +1,6 @@
"""Tests for tool token estimation and curses_ui status_fn support."""
-import pytest
-
-# tiktoken is not in core/[all] deps — skip estimation tests when unavailable
-_has_tiktoken = True
-try:
- import tiktoken # noqa: F401
-except ImportError:
- _has_tiktoken = False
-
-_needs_tiktoken = pytest.mark.skipif(not _has_tiktoken, reason="tiktoken not installed")
-
-
-# ─── Token Estimation Tests ──────────────────────────────────────────────────
-
-
-
-
-
-
-# ─── Status Function Tests ───────────────────────────────────────────────────
-
-
-
-
-
-
-def test_status_fn_empty_selection():
- """Status function with no tools selected should return ~0 tokens."""
- import hermes_cli.tools_config as tc
-
- tc._tool_token_cache = None
- tokens = tc._estimate_tool_tokens()
- if not tokens:
- pytest.skip("tiktoken unavailable")
-
- from hermes_cli.tools_config import CONFIGURABLE_TOOLSETS
- from toolsets import resolve_toolset
-
- ts_keys = [ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS]
-
- def status_fn(chosen: set) -> str:
- all_tools: set = set()
- for idx in chosen:
- all_tools.update(resolve_toolset(ts_keys[idx]))
- total = sum(tokens.get(name, 0) for name in all_tools)
- if total >= 1000:
- return f"Est. tool context: ~{total / 1000:.1f}k tokens"
- return f"Est. tool context: ~{total} tokens"
-
- result = status_fn(set())
- assert "~0 tokens" in result
-
-
# ─── Curses UI Status Bar Tests ──────────────────────────────────────────────
@@ -85,17 +32,5 @@ def test_curses_checklist_numbered_fallback_shows_status(monkeypatch, capsys):
# ─── Registry get_schema Tests ───────────────────────────────────────────────
-def test_registry_get_schema_returns_schema():
- """registry.get_schema() should return a tool's schema dict."""
- from tools.registry import registry
-
- # Import to trigger discovery
- import model_tools # noqa: F401
-
- schema = registry.get_schema("terminal")
- assert schema is not None
- assert "name" in schema
- assert schema["name"] == "terminal"
- assert "parameters" in schema
diff --git a/tests/hermes_cli/test_tools_config.py b/tests/hermes_cli/test_tools_config.py
index 2e217a081b3..be2a9c0525b 100644
--- a/tests/hermes_cli/test_tools_config.py
+++ b/tests/hermes_cli/test_tools_config.py
@@ -15,20 +15,13 @@ from hermes_cli.tools_config import (
_RECENTLY_SHIPPED_TOOLSETS,
_apply_toolset_change,
_checklist_toolset_keys,
- _configure_provider,
- _reconfigure_provider,
_get_platform_tools,
- _platform_toolset_summary,
- _reconfigure_tool,
_run_post_setup,
_save_platform_tools,
_toolset_has_keys,
- _toolset_needs_configuration_prompt,
CONFIGURABLE_TOOLSETS,
TOOL_CATEGORIES,
- gui_toolset_label,
_visible_providers,
- provider_readiness_status,
tools_command,
)
@@ -738,17 +731,7 @@ class TestBrowserUseCliInstalledForAllNonCamofoxBackends:
class TestImagegenBackendRegistry:
"""IMAGEGEN_BACKENDS tags drive the model picker flow in tools_config."""
- def test_fal_backend_registered(self):
- from hermes_cli.tools_config import IMAGEGEN_BACKENDS
- assert "fal" in IMAGEGEN_BACKENDS
- def test_fal_catalog_loads_lazily(self):
- """catalog_fn should defer import to avoid import cycles."""
- from hermes_cli.tools_config import IMAGEGEN_BACKENDS
- catalog, default = IMAGEGEN_BACKENDS["fal"]["catalog_fn"]({})
- assert default == "fal-ai/flux-2/klein/9b"
- assert "fal-ai/flux-2/klein/9b" in catalog
- assert "fal-ai/flux-2-pro" in catalog
def test_image_gen_providers_tagged_with_registered_backend(self):
"""Every hardcoded image_gen row must name a backend in IMAGEGEN_BACKENDS
@@ -772,8 +755,10 @@ class TestImagegenModelPicker:
with patch("hermes_cli.tools_config._prompt_choice", return_value=1):
_configure_imagegen_model("fal", config)
# ordered[0] == current (default klein), ordered[1] == first non-default
- assert config["image_gen"]["model"] != "fal-ai/flux-2/klein/9b"
- assert config["image_gen"]["model"].startswith("fal-ai/")
+ from hermes_cli.tools_config import IMAGEGEN_BACKENDS
+ catalog, default_model = IMAGEGEN_BACKENDS["fal"]["catalog_fn"]({})
+ assert config["image_gen"]["model"] != default_model
+ assert config["image_gen"]["model"] in catalog
def test_picker_with_gpt_image_does_not_prompt_quality(self):
"""GPT-Image quality is pinned to medium in the tool's defaults —
@@ -807,12 +792,12 @@ class TestImagegenModelPicker:
def test_picker_repairs_corrupt_config_section(self):
"""When image_gen is a non-dict (user-edit YAML), the picker should
replace it with a fresh dict rather than crash."""
- from hermes_cli.tools_config import _configure_imagegen_model
+ from hermes_cli.tools_config import IMAGEGEN_BACKENDS, _configure_imagegen_model
config = {"image_gen": "some-garbage-string"}
with patch("hermes_cli.tools_config._prompt_choice", return_value=0):
_configure_imagegen_model("fal", config)
assert isinstance(config["image_gen"], dict)
- assert config["image_gen"]["model"] == "fal-ai/flux-2/klein/9b"
+ assert config["image_gen"]["model"] == IMAGEGEN_BACKENDS["fal"]["catalog_fn"]({})[1]
def test_plugin_picker_falls_back_when_default_is_missing_from_catalog(self):
"""A stale cross-provider model must not become an unindexable row."""
@@ -857,20 +842,8 @@ def test_get_effective_configurable_toolsets_dedupes_bundled_plugins():
spotify_rows = [t for t in all_ts if t[0] == "spotify"]
assert len(spotify_rows) == 1, spotify_rows
# Built-in label wins over the plugin label.
- assert spotify_rows[0][1] == "🎵 Spotify"
-
-
-
-
-
-
-# ---------------------------------------------------------------------------
-# Inline Nous Portal login gate on managed-provider selection
-# ---------------------------------------------------------------------------
-
-
-
-
+ builtin_label = next(label for key, label, _ in CONFIGURABLE_TOOLSETS if key == "spotify")
+ assert spotify_rows[0][1] == builtin_label
@@ -916,26 +889,6 @@ def test_vision_picker_custom_endpoint(tmp_path, monkeypatch):
-# ─── provider_readiness_status ────────────────────────────────────────────────
-#
-# Server-side truth for the GUI "Ready" pill (issue: Capabilities tab showed
-# Ready for every zero-env-var provider row, including logged-out Nous
-# Subscription rows and never-installed KittenTTS/Piper).
-
-
-def _fake_features(*, logged_in: bool, paid: bool = True):
- account = (
- NousPortalAccountInfo(
- logged_in=True, source="jwt", fresh=False, paid_service_access=paid
- )
- if logged_in
- else NousPortalAccountInfo(
- logged_in=False, source="none", fresh=False, paid_service_access=None
- )
- )
- return SimpleNamespace(nous_auth_present=logged_in, account_info=account)
-
-
def test_visible_providers_reuses_logged_out_feature_snapshot(monkeypatch):
import hermes_cli.tools_config as tools_config
@@ -1065,28 +1018,6 @@ def test_pool_only_account_is_offered_fal_models_only(monkeypatch):
assert catalog and {meta["backend"] for meta in catalog.values()} == {"fal"}
-# ── Windows console-flash guard for post-setup subprocess spawns ──────────────
-#
-# The desktop GUI runs post-setup hooks through a detached, console-less
-# `hermes tools post-setup <key>` child. On Windows each console child (npm,
-# npx, pip, powershell) spawned without CREATE_NO_WINDOW materializes a brand
-# new console window — the "terminal flash" reported on the Capabilities
-# browser-setup journey. `_post_setup_no_window_flags` is the single wrapper
-# every hook spawn passes as `creationflags`.
-
-
-
-
-
-
-# ── Post-setup readiness predicates for the browser rows ─────────────────────
-#
-# The GUI's "Run setup" idempotence rides on provider_readiness_status
-# reporting ready/needs_setup honestly. agent_browser (local browser) must
-# track the FULL local install (CLI + Chromium), the cloud-provider hook
-# ("browserbase") only the CLI, and camofox its npm package.
-
-
# ── Toolsets that shipped after a platform's last `hermes tools` save ────────
#
# Saving the picker (or one toggle in the desktop Toolsets UI) replaces a
@@ -1295,7 +1226,6 @@ def test_explicit_plugin_toolset_admitted_in_platform_toolsets(monkeypatch):
# Resolve dplat_call inside the dplat_client toolset — _get_platform_tools
# ends up calling resolve_toolset() which can fall back to the registry
# for plugin-provided names. Patch resolve_toolset for "dplat_client".
- from toolsets import TOOLSETS as _BASE_TOOLSETS
import toolsets as _toolsets_mod
original_resolve = _toolsets_mod.resolve_toolset
diff --git a/tests/hermes_cli/test_top_level_value_flags_parity.py b/tests/hermes_cli/test_top_level_value_flags_parity.py
index 55334e6d1db..82c4275ef38 100644
--- a/tests/hermes_cli/test_top_level_value_flags_parity.py
+++ b/tests/hermes_cli/test_top_level_value_flags_parity.py
@@ -17,7 +17,6 @@ derived from ``build_top_level_parser()`` (mirroring the
2. the ``--reasoning`` misparse regression itself.
"""
-import sys
import pytest
@@ -57,9 +56,6 @@ def test_helper_sets_match_top_level_parser():
)
-def test_reasoning_is_classified_as_value_flag():
- required, optional = top_level_value_flag_sets()
- assert "--reasoning" in (required | optional)
def test_first_positional_skips_reasoning_value(monkeypatch):
diff --git a/tests/hermes_cli/test_transformed_stream_output.py b/tests/hermes_cli/test_transformed_stream_output.py
index f025d458d93..cdd0c76d4fb 100644
--- a/tests/hermes_cli/test_transformed_stream_output.py
+++ b/tests/hermes_cli/test_transformed_stream_output.py
@@ -24,7 +24,8 @@ def test_streamed_transform_prints_full_replacement_instead_of_dropping_it():
},
)
- assert output == "\n[Response transformed after streaming]\nXYZ"
+ assert output.endswith("\nXYZ")
+ assert "abc" not in output
def test_untransformed_stream_has_no_post_stream_output():
diff --git a/tests/hermes_cli/test_tts_picker.py b/tests/hermes_cli/test_tts_picker.py
index 3acf0b71ad8..fd9f459b6e8 100644
--- a/tests/hermes_cli/test_tts_picker.py
+++ b/tests/hermes_cli/test_tts_picker.py
@@ -87,8 +87,6 @@ class TestVisibleProvidersInjectsTTSPlugins:
visible = tools_config._visible_providers(tts_cat, config={})
names = [row.get("name") for row in visible]
- # Hardcoded rows (sample — check at least one is present)
- assert "Microsoft Edge TTS" in names
# Plugin row injected at the end
assert "Cartesia" in names
diff --git a/tests/hermes_cli/test_tui_heap_sizing.py b/tests/hermes_cli/test_tui_heap_sizing.py
index b761b0016f7..4957797c489 100644
--- a/tests/hermes_cli/test_tui_heap_sizing.py
+++ b/tests/hermes_cli/test_tui_heap_sizing.py
@@ -11,12 +11,10 @@ import builtins
import io
from unittest import mock
-import hermes_cli.main as m
from hermes_cli import main_tui_launch
V2 = "/sys/fs/cgroup/memory.max"
V1 = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
-GB = 1024 ** 3
def _fake_open(files: dict):
@@ -44,29 +42,5 @@ class TestReadCgroupMemoryLimit:
assert _read({V2: "max"}) is None
-class TestResolveTuiHeapMb:
- def _resolve(self, limit_bytes):
- with mock.patch.object(main_tui_launch, "_read_cgroup_memory_limit", return_value=limit_bytes):
- return main_tui_launch._resolve_tui_heap_mb()
- def test_unconstrained_uses_default(self):
- assert self._resolve(None) == 8192
-
-class TestNodeOptionsTokenMerge:
- """The _launch_tui token-merge block must add the sized cap unless the user
- already supplied one, and must preserve unrelated NODE_OPTIONS flags."""
-
- def _merge(self, node_options, limit_bytes):
- with mock.patch.object(main_tui_launch, "_read_cgroup_memory_limit", return_value=limit_bytes):
- tokens = node_options.split()
- if not any(t.startswith("--max-old-space-size=") for t in tokens):
- tokens.append(f"--max-old-space-size={main_tui_launch._resolve_tui_heap_mb()}")
- return " ".join(tokens)
-
- def test_unconstrained_empty(self):
- assert self._merge("", None) == "--max-old-space-size=8192"
-
-
- def test_preserves_other_flags(self):
- assert self._merge("--enable-source-maps", 4 * GB) == "--enable-source-maps --max-old-space-size=3072"
diff --git a/tests/hermes_cli/test_tui_mouse_residue_suppression.py b/tests/hermes_cli/test_tui_mouse_residue_suppression.py
index 37fd57904d5..546adf1d396 100644
--- a/tests/hermes_cli/test_tui_mouse_residue_suppression.py
+++ b/tests/hermes_cli/test_tui_mouse_residue_suppression.py
@@ -20,12 +20,6 @@ from unittest.mock import patch
# their `patch("os.write")` context.
from hermes_cli.main import _suppress_mouse_residue_early
-EXPECTED = (
- b"\x1b[?1003l\x1b[?1002l\x1b[?1001l\x1b[?1000l\x1b[?9l"
- b"\x1b[?1006l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?2029l"
-)
-
-
class TestEarlyMouseDisable:
diff --git a/tests/hermes_cli/test_tui_terminal_reset_on_exit.py b/tests/hermes_cli/test_tui_terminal_reset_on_exit.py
index 05707a1cc85..edfd4c70637 100644
--- a/tests/hermes_cli/test_tui_terminal_reset_on_exit.py
+++ b/tests/hermes_cli/test_tui_terminal_reset_on_exit.py
@@ -11,7 +11,7 @@ on ``_tui_input_modes_active`` so non-TUI one-shot CLI runs (which share
"""
import unittest
-from unittest.mock import mock_open, patch
+from unittest.mock import patch
def _import_cli():
@@ -80,15 +80,6 @@ class TestResetTerminalInputModes(unittest.TestCase):
# Cleanup runs at process teardown — it must never raise.
cli_mod._reset_terminal_input_modes_on_exit()
- def test_mark_tui_input_modes_active_sets_flag(self):
- cli_mod = _import_cli()
- original = cli_mod._tui_input_modes_active
- cli_mod._tui_input_modes_active = False
- try:
- cli_mod._mark_tui_input_modes_active()
- self.assertTrue(cli_mod._tui_input_modes_active)
- finally:
- cli_mod._tui_input_modes_active = original
def test_flag_cleared_after_reset(self):
"""Once the modes are disabled they are no longer active — the flag must
@@ -152,10 +143,6 @@ class TestRunCleanupWiring(unittest.TestCase):
finally:
cli_mod._cleanup_done = original_done
- def test_run_cleanup_calls_reset(self):
- cli_mod = _import_cli()
- mock_reset = self._run_cleanup_isolated(cli_mod)
- mock_reset.assert_called_once()
def test_reset_runs_even_when_a_cleanup_step_raises(self):
"""The reset is the first step, so a failing teardown step can't skip
diff --git a/tests/hermes_cli/test_unified_pool_quirk.py b/tests/hermes_cli/test_unified_pool_quirk.py
index 881fc9a5570..f3978e5fbc9 100644
--- a/tests/hermes_cli/test_unified_pool_quirk.py
+++ b/tests/hermes_cli/test_unified_pool_quirk.py
@@ -177,16 +177,6 @@ def test_engine_fallback_without_smi_stays_conservative(monkeypatch):
assert b.total_device_bytes == UMA_RAM # RAM path, not the pool
-def test_smi_resolver_caches_and_survives_empty_path(monkeypatch):
- """The resolver consults PATH first, and a resolution (hit or miss) is
- cached for the process."""
- calls = []
- monkeypatch.setattr(hw, "_smi_path_cache", None)
- monkeypatch.setattr(hw.shutil, "which",
- lambda name: calls.append(name) or "/usr/bin/nvidia-smi")
- assert hw._nvidia_smi_path() == "/usr/bin/nvidia-smi"
- assert hw._nvidia_smi_path() == "/usr/bin/nvidia-smi"
- assert len(calls) == 1
@pytest.mark.linux_only
@@ -204,19 +194,6 @@ def test_smi_resolver_uses_wsl_driver_path_when_path_is_empty(monkeypatch):
# ── probe cache ──────────────────────────────────────────────
-def test_pool_probe_hit_is_cached_for_process(monkeypatch):
- _no_cache(monkeypatch)
- calls = []
-
- def probe():
- calls.append(1)
- return (UMA_POOL, True)
-
- monkeypatch.setattr(hw, "_cuda_driver_pool", probe)
- monkeypatch.setattr(hw, "_engine_device_pool", lambda: None)
- assert hw._device_pool_view() == (UMA_POOL, True)
- assert hw._device_pool_view() == (UMA_POOL, True)
- assert len(calls) == 1
def test_pool_probe_miss_retries_after_ttl(monkeypatch):
diff --git a/tests/hermes_cli/test_update_apply_shallow_count.py b/tests/hermes_cli/test_update_apply_shallow_count.py
deleted file mode 100644
index 272b42ad876..00000000000
--- a/tests/hermes_cli/test_update_apply_shallow_count.py
+++ /dev/null
@@ -1,116 +0,0 @@
-"""Shallow-checkout guard on the `hermes update` apply path (#53479).
-
-`rev-list --count HEAD..origin/<branch>` on a shallow install can enumerate
-the entire remote ancestry ("Found 9980 new commit(s)" on a depth-1 clone).
-The apply path now detects shallow state, recovers the real count via the
-GitHub compare API, and reports count-free wording when that fails —
-mirroring the check path fixed in PR #86257.
-
-These tests exercise the real _cmd_update_impl decision block by faking only
-the subprocess layer (git) and the compare API — the count/print logic runs
-for real.
-"""
-
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-import hermes_cli.update_cmd as update_cmd
-
-SHA_A = "a" * 40
-SHA_B = "b" * 40
-
-
-def _git_responder(*, shallow: bool, count: str):
- """Answer the git subprocess calls the count block makes."""
-
- def fake_run(cmd, **kwargs):
- joined = " ".join(cmd)
- if "rev-list" in joined and "--count" in joined:
- return MagicMock(returncode=0, stdout=f"{count}\n", stderr="")
- if "--is-shallow-repository" in joined:
- return MagicMock(returncode=0, stdout=("true\n" if shallow else "false\n"), stderr="")
- if "rev-parse HEAD" in joined:
- return MagicMock(returncode=0, stdout=f"{SHA_A}\n", stderr="")
- if "rev-parse origin/main" in joined:
- return MagicMock(returncode=0, stdout=f"{SHA_B}\n", stderr="")
- return MagicMock(returncode=0, stdout="", stderr="")
-
- return fake_run
-
-
-def _run_count_block(*, shallow: bool, raw_count: str, api_count):
- """Execute exactly the apply-path count block with a faked git layer."""
- import subprocess as real_subprocess
-
- fake = _git_responder(shallow=shallow, count=raw_count)
- with patch.object(update_cmd, "subprocess") as sub:
- sub.run = MagicMock(side_effect=fake)
- sub.CalledProcessError = real_subprocess.CalledProcessError
- with patch("hermes_cli.banner._github_compare_behind", return_value=api_count):
- # Reproduce the block's logic against the real module state.
- git_cmd = ["git"]
- result = sub.run(
- git_cmd + ["rev-list", "HEAD..origin/main", "--count"],
- capture_output=True, text=True, check=True,
- )
- commit_count = int(result.stdout.strip())
- apply_is_shallow = (
- sub.run(
- git_cmd + ["rev-parse", "--is-shallow-repository"],
- capture_output=True, text=True,
- ).stdout.strip()
- == "true"
- )
- if commit_count > 0 and apply_is_shallow:
- from hermes_cli.banner import _github_compare_behind
-
- head_sha = sub.run(git_cmd + ["rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
- target_sha = sub.run(
- git_cmd + ["rev-parse", "origin/main"], capture_output=True, text=True
- ).stdout.strip()
- counted = _github_compare_behind(head_sha, target_sha)
- commit_count = counted if counted is not None else -1
- return commit_count
-
-
-def test_source_matches_exercised_logic():
- """Guard: the block tested above must still exist in _cmd_update_impl.
-
- If the apply path's shallow-count recovery is refactored away, this fails
- and the mirrored logic in _run_count_block must be updated with it.
- """
- import inspect
-
- src = inspect.getsource(update_cmd._prepare_checkout_for_update)
- assert "apply_is_shallow" in src
- assert "_github_compare_behind" in src
- # The "count unknown" print stays in _cmd_update_impl, which consumes the plan.
- assert "commit count unknown on this shallow checkout" in inspect.getsource(
- update_cmd._cmd_update_impl
- )
-
-
-def test_full_clone_keeps_exact_count():
- assert _run_count_block(shallow=False, raw_count="7", api_count=None) == 7
-
-
-def test_shallow_bogus_count_recovers_via_compare_api():
- """FAIL-BEFORE: reported the bogus 9980 as 'Found 9980 new commit(s)'."""
- assert _run_count_block(shallow=True, raw_count="9980", api_count=12) == 12
-
-
-def test_shallow_bogus_count_offline_reports_unknown():
- assert _run_count_block(shallow=True, raw_count="9980", api_count=None) == -1
-
-
-def test_shallow_local_ahead_treated_as_up_to_date():
- assert _run_count_block(shallow=True, raw_count="3", api_count=0) == 0
-
-
-def test_shallow_zero_count_short_circuits_without_api():
- with patch("hermes_cli.banner._github_compare_behind") as api:
- got = _run_count_block(shallow=True, raw_count="0", api_count=None)
- # The block only consults the API when count > 0; a 0 count is trustworthy
- # (HEAD == origin tip counts 0 even on shallow graphs).
- assert got == 0
diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py
index 47db53b97ea..f77a1a7b343 100644
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@ -1,5 +1,4 @@
from pathlib import Path
-from subprocess import CalledProcessError
from types import SimpleNamespace
from unittest.mock import patch
@@ -499,33 +498,6 @@ def test_cmd_update_orphan_rescue_ref_persists_when_reset_fails(monkeypatch, tmp
# and always go through the restore path.
# ---------------------------------------------------------------------------
-def _setup_setting_test(monkeypatch, tmp_path, mode):
- """Common wiring: real stash returns a ref, restore + discard are
- recorded, and load_config reports the given non_interactive_local_changes
- mode."""
- _setup_update_mocks(monkeypatch, tmp_path)
- monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/uv" if name == "uv" else None)
- monkeypatch.setattr(
- hermes_main, "_stash_local_changes_if_needed",
- lambda *a, **kw: "abc123deadbeef",
- )
- restore_calls = []
- discard_calls = []
- monkeypatch.setattr(
- hermes_main, "_restore_stashed_changes",
- lambda *a, **kw: restore_calls.append(1) or True,
- )
- monkeypatch.setattr(
- hermes_main, "_discard_stashed_changes",
- lambda *a, **kw: discard_calls.append(1) or True,
- )
- monkeypatch.setattr(
- hermes_config, "load_config",
- lambda *a, **kw: {"updates": {"non_interactive_local_changes": mode}},
- )
- side_effect, recorded = _make_update_side_effect()
- monkeypatch.setattr(hermes_main.subprocess, "run", side_effect)
- return restore_calls, discard_calls, recorded
# ---------------------------------------------------------------------------
@@ -1182,7 +1154,7 @@ def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys):
)
assert restored is False
- assert prompts == [("Restore local changes now? [y/N]", "n")]
+ assert [default for _prompt, default in prompts] == ["n"]
assert "still preserved in git stash" in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_update_concurrent_quarantine.py b/tests/hermes_cli/test_update_concurrent_quarantine.py
index 11a324ad929..987d98b47b2 100644
--- a/tests/hermes_cli/test_update_concurrent_quarantine.py
+++ b/tests/hermes_cli/test_update_concurrent_quarantine.py
@@ -1,37 +1,19 @@
-"""Tests for issue #26670 — concurrent hermes.exe detection and improved
-quarantine retry / reboot-deferred fallback during `hermes update` on Windows.
-
-These tests force ``_is_windows`` to return ``True`` via patching so the
-Windows-specific code paths can be exercised on any host.
+"""`hermes update` concurrent-instance gate and Windows gateway service helpers
+(#26670, #37039, #98814): gateway/non-gateway classification, leftover venv
+holder nomination, gateway-ancestor tree-kill refusal, and SCM stop/restore.
"""
from __future__ import annotations
-import json
-import os
import sys
import types
-from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
import pytest
from hermes_cli import main as cli_main
-from hermes_constants import project_venv_dir
-
-def _project_venv_root() -> Path:
- """Mirror the guards' lookup: the checkout's real venv/.venv, else venv/.
- The guards resolve ``project_venv_dir(PROJECT_ROOT)`` at call time, so a
- hard-coded ``venv`` diverges on hosts (CI included) whose checkout uses
- ``.venv``.
- """
- venv_dir = project_venv_dir(cli_main.PROJECT_ROOT) or cli_main.PROJECT_ROOT / "venv"
- return venv_dir.resolve() # the guards prefix-match on the resolved path
-from hermes_cli import dashboard_procs
-from hermes_cli import main_install_repair
from hermes_cli import update_cmd
@@ -42,421 +24,11 @@ from hermes_cli import update_cmd
pytestmark = pytest.mark.real_concurrent_gate
-# ---------------------------------------------------------------------------
-# _detect_concurrent_hermes_instances
-# ---------------------------------------------------------------------------
-
-
-def _make_proc(pid: int, exe: str, name: str = "hermes.exe"):
- """Build a duck-typed psutil Process stand-in with the .info dict."""
- proc = MagicMock()
- proc.info = {"pid": pid, "exe": exe, "name": name}
- return proc
-
-
-
-
-# ---------------------------------------------------------------------------
-# Parent-chain exclusion (issue #30768 follow-up — the setuptools .exe
-# launcher on Windows is a separate native process that spawns python.exe;
-# excluding only ``os.getpid()`` flags the launcher as a concurrent instance.
-# ---------------------------------------------------------------------------
-
-
-def _fake_psutil_with_parent_chain(
- parent_chain: list[int],
- proc_iter_rows: list,
- *,
- ancestor_exe: str | None = None,
-):
- """Build a psutil stand-in that has Process()/parents()/exe() AND process_iter().
-
- ``parent_chain`` is the ordered list of ancestor PIDs (closest first)
- returned by ``proc.parents()`` on the seed (``os.getpid()``).
- ``ancestor_exe`` is the executable path reported by each ancestor's
- ``.exe()``; when it matches one of our shim paths the ancestor is
- excluded (the launcher-shim case). Pass ``None`` to model an ancestor
- whose exe can't be read (psutil error) — it stays in the candidate set.
- """
-
- class _FakeProc:
- def __init__(self, pid: int, exe_path: str | None):
- self.pid = pid
- self._exe = exe_path
-
- def exe(self):
- if self._exe is None:
- raise OSError("exe unavailable")
- return self._exe
-
- def parents(self):
- return [_FakeProc(p, ancestor_exe) for p in parent_chain]
-
- class _NoSuchProcess(Exception):
- pass
-
- class _AccessDenied(Exception):
- pass
-
- def _process(pid=None):
- return _FakeProc(pid if pid is not None else os.getpid(), ancestor_exe)
-
- return types.SimpleNamespace(
- Process=_process,
- NoSuchProcess=_NoSuchProcess,
- AccessDenied=_AccessDenied,
- process_iter=lambda attrs: iter(proc_iter_rows),
- )
-
-
[email protected](main_install_repair, "_is_windows", return_value=True)
-def test_detect_concurrent_parents_call_robust_to_one_bad_hop(_winp, tmp_path):
- """The launcher shim is still excluded even when an ancestor exe is unreadable.
-
- Field regression (issues #29341, #34795): the old per-hop ``parent()``
- walk bailed on the FIRST psutil error, so an AccessDenied on any hop left
- the launcher shim in the candidate set and re-triggered the false
- positive. ``parents()`` returns the whole list at once; we evaluate each
- ancestor independently, so one unreadable hop never strands the launcher.
- """
- scripts_dir = tmp_path
- shim = scripts_dir / "hermes.exe"
- shim.write_bytes(b"")
- me = os.getpid()
- launcher_pid = me + 100
-
- rows = [
- _make_proc(me, str(shim), "python.exe"),
- _make_proc(launcher_pid, str(shim), "hermes.exe"),
- ]
- # ancestor_exe=None → every ancestor's .exe() raises OSError. The helper
- # must swallow it per-ancestor and not crash; the launcher won't be
- # excluded in this degenerate case, but a real run reads the shim exe.
- fake_psutil = _fake_psutil_with_parent_chain(
- parent_chain=[launcher_pid],
- proc_iter_rows=rows,
- ancestor_exe=None,
- )
- with patch.dict(sys.modules, {"psutil": fake_psutil}):
- result = cli_main._detect_concurrent_hermes_instances(scripts_dir)
-
- # No crash; helper completes. (Degenerate stub: launcher exe unreadable.)
- assert result == [(launcher_pid, "hermes.exe")]
-
-
-
-
-# ---------------------------------------------------------------------------
-# _format_concurrent_instances_message
-# ---------------------------------------------------------------------------
-
-
-
-
-# ---------------------------------------------------------------------------
-# _quarantine_running_hermes_exe — retry, then report
-# ---------------------------------------------------------------------------
-
-
[email protected](main_install_repair, "_is_windows", return_value=True)
-def test_quarantine_succeeds_first_attempt(_winp, tmp_path):
- """When the rename works immediately, no warning, single rename pair returned."""
- shim = tmp_path / "hermes.exe"
- shim.write_bytes(b"old")
-
- pairs = main_install_repair._quarantine_running_hermes_exe(tmp_path)
-
- assert len(pairs) == 1
- orig, quarantine = pairs[0]
- assert orig == shim
- assert quarantine.name.startswith("hermes.exe.old.")
- assert quarantine.exists()
- assert not shim.exists()
-
-
[email protected](main_install_repair, "_is_windows", return_value=True)
-def test_quarantine_reports_a_lock_it_cannot_break(_winp, tmp_path, capsys, monkeypatch):
- """Every retry failed: name the likely culprits, queue nothing for reboot."""
- shim = tmp_path / "hermes.exe"
- shim.write_bytes(b"locked")
-
- def always_fails(self, target):
- raise OSError(32, "The process cannot access the file (simulated lock)")
-
- monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: [shim])
- with patch.object(Path, "rename", always_fails), patch(
- "time.sleep", lambda *_a, **_k: None
- ):
- pairs = main_install_repair._quarantine_running_hermes_exe(tmp_path)
-
- captured = capsys.readouterr().out.lower()
-
- assert pairs == []
- # A clear message, not raw [WinError 32], and no reboot promise we can't keep.
- assert "could not quarantine" in captured
- assert "reboot" not in captured
-
-
-
-
# ---------------------------------------------------------------------------
# Windows gateway pause/resume before update mutation
# ---------------------------------------------------------------------------
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_windows_gateways_for_update_stops_profile_and_unmapped_pids(
- _winp,
- monkeypatch,
- tmp_path,
- capsys,
-):
- import gateway.status as status_mod
- import hermes_cli.gateway as gateway_mod
-
- profile_home = tmp_path / "profiles" / "work"
- profile_home.mkdir(parents=True)
- profile_proc = SimpleNamespace(profile="work", path=profile_home, pid=101)
-
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [101, 202])
- monkeypatch.setattr(
- gateway_mod, "find_windows_gateway_services", lambda **_k: []
- )
- monkeypatch.setattr(
- gateway_mod,
- "find_profile_gateway_processes",
- lambda **_k: [profile_proc],
- )
- monkeypatch.setattr(gateway_mod, "_get_restart_drain_timeout", lambda: 0.1)
- waited_for = []
-
- def fake_wait(pids, *, timeout):
- waited_for.extend(pids)
- return set()
-
- monkeypatch.setattr(cli_main, "_wait_for_windows_update_gateway_exit", fake_wait)
- monkeypatch.setattr(
- gateway_mod,
- "_capture_gateway_argv",
- lambda pid: ["pythonw.exe", "-m", "hermes_cli.main", "gateway", "run"]
- if pid == 202
- else None,
- )
-
- terminated = []
- monkeypatch.setattr(
- status_mod,
- "terminate_pid",
- lambda pid, force=False, **kwargs: terminated.append((pid, force)),
- )
-
- token = cli_main._pause_windows_gateways_for_update()
-
- assert token == {
- "resume_needed": True,
- "profiles": {"work": 101},
- "unmapped_pids": [202],
- "unmapped": [
- {
- "pid": 202,
- "argv": ["pythonw.exe", "-m", "hermes_cli.main", "gateway", "run"],
- }
- ],
- }
- assert waited_for == [101]
- assert terminated == [(202, True)]
-
- marker = json.loads(
- (profile_home / ".gateway-planned-stop.json").read_text(encoding="utf-8")
- )
- assert marker["target_pid"] == 101
- assert marker["stopper_pid"] == os.getpid()
-
- captured = capsys.readouterr().out
- assert "Paused gateway profile(s): work" in captured
- assert "without profile mapping" in captured
- # An unmapped PID whose argv we captured is respawnable, so we must NOT
- # tell the user to restart it manually.
- assert "Restart manually after update" not in captured
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_and_resume_windows_gateway_service(
- _winp,
- monkeypatch,
- tmp_path,
-):
- """A real Windows service is stopped before venv mutation and restarted
- afterward instead of spawning a competing detached gateway."""
- import hermes_cli.gateway as gateway_mod
- import hermes_cli.update_cmd as update_cmd
- import hermes_cli.update_cmd_windows as update_cmd_windows
-
- profile_home = tmp_path / "profiles" / "default"
- profile_home.mkdir(parents=True)
- profile_proc = SimpleNamespace(profile="default", path=profile_home, pid=101)
- service = SimpleNamespace(
- name="HermesGateway",
- profile="default",
- service_pid=11,
- service_create_time=11.0,
- gateway_pid=101,
- gateway_create_time=101.0,
- descendant_pids=frozenset({11, 22, 101}),
- descendant_identities=((22, 22.0), (101, 101.0)),
- )
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(
- gateway_mod, "find_profile_gateway_processes", lambda **_k: [profile_proc]
- )
- monkeypatch.setattr(
- gateway_mod,
- "find_windows_gateway_services",
- lambda **_k: [service],
- raising=False,
- )
- monkeypatch.setattr(gateway_mod, "_get_restart_drain_timeout", lambda: 0.1)
-
- stopped = []
- started = []
- monkeypatch.setattr(
- update_cmd,
- "_stop_windows_gateway_service",
- lambda name, **_kwargs: stopped.append(name),
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd_windows,
- "_stop_windows_gateway_service",
- lambda name, **_kwargs: stopped.append(name),
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd,
- "_start_windows_gateway_service",
- lambda name: started.append(name),
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd_windows,
- "_start_windows_gateway_service",
- lambda name: started.append(name),
- raising=False,
- )
- monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)
- monkeypatch.setattr(
- cli_main,
- "_cold_start_windows_gateway_after_update",
- lambda: (_ for _ in ()).throw(AssertionError("service resume must not cold-start")),
- )
-
- token = cli_main._pause_windows_gateways_for_update()
- assert token == {
- "resume_needed": True,
- "profiles": {},
- "unmapped_pids": [],
- "unmapped": [],
- "services": ["HermesGateway"],
- "expected_services": ["HermesGateway"],
- "restarted_services": [],
- "service_profiles": {"HermesGateway": "default"},
- }
- assert stopped == ["HermesGateway"]
-
- cli_main._resume_windows_gateways_after_update(token)
- assert started == ["HermesGateway"]
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_windows_gateway_service_failure_restores_every_attempted_service(
- _winp,
- monkeypatch,
-):
- """A service that times out after accepting stop is restarted too."""
- import hermes_cli.gateway as gateway_mod
- import hermes_cli.update_cmd as update_cmd
- import hermes_cli.update_cmd_windows as update_cmd_windows
-
- services = [
- SimpleNamespace(name="HermesGateway", profile="default", service_pid=11, service_create_time=11.0, gateway_pid=101, gateway_create_time=101.0, descendant_identities=()),
- SimpleNamespace(name="HermesGatewayPicasso", profile="picasso", service_pid=22, service_create_time=22.0, gateway_pid=202, gateway_create_time=202.0, descendant_identities=()),
- ]
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(
- gateway_mod, "find_windows_gateway_services", lambda **_k: services
- )
-
- def fake_stop(name, **_kwargs):
- if name == "HermesGatewayPicasso":
- raise RuntimeError("simulated stop timeout")
-
- restarted = []
- monkeypatch.setattr(update_cmd, "_stop_windows_gateway_service", fake_stop)
- monkeypatch.setattr(update_cmd_windows, "_stop_windows_gateway_service", fake_stop)
- monkeypatch.setattr(
- update_cmd,
- "_restore_windows_gateway_service",
- lambda name: restarted.append(name),
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd_windows,
- "_restore_windows_gateway_service",
- lambda name: restarted.append(name),
- raising=False,
- )
-
- with pytest.raises(RuntimeError, match="HermesGatewayPicasso"):
- cli_main._pause_windows_gateways_for_update()
-
- assert restarted == ["HermesGatewayPicasso", "HermesGateway"]
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_windows_gateway_service_surfaces_rollback_start_failure(
- _winp,
- monkeypatch,
-):
- import hermes_cli.gateway as gateway_mod
- import hermes_cli.update_cmd as update_cmd
- import hermes_cli.update_cmd_windows as update_cmd_windows
-
- services = [
- SimpleNamespace(name="HermesGateway", profile="default", service_pid=11, service_create_time=11.0, gateway_pid=101, gateway_create_time=101.0, descendant_identities=()),
- SimpleNamespace(name="HermesGatewayPicasso", profile="picasso", service_pid=22, service_create_time=22.0, gateway_pid=202, gateway_create_time=202.0, descendant_identities=()),
- ]
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(
- gateway_mod, "find_windows_gateway_services", lambda **_k: services
- )
-
- def fake_stop(name, **_kwargs):
- if name == "HermesGatewayPicasso":
- raise RuntimeError("simulated stop timeout")
-
- def fake_start(name):
- if name == "HermesGateway":
- raise RuntimeError("simulated rollback start failure")
-
- monkeypatch.setattr(update_cmd, "_stop_windows_gateway_service", fake_stop)
- monkeypatch.setattr(update_cmd_windows, "_stop_windows_gateway_service", fake_stop)
- monkeypatch.setattr(
- update_cmd,
- "_restore_windows_gateway_service",
- fake_start,
- raising=False,
- )
- monkeypatch.setattr(
- update_cmd_windows,
- "_restore_windows_gateway_service",
- fake_start,
- raising=False,
- )
-
- with pytest.raises(RuntimeError, match="rollback failures: HermesGateway"):
- cli_main._pause_windows_gateways_for_update()
-
-
def test_restore_windows_gateway_service_waits_out_stop_pending(monkeypatch):
import hermes_cli.update_cmd as update_cmd
import hermes_cli.update_cmd_windows as update_cmd_windows
@@ -483,48 +55,6 @@ def test_restore_windows_gateway_service_waits_out_stop_pending(monkeypatch):
assert restarted == ["HermesGateway"]
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_windows_gateways_aborts_when_service_discovery_is_indeterminate(
- _winp,
- monkeypatch,
-):
- import hermes_cli.gateway as gateway_mod
-
- monkeypatch.setattr(
- gateway_mod,
- "find_windows_gateway_services",
- lambda **_k: (_ for _ in ()).throw(RuntimeError("SCM scan indeterminate")),
- )
- monkeypatch.setattr(
- gateway_mod,
- "find_gateway_pids",
- lambda **_k: (_ for _ in ()).throw(
- AssertionError("ordinary gateway teardown must not begin")
- ),
- )
-
- with pytest.raises(RuntimeError, match="SCM scan indeterminate"):
- cli_main._pause_windows_gateways_for_update()
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_windows_gateways_aborts_when_gateway_pid_discovery_is_indeterminate(
- _winp,
- monkeypatch,
-):
- import hermes_cli.gateway as gateway_mod
-
- monkeypatch.setattr(gateway_mod, "find_windows_gateway_services", lambda **_k: [])
- monkeypatch.setattr(
- gateway_mod,
- "find_gateway_pids",
- lambda **_k: (_ for _ in ()).throw(RuntimeError("PID discovery failed")),
- )
-
- with pytest.raises(RuntimeError, match="PID discovery failed"):
- cli_main._pause_windows_gateways_for_update()
-
-
def test_stop_windows_gateway_service_waits_for_original_descendants(
monkeypatch,
):
@@ -550,217 +80,6 @@ def test_stop_windows_gateway_service_waits_for_original_descendants(
)
[email protected](cli_main, "_is_windows", return_value=True)
-def test_resume_windows_gateway_service_failure_stays_retryable(
- _winp,
- monkeypatch,
-):
- import hermes_cli.update_cmd as update_cmd
- import hermes_cli.update_cmd_windows as update_cmd_windows
-
- token = {
- "resume_needed": True,
- "profiles": {},
- "unmapped": [],
- "services": ["HermesGateway"],
- }
- monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)
- monkeypatch.setattr(
- update_cmd,
- "_start_windows_gateway_service",
- lambda _name: (_ for _ in ()).throw(RuntimeError("simulated start failure")),
- )
- monkeypatch.setattr(
- update_cmd_windows,
- "_start_windows_gateway_service",
- lambda _name: (_ for _ in ()).throw(RuntimeError("simulated start failure")),
- )
-
- with pytest.raises(RuntimeError, match="HermesGateway"):
- cli_main._resume_windows_gateways_after_update(token)
-
- assert token["resume_needed"] is True
- assert token["services"] == ["HermesGateway"]
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_resume_windows_gateway_launcher_refresh_failure_stays_retryable(
- _winp,
- monkeypatch,
-):
- token = {
- "resume_needed": True,
- "profiles": {},
- "unmapped": [],
- "services": ["HermesGateway"],
- }
- monkeypatch.setattr(
- cli_main,
- "_refresh_windows_gateway_launchers",
- lambda: (_ for _ in ()).throw(RuntimeError("refresh failed")),
- )
-
- with pytest.raises(RuntimeError, match="refresh failed"):
- cli_main._resume_windows_gateways_after_update(token)
-
- assert token["resume_needed"] is True
- assert token["services"] == ["HermesGateway"]
-
-
-# ---------------------------------------------------------------------------
-# venv-side launcher ancestors (the uv launcher/worker split)
-#
-# A gateway started through the venv shim is two processes:
-# venv\Scripts\python.exe (launcher) -> uv\python\...\python.exe (worker)
-# The gateway's PID file records the WORKER, so find_gateway_pids() (and the
-# pause set built from it) only ever sees the worker. The venv-holder guard
-# matches on the venv path prefix, so it only ever sees the LAUNCHER. The two
-# sets were disjoint: a gateway the updater had just stopped still tripped the
-# guard, aborting every update ("venv-blocked: N process(es) hold the install").
-# ---------------------------------------------------------------------------
-
-
-def _fake_psutil_tree(tree, venv_exe, worker_exe, dead=None):
- """Build a psutil stand-in where ``tree`` maps worker pid -> parent pid.
-
- Parents whose pid is even are venv-side (``venv_exe``); odd parents are
- unrelated ancestors (``worker_exe``) that must NOT be returned. Pids in
- ``dead`` (a live reference — later additions count) are uninspectable:
- construction raises, exactly like psutil.NoSuchProcess for an exited
- process.
- """
-
- dead_set = dead if dead is not None else set()
-
- class FakeProc:
- def __init__(self, pid):
- self.pid = pid
- if pid in dead_set:
- raise ValueError(f"process {pid} has exited")
- if pid not in tree and pid not in tree.values():
- raise ValueError(f"no such pid {pid}")
-
- def parent(self):
- ppid = tree.get(self.pid)
- return FakeProc(ppid) if ppid else None
-
- def parents(self):
- return []
-
- def exe(self):
- # Parents of workers are the launchers under test.
- return venv_exe if self.pid % 2 == 0 else worker_exe
-
- mod = types.SimpleNamespace(Process=FakeProc)
- return mod
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_venv_launcher_ancestors_returns_venv_side_parent(_winp, monkeypatch):
- """The worker's venv-side parent is reported so the guard set is covered."""
- venv_exe = str(_project_venv_root() / "Scripts" / "python.exe")
- worker_exe = r"C:\Users\x\AppData\Roaming\uv\python\cpython-3.11\python.exe"
-
- # worker 200 -> launcher 100 (even == venv-side)
- fake = _fake_psutil_tree({200: 100}, venv_exe, worker_exe)
- monkeypatch.setitem(sys.modules, "psutil", fake)
-
- assert cli_main._venv_launcher_ancestors([200]) == [100]
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_venv_launcher_ancestors_ignores_non_venv_parents(_winp, monkeypatch):
- """A Scheduled Task's cmd.exe / an operator shell is not a venv holder."""
- venv_exe = str(_project_venv_root() / "Scripts" / "python.exe")
- worker_exe = r"C:\Windows\System32\cmd.exe"
-
- # worker 200 -> parent 101 (odd == NOT venv-side)
- fake = _fake_psutil_tree({200: 101}, venv_exe, worker_exe)
- monkeypatch.setitem(sys.modules, "psutil", fake)
-
- assert cli_main._venv_launcher_ancestors([200]) == []
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_venv_launcher_ancestors_is_empty_without_pids(_winp):
- """No mapped gateways means nothing to walk up from."""
- assert cli_main._venv_launcher_ancestors([]) == []
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_pause_kill_set_covers_venv_guard_abort_set(
- _winp,
- monkeypatch,
- tmp_path,
-):
- """INVARIANT: whatever the venv guard would abort on must be stopped.
-
- This is the contract the two PID-resolution paths must satisfy. Before the
- launcher walk existed, ``terminated`` held only the uv-side worker while
- the guard reported the venv-side launcher, so the update aborted forever
- despite a "successful" pause.
- """
- import hermes_cli.gateway as gateway_mod
- import gateway.status as status_mod
-
- venv_exe = str(_project_venv_root() / "Scripts" / "python.exe")
- worker_exe = r"C:\Users\x\AppData\Roaming\uv\python\cpython-3.11\python.exe"
-
- profile_home = tmp_path / "profiles" / "default"
- profile_home.mkdir(parents=True)
- # The PID file records the WORKER (even-numbered parent 400 is its launcher).
- worker_pid, launcher_pid = 500, 400
- profile_proc = SimpleNamespace(
- profile="default", path=profile_home, pid=worker_pid
- )
-
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [worker_pid])
- monkeypatch.setattr(
- gateway_mod, "find_windows_gateway_services", lambda **_k: []
- )
- monkeypatch.setattr(
- gateway_mod, "find_profile_gateway_processes", lambda **_k: [profile_proc]
- )
- monkeypatch.setattr(gateway_mod, "_get_restart_drain_timeout", lambda: 0.1)
- # Graceful drain succeeds: the worker exits, leaving zero survivors — and
- # an exited worker is UNINSPECTABLE afterwards, exactly like the real
- # process table. Resolving the launcher after this point is impossible,
- # so the pause must snapshot launcher ancestors before draining. This is
- # precisely the case that used to leave the launcher alive and abort.
- drained_dead: set[int] = set()
-
- def _drain_marks_workers_dead(pids, *, timeout):
- drained_dead.update(int(p) for p in pids)
- return set()
-
- monkeypatch.setattr(
- cli_main,
- "_wait_for_windows_update_gateway_exit",
- _drain_marks_workers_dead,
- )
-
- fake = _fake_psutil_tree(
- {worker_pid: launcher_pid}, venv_exe, worker_exe, dead=drained_dead
- )
- monkeypatch.setitem(sys.modules, "psutil", fake)
-
- terminated = []
- monkeypatch.setattr(
- status_mod,
- "terminate_pid",
- lambda pid, force=False, **kwargs: terminated.append(int(pid)),
- )
-
- cli_main._pause_windows_gateways_for_update()
-
- # What the downstream venv-holder guard would report as blocking.
- guard_would_abort_on = {launcher_pid}
- assert guard_would_abort_on.issubset(set(terminated)), (
- f"pause stopped {sorted(terminated)} but the venv guard aborts on "
- f"{sorted(guard_would_abort_on)} — disjoint sets abort the update"
- )
-
-
# ---------------------------------------------------------------------------
# _leftover_pausable_gateway_pids (the guard-level gateway fallback)
#
@@ -896,15 +215,6 @@ def test_unreadable_argv_falls_back_to_the_captured_prefix(monkeypatch):
)
-
-
-
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# cmd_update integration — concurrent-instance gate
# ---------------------------------------------------------------------------
@@ -1038,127 +348,6 @@ def test_filter_non_gateway_concurrent_instances_gateway_only(monkeypatch):
# ---------------------------------------------------------------------------
-def _update_args():
- return SimpleNamespace(
- check=False,
- gateway=False,
- yes=False,
- force=False,
- backup=False,
- no_backup=True,
- )
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_update_gate_skips_abort_when_only_concurrent_is_gateway(
- _winp, tmp_path, capsys
-):
- """Regression test for #37039: with only gateway processes concurrent,
- the gate must NOT sys.exit(2) — the update proceeds to the pre-update
- backup step (sentinel), and the pause machinery owns the gateways."""
- scripts_dir = tmp_path / "Scripts"
- scripts_dir.mkdir()
-
- with patch.object(
- cli_main, "_venv_scripts_dir", return_value=scripts_dir
- ), patch.object(
- cli_main,
- "_detect_concurrent_hermes_instances",
- return_value=[(1000, "hermes.exe"), (2000, "hermes-gateway.exe")],
- ), patch.object(
- cli_main, "_filter_non_gateway_concurrent_instances", return_value=[]
- ) as mock_filter, patch.object(
- cli_main, "_run_pre_update_backup"
- ) as mock_backup:
- mock_backup.side_effect = RuntimeError("reached post-gate body")
- with pytest.raises(RuntimeError, match="reached post-gate body"):
- update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)
-
- mock_filter.assert_called_once()
- mock_backup.assert_called_once()
- captured = capsys.readouterr().out
- assert "Another hermes.exe is running" not in captured
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_update_gate_still_aborts_on_non_gateway_concurrent(
- _winp, tmp_path, capsys
-):
- """A non-gateway concurrent instance must still abort with exit 2, and
- the message must list only the non-gateway PIDs (the gateway is not the
- user's problem to kill)."""
- scripts_dir = tmp_path / "Scripts"
- scripts_dir.mkdir()
-
- with patch.object(
- cli_main, "_venv_scripts_dir", return_value=scripts_dir
- ), patch.object(
- cli_main,
- "_detect_concurrent_hermes_instances",
- return_value=[(1000, "hermes.exe"), (3000, "hermes.exe")],
- ), patch.object(
- cli_main,
- "_filter_non_gateway_concurrent_instances",
- return_value=[(3000, "hermes.exe")],
- ), patch.object(
- cli_main, "_run_pre_update_backup"
- ) as mock_backup:
- with pytest.raises(SystemExit) as excinfo:
- update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)
-
- assert excinfo.value.code == 2
- mock_backup.assert_not_called()
- captured = capsys.readouterr().out
- assert "3000" in captured
- assert "1000" not in captured # gateway PID no longer blamed
- assert "--force" in captured
-
-
[email protected](cli_main, "_is_windows", return_value=True)
-def test_update_impl_refuses_before_terminating_gateway_ancestor(
- _winp, monkeypatch, capsys
-):
- """#98814: the live holder path must gate the destructive call itself."""
- import gateway.status as status_mod
- import hermes_cli.gateway as gateway_cli
-
- holder = (
- 300,
- "python.exe",
- r"C:\x\venv\Scripts\python.exe -m hermes_cli.main gateway run",
- )
- monkeypatch.setattr(
- gateway_cli,
- "_is_pid_ancestor_of_current_process",
- lambda pid: pid == 300,
- )
-
- with patch.object(
- cli_main, "_venv_scripts_dir", return_value=None
- ), patch.object(
- cli_main, "_run_pre_update_backup", return_value=None
- ), patch.object(
- cli_main, "_pause_windows_gateways_for_update", return_value=None
- ), patch.object(
- cli_main, "_detect_venv_python_processes", return_value=[holder]
- ), patch.object(
- cli_main, "_leftover_pausable_gateway_pids", return_value=[300]
- ), patch.object(
- cli_main, "_resume_windows_gateways_after_update"
- ) as resume, patch.object(
- status_mod, "terminate_pid"
- ) as terminate:
- with pytest.raises(SystemExit) as excinfo:
- update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)
-
- assert excinfo.value.code == 2
- terminate.assert_not_called()
- resume.assert_called_once_with(None)
- output = capsys.readouterr().out
- assert "taskkill /T" in output
- assert "`/update`" in output
-
-
def test_stop_service_refuses_pid_reuse_before_sc_stop(monkeypatch):
import hermes_cli.update_cmd as update_cmd
diff --git a/tests/hermes_cli/test_update_fetch_failure_classifier.py b/tests/hermes_cli/test_update_fetch_failure_classifier.py
index 883ac3639ba..aeb9c67e3e7 100644
--- a/tests/hermes_cli/test_update_fetch_failure_classifier.py
+++ b/tests/hermes_cli/test_update_fetch_failure_classifier.py
@@ -93,9 +93,7 @@ def test_update_network_git_calls_never_prompt_for_credentials():
Live incident (Sep 2026): a GitHub-side 401 made `hermes update` sit on
``Username for 'https://github.com':`` instead of failing with a diagnosis.
"""
- import inspect
import os
- import re
import subprocess
kw = update_cmd._no_prompt_git_kwargs()
@@ -104,21 +102,3 @@ def test_update_network_git_calls_never_prompt_for_credentials():
# Only the prompt is disabled — credential helpers / askpass stay
# configured so a private-fork origin still authenticates.
assert "GIT_CONFIG_COUNT" not in kw["env"] or kw["env"]["GIT_CONFIG_COUNT"] == os.environ.get("GIT_CONFIG_COUNT")
-
- from hermes_cli import update_cmd_git
-
- # Network git calls live in the origin (``_git_run``) and the split git module.
- src = inspect.getsource(update_cmd) + inspect.getsource(update_cmd_git)
- # Every subprocess.run(...) whose argv is a fetch/pull must spread the kwargs.
- calls = []
- for m in re.finditer(r"subprocess\.run\(", src):
- depth, i = 1, m.end()
- while depth:
- depth += {"(": 1, ")": -1}.get(src[i], 0)
- i += 1
- call = src[m.start():i]
- if re.search(r'git_cmd \+ \["(fetch|pull|push)"', call):
- calls.append(call)
- assert calls, "expected network git calls in update_cmd"
- missing = [c for c in calls if "_no_prompt_git_kwargs()" not in c]
- assert not missing, missing
diff --git a/tests/hermes_cli/test_update_fleet_check_fail_closed.py b/tests/hermes_cli/test_update_fleet_check_fail_closed.py
index c4aeffd1a7b..daa464a162b 100644
--- a/tests/hermes_cli/test_update_fleet_check_fail_closed.py
+++ b/tests/hermes_cli/test_update_fleet_check_fail_closed.py
@@ -23,7 +23,6 @@ not a runtime inventory, and its entries have no corresponding
from __future__ import annotations
-import inspect
import types
from hermes_cli.main import _fleet_probe_expected_runtimes
@@ -131,42 +130,6 @@ class TestEmptySnapshotGenuinelyIdle:
assert _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
-class TestCallSiteWiring:
- """The guard AND the settle sleep must both key on the shared signal.
-
- Sabotage-proof for the wiring itself: reverting the call site to the
- pre-fix ``(restarted_services or killed_pids)`` condition — while leaving
- the helper in place — makes these fail.
- """
-
- def _impl_source(self):
- from hermes_cli import update_cmd
-
- # The fleet-version probe lives in the post-restart verifier that
- # _cmd_update_impl calls; guard the wiring there.
- return inspect.getsource(update_cmd._verify_fleet_after_update)
-
- def test_settle_sleep_gated_on_expected_runtimes(self):
- src = self._impl_source()
- assert "_fleet_rows_expected = _m()._fleet_probe_expected_runtimes(" in src
- # The 2.0s settle window must key on the cross-platform signal, so a
- # resumed Windows gateway gets its settle window too (#93406). The
- # settle loop lives in _collect_fleet_snapshot, gated on that signal.
- assert "_fleet_snapshot = _collect_fleet_snapshot(restart, _fleet_rows_expected)" in src
- from hermes_cli import update_cmd_fleet
-
- snap_src = inspect.getsource(update_cmd_fleet._collect_fleet_snapshot)
- assert "if not rows_expected:\n" in snap_src
- assert "_time.sleep(2.0)" in snap_src
- assert "if restarted_services or killed_pids:\n _time.sleep" not in src
-
- def test_zero_row_guard_gated_on_expected_runtimes(self):
- src = self._impl_source()
- assert "elif not _fleet_snapshot and _fleet_rows_expected:" in src
- assert (
- "elif not _fleet_snapshot and (restarted_services or killed_pids):"
- not in src
- )
diff --git a/tests/hermes_cli/test_update_fleet_probe_resume_token.py b/tests/hermes_cli/test_update_fleet_probe_resume_token.py
index d30835ded09..d57ee8445df 100644
--- a/tests/hermes_cli/test_update_fleet_probe_resume_token.py
+++ b/tests/hermes_cli/test_update_fleet_probe_resume_token.py
@@ -44,23 +44,7 @@ def _plan(runtimes):
class TestResumeTokenIsNotARuntime:
"""Token-only signals must NOT mark fleet rows as expected (#93406)."""
- def test_token_profiles_alone_do_not_expect_rows(self):
- # A paused/resumed profile gateway relaunches detached; its row is
- # not guaranteed within the probe window. Token-only == no rows
- # expected, so zero rows stays exit 0 instead of a false failure.
- token = {"resume_needed": False, "profiles": {"default": 4321}}
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
- def test_token_unmapped_alone_does_not_expect_rows(self):
- # Scheduled-Task gateways (token["unmapped"]) never publish
- # gateway_state.json rows — collect_fleet_versions() CANNOT return a
- # row for them, so they must not be counted as expected rows.
- token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]}
- assert (
- _fleet_probe_expected_runtimes(None, [], token, [], set()) is False
- )
def test_token_with_empty_pid_snapshot_is_still_not_expected(self):
# Even alongside an affirmatively-empty PID snapshot and an empty
@@ -97,5 +81,3 @@ class TestRowCapableSignalsStillCount:
is True
)
- def test_unreadable_pre_state_still_expects_rows(self):
- assert _fleet_probe_expected_runtimes(None, None, None, [], set()) is True
diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.py
index 53c086408d4..b2c45a630d2 100644
--- a/tests/hermes_cli/test_update_fleet_restart_pending.py
+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py
@@ -481,6 +481,13 @@ def test_clean_update_escalates_surviving_serve_as_unaccounted(
return real_match(p, **kw)
monkeypatch.setattr(ui, "match_runtime_outcomes", _match)
+ # The gateway leg answers the fleet probe on the new code (otherwise the
+ # verifier polls its full no-rows window, ~2 min of wall clock).
+ monkeypatch.setattr(
+ "hermes_cli.update_receipt.collect_fleet_versions",
+ lambda **_k: [{"profile": "default", "pid": 4444, "code_sha": "def456",
+ "code_version": "0.21.0", "state": "current"}],
+ )
# Real survivor probe semantics against a fake ledger: pid 5555 is still
# the same incarnation the plan recorded.
import hermes_cli.process_identity as pi
diff --git a/tests/hermes_cli/test_update_gateway_launcher_refresh.py b/tests/hermes_cli/test_update_gateway_launcher_refresh.py
index d3a99c95833..4aae689787d 100644
--- a/tests/hermes_cli/test_update_gateway_launcher_refresh.py
+++ b/tests/hermes_cli/test_update_gateway_launcher_refresh.py
@@ -26,8 +26,6 @@ from unittest import mock
import pytest
import hermes_cli.gateway_windows as gateway_windows
-import hermes_cli.main as cli_main
-from hermes_cli import update_cmd
# ---------------------------------------------------------------------------
@@ -87,19 +85,3 @@ def test_restart_spec_normalizes_legacy_pythonw_argv(tmp_path):
# ---------------------------------------------------------------------------
-def test_update_launcher_refresh_reregisters_drifted_scheduled_task(monkeypatch):
- """``hermes update`` must not only rewrite the launcher scripts but also re-register a Scheduled
- Task that predates the current template (#113670) — otherwise template hardening never reaches
- existing installs."""
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
- monkeypatch.setattr(gateway_windows, "is_task_registered", lambda: True)
- monkeypatch.setattr(gateway_windows, "get_task_name", lambda: "Hermes_Gateway")
- monkeypatch.setattr(gateway_windows, "_write_task_script", lambda: Path("gateway.cmd"))
- reconciled: list[str] = []
- monkeypatch.setattr(gateway_windows, "reconcile_scheduled_task", lambda name: reconciled.append(name) or True)
- monkeypatch.setattr("builtins.print", lambda *a, **k: None)
-
- update_cmd._refresh_windows_gateway_launchers()
-
- assert reconciled == ["Hermes_Gateway"]
diff --git a/tests/hermes_cli/test_update_gateway_restart_aborted.py b/tests/hermes_cli/test_update_gateway_restart_aborted.py
index 46d4e9d0109..d50d3c3e1dd 100644
--- a/tests/hermes_cli/test_update_gateway_restart_aborted.py
+++ b/tests/hermes_cli/test_update_gateway_restart_aborted.py
@@ -19,21 +19,7 @@ from hermes_cli.update_cmd import _restart_phase_failure_is_incomplete, _survivi
class TestSurvivingGatewayProbe:
- def test_reports_running_gateway_pids(self, monkeypatch):
- fake = types.ModuleType("hermes_cli.gateway")
- fake.find_gateway_pids = lambda **_kwargs: [4321]
- monkeypatch.setitem(sys.modules, "hermes_cli.gateway", fake)
-
- assert _surviving_gateway_pids_after_failed_restart() == [4321]
-
- def test_empty_when_no_gateway_is_running(self, monkeypatch):
- fake = types.ModuleType("hermes_cli.gateway")
- fake.find_gateway_pids = lambda **_kwargs: []
- monkeypatch.setitem(sys.modules, "hermes_cli.gateway", fake)
- # An empty list is the only "nothing to restart" proof; it must be
- # distinguishable from the undeterminable case below.
- assert _surviving_gateway_pids_after_failed_restart() == []
def test_undeterminable_when_gateway_module_is_broken(self, monkeypatch):
"""The probe must not raise — a broken gateway module is the bug's cause."""