Skip to content

The agent that grows with you

test: purge low-value tests, lane py11 (303 removed)

teknium14f1dcc2dad51
diff --git a/scripts/ci/check_os_marker_fakes.py b/scripts/ci/check_os_marker_fakes.py
index 18f90690b62..f4c1a61c82e 100644
--- a/scripts/ci/check_os_marker_fakes.py
+++ b/scripts/ci/check_os_marker_fakes.py
@@ -49,9 +49,6 @@ _FAKES = (
# Files that faked macOS before this check existed (#111866). Burn down, never extend.
_BASELINE = frozenset(
{
- "tests/hermes_cli/test_doctor.py",
- "tests/hermes_cli/test_gateway.py",
- "tests/hermes_cli/test_gateway_proc_fallback.py",
"tests/hermes_cli/test_linux_sandbox_fixup.py",
"tests/hermes_cli/test_macos_fda_guidance.py",
"tests/hermes_cli/test_orphan_desktop_serve_reap.py",
diff --git a/tests/hermes_cli/test_dashboard_auth_password_login.py b/tests/hermes_cli/test_dashboard_auth_password_login.py
index 4319c6e29f0..640e137db13 100644
--- a/tests/hermes_cli/test_dashboard_auth_password_login.py
+++ b/tests/hermes_cli/test_dashboard_auth_password_login.py
@@ -24,7 +24,6 @@ from hermes_cli.dashboard_auth import (
InvalidCredentialsError,
ProviderError,
Session,
- assert_protocol_compliance,
clear_providers,
register_provider,
)
@@ -170,12 +169,7 @@ def gated_app(pw_provider):
class TestProtocolExtension:
- def test_password_provider_is_protocol_compliant(self):
- assert assert_protocol_compliance(PasswordProvider) is None
- def test_default_supports_password_is_false(self):
- # OAuth providers (the Stub) inherit the False default.
- assert StubAuthProvider.supports_password is False
def test_default_complete_password_login_raises_not_implemented(self):
# A provider that doesn't override the method (the Stub) raises,
@@ -344,19 +338,6 @@ class TestRateLimit:
class TestLoginPageRender:
- def test_password_provider_renders_credential_form_and_script(self):
- clear_providers()
- register_provider(PasswordProvider())
- try:
- html = render_login_html(next_path="/sessions")
- assert '<form class="provider-form" data-provider="testpw"' in html
- assert 'name="username"' in html
- assert 'name="password"' in html
- assert 'value="/sessions"' in html
- assert "<script>" in html
- assert "/auth/password-login" in html
- finally:
- clear_providers()
def test_oauth_only_page_stays_script_free(self):
clear_providers()
diff --git a/tests/hermes_cli/test_dashboard_auth_plugin_hook.py b/tests/hermes_cli/test_dashboard_auth_plugin_hook.py
index dd1fda6f257..b559e624de3 100644
--- a/tests/hermes_cli/test_dashboard_auth_plugin_hook.py
+++ b/tests/hermes_cli/test_dashboard_auth_plugin_hook.py
@@ -64,9 +64,6 @@ def _make_ctx(name: str = "dashboard-auth-stub") -> PluginContext:
return PluginContext(manifest=manifest, manager=_MinimalManager()) # type: ignore[arg-type]
-def test_plugin_ctx_exposes_register_dashboard_auth_provider():
- ctx = _make_ctx()
- assert hasattr(ctx, "register_dashboard_auth_provider")
def test_plugin_ctx_silently_ignores_non_provider(caplog):
diff --git a/tests/hermes_cli/test_dashboard_auth_provider_base.py b/tests/hermes_cli/test_dashboard_auth_provider_base.py
deleted file mode 100644
index af1ad1e0c9d..00000000000
--- a/tests/hermes_cli/test_dashboard_auth_provider_base.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""Contract test for DashboardAuthProvider implementations.
-
-Every provider plugin should call ``assert_protocol_compliance`` on its
-provider class in its own unit test. This module tests the abstract base
-itself: dataclass fields, ABC rejection of partial impls, and the
-protocol-compliance helper.
-"""
-from __future__ import annotations
-
-import pytest
-
-from hermes_cli.dashboard_auth.base import (
- DashboardAuthProvider,
- Session,
- LoginStart,
- assert_protocol_compliance,
-)
-
-
-# ---------------------------------------------------------------------------
-# Dataclasses
-# ---------------------------------------------------------------------------
-
-
-def test_session_has_required_fields():
- s = Session(
- user_id="u1",
- display_name="A",
- org_id="org_1",
- provider="test",
- expires_at=1234567890,
- access_token="at",
- refresh_token="rt",
- )
- assert s.user_id == "u1"
- assert s.provider == "test"
- assert s.expires_at == 1234567890
-
-
-
-
-# ---------------------------------------------------------------------------
-# ABC enforcement
-# ---------------------------------------------------------------------------
-
-
-
-
-class _BrokenProvider(DashboardAuthProvider):
- name = "broken"
- display_name = "Broken"
- # Deliberately missing all the methods.
-
-
-class _CompliantProvider(DashboardAuthProvider):
- name = "ok"
- display_name = "OK"
-
- def start_login(self, *, redirect_uri: str) -> LoginStart:
- return LoginStart(redirect_url="x", cookie_payload={})
-
- def complete_login(self, *, code, state, code_verifier, redirect_uri) -> Session:
- return Session(
- user_id="u", email="x", display_name="x", org_id="o",
- provider=self.name, expires_at=0,
- access_token="a", refresh_token="r",
- )
-
- def verify_session(self, *, access_token: str):
- return None
-
- def refresh_session(self, *, refresh_token: str) -> Session:
- return Session(
- user_id="u", email="x", display_name="x", org_id="o",
- provider=self.name, expires_at=0,
- access_token="a", refresh_token="r",
- )
-
- def revoke_session(self, *, refresh_token: str) -> None:
- return None
-
-
-
-
-
-
-# ---------------------------------------------------------------------------
-# Registry (Task 1.2)
-# ---------------------------------------------------------------------------
-
-
-from hermes_cli.dashboard_auth import ( # noqa: E402 (after-imports for clarity)
- register_provider,
- get_provider,
- list_providers,
- clear_providers,
-)
-
-
[email protected](autouse=True)
-def _isolated_registry():
- """Every test starts with an empty registry and leaves it empty."""
- clear_providers()
- yield
- clear_providers()
-
-
-
-
-
-
-def test_registry_lists_in_registration_order():
- class A(_CompliantProvider):
- name = "a"
- display_name = "A"
-
- class B(_CompliantProvider):
- name = "b"
- display_name = "B"
-
- register_provider(A())
- register_provider(B())
- names = [p.name for p in list_providers()]
- assert names == ["a", "b"]
-
-
diff --git a/tests/hermes_cli/test_dashboard_auth_stub_provider.py b/tests/hermes_cli/test_dashboard_auth_stub_provider.py
deleted file mode 100644
index 686e51dbf38..00000000000
--- a/tests/hermes_cli/test_dashboard_auth_stub_provider.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""Contract test for the StubAuthProvider used in dashboard-auth E2E tests.
-
-Phase 2 of the dashboard-OAuth plan. Validates the stub against the
-provider protocol so subsequent phases that depend on its behavior
-have a guarantee.
-"""
-from __future__ import annotations
-
-import pytest
-
-from hermes_cli.dashboard_auth.base import (
- InvalidCodeError, RefreshExpiredError, assert_protocol_compliance,
-)
-from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider
-
-
-def _pkce_payload(ls) -> dict:
- """Parse ``state=...;verifier=...`` out of the LoginStart cookie payload."""
- return dict(
- item.split("=", 1)
- for item in ls.cookie_payload["hermes_session_pkce"].split(";")
- )
-
-
-def test_stub_complies_with_protocol():
- assert assert_protocol_compliance(StubAuthProvider) is None
-
-
-def test_stub_complete_login_rejects_mismatched_state():
- p = StubAuthProvider()
- p.start_login(redirect_uri="https://x.fly.dev/auth/callback")
- with pytest.raises(InvalidCodeError):
- p.complete_login(
- code="stub_code",
- state="WRONG",
- code_verifier="anything",
- redirect_uri="https://x.fly.dev/auth/callback",
- )
-
-
-def test_stub_verify_tampered_token_returns_none():
- p = StubAuthProvider()
- assert p.verify_session(access_token="garbage-not-a-real-token") is None
-
-
diff --git a/tests/hermes_cli/test_dashboard_auth_ws_tickets.py b/tests/hermes_cli/test_dashboard_auth_ws_tickets.py
index 74d91e4c9b2..39a8c229770 100644
--- a/tests/hermes_cli/test_dashboard_auth_ws_tickets.py
+++ b/tests/hermes_cli/test_dashboard_auth_ws_tickets.py
@@ -71,9 +71,6 @@ class TestSingleUse:
class TestTTL:
- def test_constant_is_30_seconds(self):
- # Pinned so a refactor that doubled the lifetime would surface here.
- assert TTL_SECONDS == 30
def test_expired_ticket_rejected(self, monkeypatch):
# Mock time inside the ws_tickets module so mint and consume see
diff --git a/tests/hermes_cli/test_dashboard_browser_safe_imports.py b/tests/hermes_cli/test_dashboard_browser_safe_imports.py
deleted file mode 100644
index 05f3a33bc19..00000000000
--- a/tests/hermes_cli/test_dashboard_browser_safe_imports.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""Static dashboard tests for browser-safe @nous-research/ui imports."""
-from pathlib import Path
-
-
-WEB_SRC = Path(__file__).resolve().parents[2] / "web" / "src"
-
-
-def test_dashboard_does_not_import_nous_ui_root_barrel():
- offenders = []
- for ext in ("*.tsx", "*.ts"):
- for path in WEB_SRC.rglob(ext):
- content = path.read_text(encoding="utf-8")
- if 'from "@nous-research/ui"' in content or "from '@nous-research/ui'" in content:
- offenders.append(str(path.relative_to(WEB_SRC)))
-
- assert offenders == []
diff --git a/tests/hermes_cli/test_dashboard_lifecycle_flags.py b/tests/hermes_cli/test_dashboard_lifecycle_flags.py
index acfabdebad6..eda1c9f8364 100644
--- a/tests/hermes_cli/test_dashboard_lifecycle_flags.py
+++ b/tests/hermes_cli/test_dashboard_lifecycle_flags.py
@@ -54,7 +54,6 @@ class TestDashboardStatus:
# Status is informational — always exits 0.
assert exc.value.code == 0
out = capsys.readouterr().out
- assert "3 hermes dashboard/serve process(es) running" in out
assert "PID 12345" in out
assert "PID 12346" in out
assert "PID 12347" in out and "[serve]" in out
@@ -175,23 +174,3 @@ class TestLifecycleFlagsTakePrecedence:
assert called["start"] is False
-class TestArgparseWiring:
- """Confirm the flags are exposed via the real argparse tree so
- ``hermes dashboard --stop`` / ``--status`` actually parse."""
-
- def test_flags_are_registered(self):
- from hermes_cli.main import main as _cli_main # noqa: F401
- # Rebuild the argparse tree by re-running the section of main()
- # that builds it. Cheapest way: introspect via --help on the
- # already-built parser would require refactoring; instead we
- # parse the flags directly via a minimal replay.
- import importlib
- mod = importlib.import_module("hermes_cli.main")
- # Find the dashboard_parser instance by running build logic would
- # be too invasive. Instead parse args as if via the CLI by
- # intercepting parse_args. This is overkill for a smoke test —
- # we just want to know the flags don't KeyError.
- with patch("hermes_cli.dashboard_procs._scan_dashboard_processes", return_value=[]), \
- pytest.raises(SystemExit) as exc:
- mod.cmd_dashboard(_ns(status=True))
- assert exc.value.code == 0
diff --git a/tests/hermes_cli/test_dashboard_param_clamps.py b/tests/hermes_cli/test_dashboard_param_clamps.py
index 96c9dfb9be8..8c75a83ba45 100644
--- a/tests/hermes_cli/test_dashboard_param_clamps.py
+++ b/tests/hermes_cli/test_dashboard_param_clamps.py
@@ -31,9 +31,6 @@ class TestSessionPaginationClamps:
r = client.get("/api/sessions", params={"limit": 10_000})
assert r.status_code == 422
- def test_negative_limit_rejected(self, client):
- r = client.get("/api/sessions", params={"limit": -1})
- assert r.status_code == 422
def test_profile_fanout_limit_clamped(self, client):
r = client.get("/api/profiles/sessions", params={"limit": 10_000})
diff --git a/tests/hermes_cli/test_dashboard_plugin_routes_secret_scope.py b/tests/hermes_cli/test_dashboard_plugin_routes_secret_scope.py
index 71048b10fed..fc8d6cdc77f 100644
--- a/tests/hermes_cli/test_dashboard_plugin_routes_secret_scope.py
+++ b/tests/hermes_cli/test_dashboard_plugin_routes_secret_scope.py
@@ -94,7 +94,7 @@ def test_failure_and_request_shape_errors_are_unchanged(client, multiplexed, mon
failed = client.post("/api/dashboard/agent-plugins/install", json={"identifier": "owner/repo"})
assert failed.status_code == 400
- assert failed.json()["detail"] == "Install failed: no such plugin."
+ assert "no such plugin" in failed.json()["detail"]
malformed = client.post("/api/dashboard/agent-plugins/install", json={"identifier": ""})
assert malformed.status_code == 400
diff --git a/tests/hermes_cli/test_dashboard_procs_kill_grace.py b/tests/hermes_cli/test_dashboard_procs_kill_grace.py
index f8d7b661495..e32b0053d3a 100644
--- a/tests/hermes_cli/test_dashboard_procs_kill_grace.py
+++ b/tests/hermes_cli/test_dashboard_procs_kill_grace.py
@@ -14,7 +14,6 @@ real signals, a real PTY.
from __future__ import annotations
import os
-import pathlib
import signal
import subprocess
import sys
@@ -25,25 +24,8 @@ import pytest
from hermes_cli import dashboard_procs
-_REPO_ROOT = pathlib.Path(dashboard_procs.__file__).resolve().parents[1]
-
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal semantics only")
-# Mirrors the lifespan: sleep for the teardown budget on SIGTERM, then leave a marker and exit 0.
-_GRACEFUL_CHILD = textwrap.dedent(
- """
- import pathlib, signal, sys, time
- marker, ready, secs = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), float(sys.argv[3])
- def _on_term(_signum, _frame):
- time.sleep(secs)
- marker.write_text("teardown-complete")
- sys.exit(0)
- signal.signal(signal.SIGTERM, _on_term)
- ready.write_text("ready")
- time.sleep(300)
- """
-)
-
_IGNORING_CHILD = textwrap.dedent(
"""
import pathlib, signal, sys, time
@@ -131,17 +113,6 @@ def _pid_running(pid: int) -> bool:
return bool(stat) and not stat.startswith("Z")
-def test_teardown_as_long_as_lifespan_budget_exits_gracefully(tmp_path):
- """A teardown spanning the 5s hosted-room stop + 1s join must not be SIGKILLed."""
- marker, ready = tmp_path / "marker", tmp_path / "ready"
- child = _spawn_ready(_GRACEFUL_CHILD, ready, str(marker), str(ready), "6.2")
-
- killed, failed = _kill_and_reap(child)
-
- assert failed == []
- assert child.returncode == 0, f"SIGKILLed mid-teardown (rc={child.returncode})"
- assert marker.read_text() == "teardown-complete"
- assert killed == [child.pid]
def test_sigterm_ignoring_process_is_still_sigkilled(tmp_path, monkeypatch):
@@ -178,53 +149,3 @@ def test_wedged_pty_descendant_is_gone_but_detached_bot_survives(tmp_path, monke
for pid in (tui_pid, bot_pid):
if _pid_running(pid):
os.kill(pid, signal.SIGKILL)
-
-
-# The stopper itself, run as a same-session child of the backend (a shell escape inside the hosted
-# Chat TUI): `hermes dashboard --stop` / `hermes update` must not SIGTERM their own process.
-_STOPPER_CHILD = textwrap.dedent(
- """
- import os, pathlib, sys
- from hermes_cli import dashboard_procs as dp
- dp._POSIX_TERM_GRACE_SECONDS = 0.5
- backend, marker = int(sys.argv[1]), pathlib.Path(sys.argv[2])
- snapshot = dp._posix_descendants([backend])
- killed, failed = [], []
- dp._kill_pids_posix([backend], killed, failed)
- marker.write_text(f"{os.getpid() in snapshot} {killed} {failed}")
- """
-)
-
-_BACKEND_WITH_STOPPER_CHILD = textwrap.dedent(
- f"""
- import os, pathlib, signal, subprocess, sys, time
- signal.signal(signal.SIGTERM, lambda *_: time.sleep(300))
- pathlib.Path(sys.argv[2]).write_text("ready")
- subprocess.Popen([sys.executable, "-c", {_STOPPER_CHILD!r}, str(os.getpid()), sys.argv[1]]).wait()
- time.sleep(300)
- """
-)
-
-
-def test_stopper_running_as_backend_descendant_survives_the_sweep(tmp_path):
- """POSIX twin of the Windows #98814 hazard: the caller and its ancestors are not descendants
- to sweep, even when the stop runs from inside the backend's own process tree."""
- marker, ready = tmp_path / "marker", tmp_path / "ready"
- env = dict(os.environ, PYTHONPATH=os.pathsep.join(filter(None, [str(_REPO_ROOT), os.environ.get("PYTHONPATH")])))
- backend = subprocess.Popen(
- [sys.executable, "-c", _BACKEND_WITH_STOPPER_CHILD, str(marker), str(ready)], env=env,
- stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- )
- try:
- deadline = time.monotonic() + 30.0
- while backend.poll() is None and time.monotonic() < deadline:
- time.sleep(0.05)
- assert backend.returncode == -signal.SIGKILL, "the stopper never SIGKILLed the wedged backend"
- assert marker.exists(), "stopper died before finishing the stop: it swept itself"
- in_snapshot, _, rest = marker.read_text().partition(" ")
- assert in_snapshot == "False"
- assert rest == f"[{backend.pid}] []"
- finally:
- if backend.poll() is None:
- backend.kill()
- backend.wait(timeout=10)
diff --git a/tests/hermes_cli/test_dashboard_profiles_nav_label.py b/tests/hermes_cli/test_dashboard_profiles_nav_label.py
deleted file mode 100644
index 924f217bd2e..00000000000
--- a/tests/hermes_cli/test_dashboard_profiles_nav_label.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""Static dashboard tests for the Profiles navigation copy."""
-from pathlib import Path
-
-
-def test_profiles_nav_label_uses_short_copy():
- en_i18n = Path(__file__).resolve().parents[2] / "web" / "src" / "i18n" / "en.ts"
-
- content = en_i18n.read_text(encoding="utf-8")
-
- # Nav label should be the clean short form, not the old verbose string
- assert 'profiles: "Profiles"' in content
- assert "profiles : multi agents" not in content
diff --git a/tests/hermes_cli/test_dashboard_register.py b/tests/hermes_cli/test_dashboard_register.py
index 33d45b7e06b..de8d6659171 100644
--- a/tests/hermes_cli/test_dashboard_register.py
+++ b/tests/hermes_cli/test_dashboard_register.py
@@ -32,14 +32,6 @@ def _ns(**kw):
return argparse.Namespace(**defaults)
-class TestNameGenerator:
- def test_shape_is_adjective_underscore_noun(self):
- for _ in range(50):
- name = dr._generate_dashboard_name()
- assert "_" in name
- adj, _, noun = name.partition("_")
- assert adj in dr._NAME_ADJECTIVES
- assert noun in dr._NAME_NOUNS
class TestFastFails:
diff --git a/tests/hermes_cli/test_debug.py b/tests/hermes_cli/test_debug.py
index e826794a6ae..e97f6c60605 100644
--- a/tests/hermes_cli/test_debug.py
+++ b/tests/hermes_cli/test_debug.py
@@ -1,7 +1,6 @@
"""Tests for ``hermes debug`` CLI command and debug utilities."""
import os
-import urllib.error
from unittest.mock import MagicMock, patch
import pytest
@@ -45,32 +44,6 @@ def hermes_home(tmp_path, monkeypatch):
# Unit tests for upload helpers
# ---------------------------------------------------------------------------
-class TestUploadPasteRs:
- """Test paste.rs upload path."""
-
- def test_upload_paste_rs_success(self):
- from hermes_cli.debug import _upload_paste_rs
-
- mock_resp = MagicMock()
- mock_resp.read.return_value = b"https://paste.rs/abc123\n"
- mock_resp.__enter__ = lambda s: s
- mock_resp.__exit__ = MagicMock(return_value=False)
-
- with patch("hermes_cli.debug.urllib.request.urlopen", return_value=mock_resp):
- url = _upload_paste_rs("hello world")
-
- assert url == "https://paste.rs/abc123"
-
-
- def test_upload_paste_rs_network_error(self):
- from hermes_cli.debug import _upload_paste_rs
-
- with patch(
- "hermes_cli.debug.urllib.request.urlopen",
- side_effect=urllib.error.URLError("connection refused"),
- ):
- with pytest.raises(urllib.error.URLError):
- _upload_paste_rs("test")
@@ -171,7 +144,6 @@ class TestMissingLogNote:
snap = _capture_log_snapshot("desktop", tail_lines=10)
assert snap.full_text is None
assert "not on this host" in snap.tail_text
- assert "Hermes Desktop" in snap.tail_text
# The reader needs the path to collect by hand on the client machine.
assert str(hermes_home / "logs" / "desktop.log") in snap.tail_text
@@ -303,20 +275,6 @@ class TestCaptureLogSnapshotRedaction:
assert snap.full_text is not None
assert "[email protected]" not in snap.full_text
- def test_no_redact_preserves_email_addresses(self, hermes_home_with_secret):
- from hermes_cli.debug import _capture_log_snapshot
-
- log_path = hermes_home_with_secret / "logs" / "agent.log"
- log_path.write_text(
- "2026-04-12 17:00:00 INFO gateway.run: "
- "inbound message: platform=bluebubbles "
- "[email protected] chat=iMessage;-;[email protected] msg='hello'\n"
- )
-
- snap = _capture_log_snapshot("agent", tail_lines=10, redact=False)
-
- assert "[email protected]" in snap.tail_text
- assert "[email protected]" in (snap.full_text or "")
def test_capture_default_log_snapshots_threads_redact(
self, hermes_home_with_secret
@@ -329,35 +287,12 @@ class TestCaptureLogSnapshotRedaction:
assert _REDACT_FIXTURE_TOKEN not in snaps["agent"].tail_text
assert _REDACT_FIXTURE_TOKEN not in (snaps["agent"].full_text or "")
- def test_capture_default_log_snapshots_no_redact_passes_through(
- self, hermes_home_with_secret
- ):
- from hermes_cli.debug import _capture_default_log_snapshots
-
- snaps = _capture_default_log_snapshots(50, redact=False)
-
- assert _REDACT_FIXTURE_TOKEN in snaps["agent"].tail_text
- assert _REDACT_FIXTURE_TOKEN in (snaps["agent"].full_text or "")
# ---------------------------------------------------------------------------
# Debug report collection
# ---------------------------------------------------------------------------
-class TestCollectDebugReport:
- """Test the debug report builder."""
-
- def test_report_includes_dump_output(self, hermes_home):
- from hermes_cli.debug import collect_debug_report
-
- with patch("hermes_cli.dump.run_dump") as mock_dump:
- mock_dump.side_effect = lambda args: print(
- "--- hermes dump ---\nversion: 0.8.0\n--- end dump ---"
- )
- report = collect_debug_report(log_lines=50)
-
- assert "--- hermes dump ---" in report
- assert "version: 0.8.0" in report
# ---------------------------------------------------------------------------
@@ -367,24 +302,6 @@ class TestCollectDebugReport:
class TestRunDebugShare:
"""Test the run_debug_share CLI handler."""
- def test_share_sweeps_expired_pastes(self, hermes_home, capsys):
- """Slash-command path should sweep old pending deletes before uploading."""
- from hermes_cli.debug import run_debug_share
-
- args = MagicMock()
- args.lines = 50
- args.expire = 7
- args.local = False
- args.nous = False
-
- with patch("hermes_cli.dump.run_dump"), \
- patch("hermes_cli.debug._sweep_expired_pastes", return_value=(0, 0)) as mock_sweep, \
- patch("hermes_cli.debug.upload_to_pastebin",
- return_value="https://paste.rs/test"):
- run_debug_share(args)
-
- mock_sweep.assert_called_once()
- assert "Debug report uploaded" in capsys.readouterr().out
@@ -567,32 +484,6 @@ class TestRunDebugShareRedaction:
# run_debug router
# ---------------------------------------------------------------------------
-class TestRunDebug:
- def test_no_subcommand_shows_usage(self, capsys):
- from hermes_cli.debug import run_debug
-
- args = MagicMock()
- args.debug_command = None
-
- run_debug(args)
-
- out = capsys.readouterr().out
- assert "hermes debug" in out
- assert "share" in out
- assert "delete" in out
-
- def test_share_subcommand_routes(self, hermes_home):
- from hermes_cli.debug import run_debug
-
- args = MagicMock()
- args.debug_command = "share"
- args.lines = 200
- args.expire = 7
- args.local = True
- args.nous = False
-
- with patch("hermes_cli.dump.run_dump"):
- run_debug(args)
# ---------------------------------------------------------------------------
@@ -603,15 +494,6 @@ class TestRunDebug:
# Delete / auto-delete
# ---------------------------------------------------------------------------
-class TestExtractPasteId:
- def test_paste_rs_url(self):
- from hermes_cli.debug import _extract_paste_id
- assert _extract_paste_id("https://paste.rs/abc123") == "abc123"
-
-
- def test_empty_returns_none(self):
- from hermes_cli.debug import _extract_paste_id
- assert _extract_paste_id("") is None
class TestDeletePaste:
@@ -637,7 +519,7 @@ class TestDeletePaste:
paste cannot be deleted and will expire on its own (#106164)."""
from hermes_cli.debug import delete_paste
- with pytest.raises(ValueError, match="cannot be deleted.*expire on their own"):
+ with pytest.raises(ValueError):
delete_paste("https://dpaste.com/ABC123")
@@ -768,82 +650,10 @@ class TestSweepExpiredPastes:
assert len(_load_pending()) == 1
-class TestRunDebugSweepsOnInvocation:
- """``run_debug`` must sweep expired pastes on every invocation."""
-
- def test_run_debug_calls_sweep(self, hermes_home):
- from hermes_cli.debug import run_debug
-
- args = MagicMock()
- args.debug_command = None # default → prints help
-
- with patch("hermes_cli.debug._sweep_expired_pastes") as mock_sweep:
- run_debug(args)
-
- mock_sweep.assert_called_once()
-
-
-class TestRunDebugDelete:
-
- def test_handles_delete_failure(self, capsys):
- from hermes_cli.debug import run_debug_delete
-
- args = MagicMock()
- args.urls = ["https://paste.rs/abc"]
-
- with patch("hermes_cli.debug.delete_paste",
- side_effect=Exception("network error")):
- run_debug_delete(args)
-
- out = capsys.readouterr().out
- assert "Could not delete" in out
-
-
-class TestShareIncludesAutoDelete:
- """Verify that run_debug_share schedules auto-deletion and prints TTL."""
-
-
- def test_share_shows_privacy_notice(self, hermes_home, capsys):
- from hermes_cli.debug import run_debug_share
-
- args = MagicMock()
- args.lines = 50
- args.expire = 7
- args.local = False
- args.nous = False
-
- with patch("hermes_cli.dump.run_dump"), \
- patch("hermes_cli.debug.upload_to_pastebin",
- return_value="https://paste.rs/test"), \
- patch("hermes_cli.debug._schedule_auto_delete"):
- run_debug_share(args)
-
- out = capsys.readouterr().out
- assert "PUBLIC paste service" in out
- assert "NOT redacted" in out
- def test_share_output_warns_on_dpaste_fallback(self, hermes_home, capsys):
- """With dpaste.com URLs the output must not promise 6-hour auto-delete
- or a working `hermes debug delete` (#106164)."""
- from hermes_cli.debug import run_debug_share
- args = MagicMock()
- args.lines = 50
- args.expire = 1
- args.local = False
- args.nous = False
- with patch("hermes_cli.dump.run_dump"), \
- patch("hermes_cli.debug.upload_to_pastebin",
- return_value="https://dpaste.com/TEST"), \
- patch("hermes_cli.debug._schedule_auto_delete"):
- run_debug_share(args)
- out = capsys.readouterr().out
- assert "fell back to dpaste.com" in out
- assert "CANNOT be deleted" in out
- assert "To delete now" not in out
- assert "paste.rs pastes will auto-delete in 6 hours" in out
# ---------------------------------------------------------------------------
@@ -912,13 +722,6 @@ class TestBuildDebugShare:
class TestCollectShareBundle:
- def test_no_redact_omits_banner(self, hermes_home):
- from hermes_cli.debug import collect_share_bundle
-
- with patch("hermes_cli.dump.run_dump"):
- bundle = collect_share_bundle(log_lines=50, redact=False)
-
- assert "redacted at upload time" not in bundle["report"]
def test_redaction_keeps_secrets_out(self, hermes_home):
from hermes_cli.debug import collect_share_bundle
@@ -997,7 +800,6 @@ class TestRunDebugShareNous:
run_debug_share(self._args())
out = capsys.readouterr().out
- assert "Nous-INTERNAL" in out
assert "https://support.example.com/diagnostics/id-1" in out
assert "2026-06-20T00:00:00Z" in out
# The blob passed to share_to_nous must be gzip bytes.
@@ -1015,7 +817,6 @@ class TestRunDebugShareNous:
run_debug_share(self._args())
assert exc.value.code == 1
err = capsys.readouterr().err
- assert "Nous upload failed" in err
assert "--local" in err
def test_nous_does_not_touch_pastebin(self, hermes_home):
@@ -1059,7 +860,6 @@ class TestDebugSlashCommand:
def test_bare_debug_defaults_to_paste(self):
c = self._captured("/debug")
assert c["nous"] is False and c["local"] is False
- assert c["lines"] == 200 and c["expire"] == 7
# The slash command IS the consent action → skip the [y/N] prompt
# (input() would hang inside prompt_toolkit's event loop).
assert c["yes"] is True
@@ -1070,10 +870,6 @@ class TestDebugSlashCommand:
assert c["nous"] is True
- def test_no_arg_default_keyword(self):
- # Calling with no cmd_original (legacy callers) must still work.
- c = self._captured("")
- assert c["nous"] is False and c["local"] is False
class TestShareConsentGate:
@@ -1108,9 +904,7 @@ class TestShareConsentGate:
assert exc.value.code == 1
mock_upload.assert_not_called()
- err = capsys.readouterr().err
- assert "Non-interactive mode requires --yes" in err
- assert "personal data" in err
+ assert "--yes" in capsys.readouterr().err
def test_local_never_prompts(self, hermes_home, capsys, monkeypatch):
diff --git a/tests/hermes_cli/test_default_interface_resolution.py b/tests/hermes_cli/test_default_interface_resolution.py
index 3f6216cd9af..acef54aded0 100644
--- a/tests/hermes_cli/test_default_interface_resolution.py
+++ b/tests/hermes_cli/test_default_interface_resolution.py
@@ -30,7 +30,6 @@ These tests pin that precedence at every layer that makes the decision:
from __future__ import annotations
-import os
from types import SimpleNamespace
import pytest
@@ -149,14 +148,6 @@ class TestWantsTuiEarly:
assert m._config_default_interface_early() == "tui"
assert m._wants_tui_early([]) is True
- def test_same_home_is_read_only_once(self, tmp_path, monkeypatch):
- (tmp_path / "config.yaml").write_text("display:\n interface: tui\n")
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- assert m._config_default_interface_early() == "tui"
-
- # The cache still spares the hot path a second YAML parse.
- (tmp_path / "config.yaml").write_text("display:\n interface: cli\n")
- assert m._config_default_interface_early() == "tui"
# ---------------------------------------------------------------------------
@@ -189,7 +180,3 @@ class TestParserFlags:
# ---------------------------------------------------------------------------
# config default — shipped default preserves classic behavior
# ---------------------------------------------------------------------------
-def test_default_config_interface_is_cli():
- from hermes_cli.config import DEFAULT_CONFIG
-
- assert DEFAULT_CONFIG["display"]["interface"] == "cli"
diff --git a/tests/hermes_cli/test_deferred_platform_client_tools.py b/tests/hermes_cli/test_deferred_platform_client_tools.py
index 245f8b691b8..0f5b626e177 100644
--- a/tests/hermes_cli/test_deferred_platform_client_tools.py
+++ b/tests/hermes_cli/test_deferred_platform_client_tools.py
@@ -166,20 +166,6 @@ def clean_registry():
class TestA2AClientToolsInCliProcess:
"""The issue's exact repro: a CLI/TUI process, no gateway startup."""
- def test_manifest_declares_the_client_tools(self):
- """The opt-in lives in the manifest, so it is pinned like any contract.
-
- Dropping ``provides_tools`` from plugin.yaml silently reverts a2a to
- the deferred-and-invisible behaviour of #78050, with every other test
- here still passing on the synthetic plugins — so assert it directly.
- """
- manifest_path = (
- Path(__file__).resolve().parents[2]
- / "plugins" / "platforms" / "a2a" / "plugin.yaml"
- )
- manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
-
- assert set(manifest.get("provides_tools") or []) == A2A_CLIENT_TOOLS
def test_a2a_toolset_resolves_without_materializing_the_platform(self):
from hermes_cli.plugins import PluginManager
diff --git a/tests/hermes_cli/test_desktop_install_after_update.py b/tests/hermes_cli/test_desktop_install_after_update.py
index ef0fc99a327..2e9b671ed7f 100644
--- a/tests/hermes_cli/test_desktop_install_after_update.py
+++ b/tests/hermes_cli/test_desktop_install_after_update.py
@@ -53,7 +53,7 @@ def test_stale_bundle_is_replaced_current_and_running_are_left_alone(rebuilt, tm
assert current_marker.read_text() == "untouched"
# A live app is reported, never swapped under.
assert _asar(running) == b"older"
- assert len(problems) == 1 and str(running) in problems[0] and "quit Hermes Desktop" in problems[0]
+ assert len(problems) == 1 and str(running) in problems[0]
def test_failed_swap_keeps_the_previous_bundle_launchable(rebuilt, tmp_path, monkeypatch):
@@ -69,6 +69,6 @@ def test_failed_swap_keeps_the_previous_bundle_launchable(rebuilt, tmp_path, mon
installed, problems = main_desktop._install_rebuilt_macos_bundles(rebuilt, [stale], running=set())
assert installed == []
- assert len(problems) == 1 and "previous app was kept" in problems[0]
+ assert len(problems) == 1
assert stale.is_dir() and _asar(stale) == b"stale"
assert not (stale.parent / "Hermes.app.hermes-update-new").exists()
diff --git a/tests/hermes_cli/test_desktop_lifecycle_windows_live.py b/tests/hermes_cli/test_desktop_lifecycle_windows_live.py
deleted file mode 100644
index 4a462ea03d6..00000000000
--- a/tests/hermes_cli/test_desktop_lifecycle_windows_live.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""LIVE Windows E2E for the Desktop-lifecycle cold-start skip (#76129/#76745).
-
-Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``
-lane). Exercises the REAL ownership predicate against REAL processes:
-
- 1. A real child process self-registers in the REAL spawn ledger as a
- ``serve`` purpose with THIS process as its live spawner — ownership
- must hold, and ``_pause_windows_gateways_for_update`` must return None
- (no cold-start plan) even with an autostart artifact present.
- 2. Kill the child (dead serve) — ownership drops, the pause plan carries
- ``cold_start_if_installed`` again.
- 3. Venv-holder fallback rung: a real venv-python process with true
- ``serve`` argv is detected by the scan and, having a live parent,
- confers ownership; the token classifier rejects a ``kanban
- --preserve-cache`` lookalike (the #90778 class the salvage fixed).
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-import time
-from pathlib import Path
-
-import pytest
-
-pytestmark = pytest.mark.skipif(
- sys.platform != "win32", reason="live Windows lifecycle E2E"
-)
-
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
-
-
-def sleeper():
- procs: list[subprocess.Popen] = []
-
- def _spawn(*tail: str) -> subprocess.Popen:
- p = subprocess.Popen(
- [sys.executable, "-c", "import time; time.sleep(120)", *tail],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
- procs.append(p)
- time.sleep(0.5)
- assert p.poll() is None
- return p
-
- yield _spawn
- for p in procs:
- if p.poll() is None:
- p.kill()
- p.wait()
-
-
-def _write_ledger(entries: list[dict]) -> None:
- from hermes_cli import process_identity as pid_mod
-
- path = pid_mod._ledger_path()
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(entries), encoding="utf-8")
-
-
-def _entry(proc: subprocess.Popen, purpose: str = "serve") -> dict:
- import psutil
-
- from hermes_cli import process_identity as pid_mod
-
- return {
- "install": pid_mod.install_id(None),
- "pid": proc.pid,
- "create_time": psutil.Process(proc.pid).create_time(),
- "purpose": purpose,
- "spawner_pid": os.getpid(),
- "spawner_create": psutil.Process(os.getpid()).create_time(),
- }
-
-
-def test_live_supervised_serve_suppresses_cold_start(sleeper, monkeypatch, tmp_path):
- from hermes_cli import gateway as hermes_gateway
- from hermes_cli import gateway_windows
- from hermes_cli import update_cmd
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- (tmp_path / ".hermes").mkdir()
-
- serve = sleeper()
- _write_ledger([_entry(serve)])
-
- assert update_cmd._desktop_owns_gateway_lifecycle() is True
-
- # Autostart artifact present + no gateway running: WITHOUT ownership the
- # pause phase would plan a cold start; WITH it, no plan.
- monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
- monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
- assert update_cmd._pause_windows_gateways_for_update() is None
-
- # Dead serve → ownership drops → plan returns.
- serve.kill()
- serve.wait()
- time.sleep(0.5)
- assert update_cmd._desktop_owns_gateway_lifecycle() is False
- token = update_cmd._pause_windows_gateways_for_update()
- assert token is not None and token.get("cold_start_if_installed") is True
-
-
-def test_holder_scan_fallback_respects_token_classifier(sleeper, monkeypatch, tmp_path):
- from hermes_cli import update_cmd
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- (tmp_path / ".hermes").mkdir()
- _write_ledger([]) # force the fallback rung
-
- # Real process whose argv carries genuine serve shape, visible to psutil.
- serve_like = sleeper("-m", "hermes_cli.main", "serve")
- # Lookalike from the #90778 class — must NOT confer ownership.
- kanban_like = sleeper("-m", "hermes_cli.main", "kanban", "--preserve-cache")
-
- def fake_holders():
- import psutil
-
- out = []
- for p in (serve_like, kanban_like):
- proc = psutil.Process(p.pid)
- out.append((p.pid, proc.name(), " ".join(proc.cmdline())))
- return out
-
- monkeypatch.setattr(
- "hermes_cli.main._detect_venv_python_processes", fake_holders
- )
-
- # serve-shaped holder with a live parent (us) → owns
- assert update_cmd._desktop_owns_gateway_lifecycle() is True
-
- # Only the kanban lookalike left → classifier rejects → does not own
- serve_like.kill()
- serve_like.wait()
- monkeypatch.setattr(
- "hermes_cli.main._detect_venv_python_processes",
- lambda: [fake_holders()[1]],
- )
- assert update_cmd._desktop_owns_gateway_lifecycle() is False
diff --git a/tests/hermes_cli/test_desktop_local_flag.py b/tests/hermes_cli/test_desktop_local_flag.py
index c581705ebdc..96eab2f6356 100644
--- a/tests/hermes_cli/test_desktop_local_flag.py
+++ b/tests/hermes_cli/test_desktop_local_flag.py
@@ -32,8 +32,3 @@ def test_local_flag_defaults_off():
assert args.local is False
-def test_local_flag_composes_with_build_flags():
- args = _parser().parse_args(["desktop", "--local", "--force-build"])
-
- assert args.local is True
- assert args.force_build is True
diff --git a/tests/hermes_cli/test_desktop_repo_discovery_config.py b/tests/hermes_cli/test_desktop_repo_discovery_config.py
deleted file mode 100644
index a5c711e8a18..00000000000
--- a/tests/hermes_cli/test_desktop_repo_discovery_config.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from hermes_cli.config import DEFAULT_CONFIG
-from hermes_cli.web_server_config import CONFIG_SCHEMA
-
-
-def test_desktop_repo_discovery_defaults_preserve_existing_behavior():
- desktop = DEFAULT_CONFIG["desktop"]
-
- assert desktop["repo_scan_enabled"] is True
- assert desktop["repo_scan_roots"] == []
- assert desktop["repo_scan_exclude_paths"] == []
-
-
-def test_desktop_repo_discovery_keys_are_in_generated_schema():
- assert CONFIG_SCHEMA["desktop.repo_scan_enabled"]["type"] == "boolean"
- assert CONFIG_SCHEMA["desktop.repo_scan_roots"]["type"] == "list"
- assert CONFIG_SCHEMA["desktop.repo_scan_exclude_paths"]["type"] == "list"
diff --git a/tests/hermes_cli/test_desktop_slash_registry.py b/tests/hermes_cli/test_desktop_slash_registry.py
index ef34fac950e..4983b73eed6 100644
--- a/tests/hermes_cli/test_desktop_slash_registry.py
+++ b/tests/hermes_cli/test_desktop_slash_registry.py
@@ -1,16 +1,12 @@
"""The desktop's offline slash block-list is a dump of COMMAND_REGISTRY, never hand-authored."""
-import importlib.util
import json
-import subprocess
-import sys
from pathlib import Path
from hermes_cli.commands import COMMAND_REGISTRY, desktop_surface_registry, resolve_command
ROOT = Path(__file__).resolve().parents[2]
DUMP = ROOT / "apps" / "desktop" / "src" / "lib" / "desktop-slash-registry.json"
-DUMP_SCRIPT = ROOT / "scripts" / "dump_desktop_slash_registry.py"
def test_committed_desktop_dump_matches_registry():
@@ -32,28 +28,5 @@ def test_desktop_surface_registry_covers_every_alias_with_its_canonical_value():
assert resolve_command(key) is not None, key
-def test_offered_built_ins_are_present_as_null_rows():
- # #116159: /context (alias /ctx) has no desktop disposition — offline the desktop
- # still needs its name to keep it out of the Skills group and on the built-in path.
- registry = desktop_surface_registry()
- assert "/context" in registry and registry["/context"] is None
- assert "/ctx" in registry and registry["/ctx"] is None
-def test_dump_script_check_mode_is_green_on_the_committed_json_and_red_on_drift(tmp_path):
- """``--check`` is the shell-usable twin of the equality test: 0 on the committed file, 1 on a stale copy."""
- proc = subprocess.run(
- [sys.executable, str(DUMP_SCRIPT), "--check"], cwd=ROOT, capture_output=True, text=True, timeout=120,
- )
- assert proc.returncode == 0, proc.stderr
-
- # Negative case in-process against a hand-edited copy: flipping one value must be caught.
- spec = importlib.util.spec_from_file_location("dump_desktop_slash_registry", DUMP_SCRIPT)
- mod = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(mod)
- stale = tmp_path / "desktop-slash-registry.json"
- payload = json.loads(DUMP.read_text(encoding="utf-8"))
- payload[next(iter(payload))] = {"desktop": "hand-edited"}
- stale.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- assert mod.check(stale) == 1
- assert mod.check(DUMP) == 0
diff --git a/tests/hermes_cli/test_desktop_swap_file_lock_retry.py b/tests/hermes_cli/test_desktop_swap_file_lock_retry.py
index 9e23f89bd72..16ba4a4aa3a 100644
--- a/tests/hermes_cli/test_desktop_swap_file_lock_retry.py
+++ b/tests/hermes_cli/test_desktop_swap_file_lock_retry.py
@@ -55,8 +55,7 @@ def test_swap_retries_transient_permission_error_then_promotes(tmp_path, monkeyp
assert promoted == live_exe
assert live_exe.read_text(encoding="utf-8") == "new"
- assert slept == [0.5, 1.0]
- assert sum("hit a file lock" in r.message for r in caplog.records) == 2
+ assert len(slept) == 2 # two transient locks → two backoff sleeps before the promotion
assert not staging.exists()
diff --git a/tests/hermes_cli/test_destructive_slash_confirm.py b/tests/hermes_cli/test_destructive_slash_confirm.py
index 591c95d16e3..0ac0541353d 100644
--- a/tests/hermes_cli/test_destructive_slash_confirm.py
+++ b/tests/hermes_cli/test_destructive_slash_confirm.py
@@ -6,7 +6,6 @@ don't have to construct a full HermesCLI (which requires extensive setup).
from __future__ import annotations
-import queue
from types import SimpleNamespace
from unittest.mock import patch
@@ -147,31 +146,6 @@ def test_confirm_destructive_slash_now_skips_modal():
assert result == "once"
-def test_confirm_destructive_slash_yes_flag_skips_modal():
- """``--yes`` flag is equivalent to ``now``."""
- from cli import HermesCLI
-
- def _explode(**_kw):
- raise AssertionError("modal must not be invoked when --yes present")
-
- self_ = SimpleNamespace(
- _app=None,
- _prompt_text_input_modal=_explode,
- )
- self_._normalize_slash_confirm_choice = _bound(
- HermesCLI._normalize_slash_confirm_choice, self_,
- )
- self_._split_destructive_skip = HermesCLI._split_destructive_skip
-
- with patch(
- "cli.load_cli_config",
- return_value={"approvals": {"destructive_slash_confirm": True}},
- ):
- result = _bound(HermesCLI._confirm_destructive_slash, self_)(
- "new", "detail", cmd_original="/new --yes My Session",
- )
-
- assert result == "once"
def test_confirm_destructive_slash_no_skip_token_still_prompts():
diff --git a/tests/hermes_cli/test_destructive_slash_confirm_gate.py b/tests/hermes_cli/test_destructive_slash_confirm_gate.py
index f8dcd4425d6..c2cdd81fbbf 100644
--- a/tests/hermes_cli/test_destructive_slash_confirm_gate.py
+++ b/tests/hermes_cli/test_destructive_slash_confirm_gate.py
@@ -15,10 +15,6 @@ from hermes_cli.config import DEFAULT_CONFIG
class TestDestructiveSlashConfirmDefault:
- def test_default_config_has_the_key(self):
- approvals = DEFAULT_CONFIG.get("approvals")
- assert isinstance(approvals, dict)
- assert "destructive_slash_confirm" in approvals
def test_default_is_true(self):
# New installs confirm by default — destructive commands must not
diff --git a/tests/hermes_cli/test_dingtalk_auth.py b/tests/hermes_cli/test_dingtalk_auth.py
index d3c3b2382b8..9fa85172333 100644
--- a/tests/hermes_cli/test_dingtalk_auth.py
+++ b/tests/hermes_cli/test_dingtalk_auth.py
@@ -156,14 +156,5 @@ class TestRenderQR:
# ---------------------------------------------------------------------------
-class TestConfigOverrides:
-
- def test_base_url_default(self, monkeypatch):
- monkeypatch.delenv("DINGTALK_REGISTRATION_BASE_URL", raising=False)
- # Force module reload to pick up current env
- import importlib
- import hermes_cli.dingtalk_auth as mod
- importlib.reload(mod)
- assert mod.REGISTRATION_BASE_URL == "https://oapi.dingtalk.com"
diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.py
index c026df0d438..c61a312c0f1 100644
--- a/tests/hermes_cli/test_doctor.py
+++ b/tests/hermes_cli/test_doctor.py
@@ -1,21 +1,16 @@
"""Tests for hermes_cli.doctor."""
import importlib.util
-import os
import subprocess
import sys
import types
import io
import contextlib
from argparse import Namespace
-from types import SimpleNamespace
import pytest
-import hermes_cli.doctor as doctor
-import hermes_constants
from hermes_cli import config as config_mod
-import hermes_cli.gateway as gateway_cli
from hermes_cli import doctor as doctor_mod
from hermes_cli.doctor_config import _has_provider_env_config
import shutil
@@ -27,12 +22,6 @@ from tools import browser_tool_install as bt_install
class TestDoctorPlatformHints:
- def test_termux_package_hint(self, monkeypatch):
- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")
- monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")
- assert hermes_constants.is_termux() is True
- assert doctor_platform._python_install_cmd() == "python -m pip install"
- assert doctor_platform._system_package_install_cmd("ripgrep") == "pkg install ripgrep"
def test_sqlite_upgrade_hint_recreates_docker_containers(self, monkeypatch):
@@ -41,13 +30,8 @@ class TestDoctorPlatformHints:
hint = doctor_platform._sqlite_upgrade_hint()
assert "docker pull nousresearch/hermes-agent:latest" in hint
- assert "recreate all Hermes containers" in hint
assert "hermes update" not in hint
- def test_sqlite_upgrade_hint_keeps_git_runtime_repair(self):
- hint = doctor_platform._sqlite_upgrade_hint("git")
-
- assert "run `hermes update`" in hint
def test_sqlite_upgrade_hint_uses_pkg_for_apt_managed_install(self):
hint = doctor_platform._sqlite_upgrade_hint("apt")
@@ -135,7 +119,6 @@ class TestDoctorToolAvailabilitySummary:
rows = doctor_tools._doctor_web_capability_rows()
assert rows
assert all(status == "warn" for status, _, _ in rows)
- assert any("firecrawl selected; provider not configured" in detail for _, _, detail in rows)
def test_web_capability_rows_ok_when_provider_ready(self, monkeypatch):
class _Ready:
@@ -155,10 +138,7 @@ class TestDoctorToolAvailabilitySummary:
)
rows = doctor_tools._doctor_web_capability_rows()
- assert rows == [
- ("ok", "web search", "(ddgs)"),
- ("ok", "web extract", "(ddgs)"),
- ]
+ assert rows and all(status == "ok" for status, _, _ in rows)
class TestDoctorEnvFileEncoding:
@@ -265,16 +245,6 @@ class TestDoctorToolAvailabilityOverrides:
-class TestHonchoDoctorConfigDetection:
- def test_reports_configured_when_enabled_with_api_key(self, monkeypatch):
- fake_config = SimpleNamespace(enabled=True, api_key="***")
-
- monkeypatch.setattr(
- "plugins.memory.honcho.client.HonchoClientConfig.from_global_config",
- lambda: fake_config,
- )
-
- assert doctor_state._honcho_is_configured_for_doctor()
@@ -303,16 +273,8 @@ def test_doctor_reports_vercel_backend_diagnostics(monkeypatch, tmp_path):
doctor_mod.run_doctor(Namespace(fix=False))
out = buf.getvalue()
- assert "Vercel runtime" in out
- assert "python3.13" in out
- assert "Vercel custom disk unsupported" in out
- assert "Vercel auth incomplete" in out
- assert "VERCEL_PROJECT_ID" in out
- assert "Vercel auth mode: incomplete access token" in out
- assert "Vercel auth present env: VERCEL_TOKEN, VERCEL_TEAM_ID" in out
- assert "Vercel auth missing env: VERCEL_PROJECT_ID" in out
- assert "super-secret-value" not in out
- assert "snapshot filesystem only" in out
+ assert "VERCEL_PROJECT_ID" in out # names the missing auth var
+ assert "super-secret-value" not in out # never echoes the token value
# ── Memory provider section (doctor should only check the *active* provider) ──
@@ -413,40 +375,6 @@ class TestDoctorMemoryProviderSection:
assert ("Built-in memory files disabled by config" in out) is not memory_enabled
-def test_run_doctor_termux_treats_docker_and_browser_warnings_as_expected(monkeypatch, tmp_path):
- helper = TestDoctorMemoryProviderSection()
- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")
- monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")
-
- real_which = shutil.which
-
- def fake_which(cmd):
- if cmd in {"docker", "node", "npm"}:
- return None
- return real_which(cmd)
-
- monkeypatch.setattr(shutil, "which", fake_which)
- # The docker check resolves through find_docker() (which also knows the macOS Docker
- # Desktop paths), so pin it off the host instead of relying on PATH alone.
- from hermes_cli import doctor_tools
-
- monkeypatch.setattr(doctor_tools, "find_docker", lambda: None)
-
- out = helper._run_doctor_and_capture(monkeypatch, tmp_path, provider="")
-
- assert "Docker backend is not available inside Termux" in out
- assert "Node.js not found (browser tools are optional in the tested Termux path)" in out
- assert "Install Node.js on Termux with: pkg install nodejs" in out
- assert "Termux browser setup:" in out
- assert "1) pkg install nodejs" in out
- assert "2) npm install -g agent-browser" in out
- assert "3) agent-browser install" in out
- assert "Termux compatibility fallbacks:" in out
- assert "use .[termux-all] for broad compatibility" in out
- assert "Matrix E2EE extra is excluded on Termux" in out
- assert "Local faster-whisper extra is excluded on Termux" in out
- assert "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY)." in out
- assert "docker not found (optional)" not in out
def test_run_doctor_accepts_named_provider_from_providers_section(monkeypatch, tmp_path):
@@ -626,7 +554,6 @@ def test_run_doctor_flags_missing_credentials_for_active_openrouter_provider(mon
out = buf.getvalue()
assert "model.provider 'openrouter' is set but no API key is configured" in out
- assert "No credentials found for provider 'openrouter'." in out
@pytest.mark.parametrize(
@@ -826,48 +753,6 @@ def test_run_doctor_accepts_kimi_coding_cn_provider(monkeypatch, tmp_path):
assert "model.provider 'kimi-coding-cn' is not a recognised provider" not in out
-def test_run_doctor_termux_does_not_mark_browser_available_without_agent_browser(monkeypatch, tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir(parents=True, exist_ok=True)
- (home / "config.yaml").write_text("memory: {}\n", encoding="utf-8")
- project = tmp_path / "project"
- project.mkdir(exist_ok=True)
-
- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")
- monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")
- monkeypatch.setattr(doctor_mod, "HERMES_HOME", home)
- monkeypatch.setattr(doctor_mod, "PROJECT_ROOT", project)
- monkeypatch.setattr(doctor_mod, "_DHH", str(home))
- monkeypatch.setattr(shutil, "which", lambda cmd: "/data/data/com.termux/files/usr/bin/node" if cmd in {"node", "npm"} else None)
-
- fake_model_tools = types.SimpleNamespace(
- check_tool_availability=lambda *a, **kw: (["terminal"], [{"name": "browser", "env_vars": [], "tools": ["browser_navigate"]}]),
- TOOLSET_REQUIREMENTS={
- "terminal": {"name": "terminal"},
- "browser": {"name": "browser"},
- },
- )
- monkeypatch.setitem(sys.modules, "model_tools", fake_model_tools)
-
- try:
- from hermes_cli import auth as _auth_mod
- monkeypatch.setattr(_auth_mod, "get_nous_auth_status_local", lambda: {})
- monkeypatch.setattr(_auth_mod, "get_codex_auth_status", lambda: {})
- monkeypatch.setattr(_auth_mod, "get_xai_oauth_auth_status", lambda: {})
- except Exception:
- pass
-
- import io, contextlib
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- doctor_mod.run_doctor(Namespace(fix=False))
- out = buf.getvalue()
-
- assert "✓ browser" not in out
- assert "browser" in out
- assert "system dependency not met" in out
- assert "agent-browser is not installed (expected in the tested Termux path)" in out
- assert "npm install -g agent-browser && agent-browser install" in out
def _doctor_env_for_agent_browser(monkeypatch, tmp_path):
@@ -1132,75 +1017,9 @@ def test_run_doctor_opencode_go_skips_invalid_models_probe(monkeypatch, tmp_path
class TestGitHubTokenCheck:
"""Tests for GitHub token / gh auth detection in doctor."""
- @staticmethod
- def _isolate_home(monkeypatch, home):
- """Point doctor at the temp HERMES_HOME.
- ``run_doctor`` reads the module-level ``HERMES_HOME`` constant (cached
- at import time), NOT the env var — so ``setenv("HERMES_HOME")`` alone
- leaves doctor probing the REAL ~/.hermes. On a dev machine with a
- large state.db that meant a multi-minute ``PRAGMA integrity_check``
- that blew the 300s per-file budget and killed the whole file.
- """
- monkeypatch.setattr(doctor_mod, "HERMES_HOME", home)
- monkeypatch.setattr(doctor_mod, "_DHH", str(home))
- monkeypatch.setenv("HERMES_HOME", str(home))
- def test_no_token_and_not_gh_authenticated_shows_warn(self, monkeypatch, tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir(parents=True, exist_ok=True)
- self._isolate_home(monkeypatch, home)
- monkeypatch.setenv("PATH", "/nonexistent") # gh not found
- from hermes_cli.doctor import run_doctor
- import io, contextlib
-
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- run_doctor(Namespace(fix=False))
- out = buf.getvalue()
-
- assert "No GITHUB_TOKEN" in out
- assert "60 req/hr" in out
-
-
- def test_gh_authenticated_without_env_token_shows_ok(self, monkeypatch, tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir(parents=True, exist_ok=True)
- self._isolate_home(monkeypatch, home)
- # No GITHUB_TOKEN or GH_TOKEN
- monkeypatch.delenv("GITHUB_TOKEN", raising=False)
- monkeypatch.delenv("GH_TOKEN", raising=False)
-
- # Mock gh to return success
- import shutil
- real_which = shutil.which
- def mock_which(cmd):
- return "/usr/local/bin/gh" if cmd == "gh" else real_which(cmd)
- monkeypatch.setattr(shutil, "which", mock_which)
-
- call_log = []
- def mock_run(cmd, **kwargs):
- call_log.append(cmd)
- if cmd[:2] == ["gh", "auth"]:
- result = types.SimpleNamespace(returncode=0, stdout="", stderr="")
- else:
- result = types.SimpleNamespace(returncode=1, stdout="", stderr="")
- return result
-
- import subprocess
- monkeypatch.setattr(subprocess, "run", mock_run)
-
- from hermes_cli.doctor import run_doctor
- import io, contextlib
-
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- run_doctor(Namespace(fix=False))
- out = buf.getvalue()
-
- assert "gh auth" in str(call_log) or any(c[0] == "gh" for c in call_log), f"gh not called: {call_log}"
- assert "GitHub authenticated via gh CLI" in out or "token configured" in out
def test_gh_authenticated_on_gh_without_authenticated_json_field(self, monkeypatch):
@@ -1215,7 +1034,6 @@ class TestGitHubTokenCheck:
return types.SimpleNamespace(returncode=1, stdout=b"", stderr=b"unknown JSON field")
return types.SimpleNamespace(returncode=0, stdout=b"", stderr=b"Logged in to github.com")
- import subprocess
monkeypatch.setattr(subprocess, "run", gh_2_98)
assert doctor_state._gh_authenticated() is True
@@ -1326,22 +1144,8 @@ def test_run_doctor_ignores_invalid_direct_keys_when_oauth_fallback_is_healthy(
assert unexpected_issue not in out
-def test_has_healthy_oauth_fallback_returns_false_for_unknown_provider():
- from hermes_cli.doctor import _has_healthy_oauth_fallback_for_apikey_provider
- assert _has_healthy_oauth_fallback_for_apikey_provider("unknown-provider") is False
-class TestHasHealthyOauthFallbackForXai:
-
-
- def test_returns_false_when_xai_import_unavailable(self, monkeypatch):
- import sys
- # Simulate get_xai_oauth_auth_status missing from auth module
- monkeypatch.delattr("hermes_cli.auth.get_xai_oauth_auth_status", raising=False)
- # Force doctor module to re-import the function
- monkeypatch.delitem(sys.modules, "hermes_cli.doctor", raising=False)
- from hermes_cli.doctor import _has_healthy_oauth_fallback_for_apikey_provider
- assert _has_healthy_oauth_fallback_for_apikey_provider("xai") is False
# ---------------------------------------------------------------------------
@@ -1444,67 +1248,6 @@ class TestDoctorXaiOAuthStatus:
# ---------------------------------------------------------------------------
-class TestDoctorCodexCliHintPlacement:
- """The `codex CLI not installed` hint belongs under OpenAI Codex auth.
-
- Regression for #27975: the hint used to be emitted as a standalone block
- after all auth-provider rows, so it visually attached to whichever
- provider happened to print last (MiniMax OAuth in the reported repro),
- reading as remediation for an unrelated provider.
- """
-
- def _run(self, monkeypatch, tmp_path, *, codex_logged_in: bool, codex_cli_present: bool) -> str:
- home = tmp_path / ".hermes"
- home.mkdir(parents=True, exist_ok=True)
- (home / "config.yaml").write_text("memory: {}\n", encoding="utf-8")
- project = tmp_path / "project"
- project.mkdir(exist_ok=True)
-
- monkeypatch.setattr(doctor_mod, "HERMES_HOME", home)
- monkeypatch.setattr(doctor_mod, "PROJECT_ROOT", project)
- monkeypatch.setattr(doctor_mod, "_DHH", str(home))
-
- fake_model_tools = types.SimpleNamespace(
- check_tool_availability=lambda *a, **kw: ([], []),
- TOOLSET_REQUIREMENTS={},
- )
- monkeypatch.setitem(sys.modules, "model_tools", fake_model_tools)
-
- from hermes_cli import auth as _auth_mod
- monkeypatch.setattr(_auth_mod, "get_nous_auth_status_local", lambda: {"logged_in": False})
- monkeypatch.setattr(_auth_mod, "get_codex_auth_status", lambda: {"logged_in": codex_logged_in})
- monkeypatch.setattr(_auth_mod, "get_minimax_oauth_auth_status", lambda: {"logged_in": False})
- monkeypatch.setattr(_auth_mod, "get_xai_oauth_auth_status", lambda: {"logged_in": False})
-
- real_which = shutil.which
- monkeypatch.setattr(
- shutil,
- "which",
- lambda cmd: ("/usr/local/bin/codex" if codex_cli_present else None) if cmd == "codex" else real_which(cmd),
- )
-
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- doctor_mod.run_doctor(Namespace(fix=False))
- return buf.getvalue()
-
- @staticmethod
- def _hint_line() -> str:
- return "codex CLI not installed"
-
- def test_hint_appears_under_codex_auth_when_missing(self, monkeypatch, tmp_path):
- out = self._run(monkeypatch, tmp_path, codex_logged_in=False, codex_cli_present=False)
- lines = out.splitlines()
- codex_idx = next(i for i, l in enumerate(lines) if "OpenAI Codex auth" in l)
- hint_idx = next(i for i, l in enumerate(lines) if self._hint_line() in l)
- minimax_idx = next(i for i, l in enumerate(lines) if "MiniMax OAuth" in l)
- # Hint must sit between Codex auth and the next provider row (#27975).
- assert codex_idx < hint_idx < minimax_idx
-
- def test_hint_suppressed_when_codex_cli_present(self, monkeypatch, tmp_path):
- out = self._run(monkeypatch, tmp_path, codex_logged_in=False, codex_cli_present=True)
- assert "OpenAI Codex auth" in out
- assert self._hint_line() not in out
class TestDoctorStaleMaxIterationsDrift:
@@ -1520,7 +1263,6 @@ class TestDoctorStaleMaxIterationsDrift:
def _run_config_section(self, monkeypatch, tmp_path, *, fix, ghost, cfg_turns,
os_environ_value=None):
- import pathlib
import contextlib
import io
from argparse import Namespace
@@ -1604,7 +1346,7 @@ class TestDoctorLegacyCustomProvidersResidue:
out, finding = self._run(tmp_path, (
"custom_providers:\n - name: Local (8283)\n base_url: http://127.0.0.1:8283/v1\n"
"providers:\n other:\n api: http://127.0.0.1:8290/v1\n"))
- assert "Legacy custom_providers entry 'Local (8283)' has no providers: twin" in out
+ assert "Local (8283)" in out
assert finding.manual_issues and "providers.<key>.api: http://127.0.0.1:8283/v1" in finding.manual_issues[0]
assert finding.fixed == 0 and finding.issues == [] # warn-only: no --fix rewrite of config.yaml
@@ -1630,213 +1372,13 @@ class TestDoctorDeprecatedConfigAndEnv:
assert doctor_config.collect_deprecated_env_vars({}) == []
assert doctor_config.collect_deprecated_env_vars(None) == []
- def test_hermes_tool_progress_warning_says_unsupported_since_floor(self):
- """HERMES_TOOL_PROGRESS lost its last consumer (the retired v3→4
- migration) when the v12 support floor landed — doctor must say the
- variable is ignored rather than merely 'deprecated but read'."""
- findings = dict(
- doctor_config.collect_deprecated_env_vars({"HERMES_TOOL_PROGRESS": "true"})
- )
- assert "ignored/unsupported since config floor v12" in findings["HERMES_TOOL_PROGRESS"]
- # The MODE variant is still read by the gateway fallback → keeps the
- # plain deprecation wording.
- mode = dict(
- doctor_config.collect_deprecated_env_vars({"HERMES_TOOL_PROGRESS_MODE": "all"})
- )
- assert mode["HERMES_TOOL_PROGRESS_MODE"] == "display.tool_progress in config.yaml"
-
- def _run_doctor_with_config(self, monkeypatch, tmp_path, *, config_yaml: str, env_text: str = ""):
- hermes_home = tmp_path / ".hermes"
- hermes_home.mkdir(parents=True)
- (hermes_home / "config.yaml").write_text(config_yaml, encoding="utf-8")
- env_body = env_text if env_text else "OPENAI_API_KEY=sk-test\n"
- (hermes_home / ".env").write_text(env_body, encoding="utf-8")
-
- monkeypatch.setattr(doctor_mod, "HERMES_HOME", hermes_home)
- monkeypatch.setattr(doctor_mod, "get_hermes_home", lambda: hermes_home)
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- # Clear process-level legacy env so tests only see the on-disk .env.
- for k in (
- "HERMES_TOOL_PROGRESS",
- "HERMES_TOOL_PROGRESS_MODE",
- "TERMINAL_CWD",
- "MESSAGING_CWD",
- "QQ_HOME_CHANNEL",
- "QQ_HOME_CHANNEL_NAME",
- ):
- monkeypatch.delenv(k, raising=False)
-
- fake_model_tools = types.SimpleNamespace(
- check_tool_availability=lambda *a, **kw: (_ for _ in ()).throw(SystemExit(0)),
- TOOLSET_REQUIREMENTS={},
- )
- monkeypatch.setitem(sys.modules, "model_tools", fake_model_tools)
-
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf), pytest.raises(SystemExit):
- doctor_mod.run_doctor(Namespace(fix=False))
- return buf.getvalue(), hermes_home
- def test_report_does_not_count_as_blocking_issue(self, monkeypatch, tmp_path, capsys):
- """report_deprecated_config_and_env is warn-only — no issues list mutation."""
- findings = doctor_config.report_deprecated_config_and_env(
- {"delegation": {"max_async_children": 2}},
- {"HERMES_TOOL_PROGRESS_MODE": "verbose"},
- )
- out = capsys.readouterr().out
- assert len(findings) == 2
- assert "Deprecated: delegation.max_async_children" in out
- assert "Deprecated: HERMES_TOOL_PROGRESS_MODE" in out
- assert "⚠" in out or "Deprecated" in out
-class TestMacOSTCCGrants:
- """macOS TCC grant persistence check (issue #86385)."""
- def test_silent_on_non_macos(self, monkeypatch, capsys, tmp_path):
- """Non-macOS: the check must produce no output even with a bundle present."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "linux")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- doctor_platform.check_macos_tcc_grants()
- assert capsys.readouterr().out == ""
-
- def test_silent_when_no_desktop_bundle(self, monkeypatch, capsys):
- """No locally-built desktop bundle: nothing to check, no output."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(doctor_platform, "_desktop_app_bundle", lambda: None)
- doctor_platform.check_macos_tcc_grants()
- assert capsys.readouterr().out == ""
-
- def test_warns_on_cdhash_pinned_dr(self, monkeypatch, capsys, tmp_path):
- """Pre-#73681 builds have a cdhash-pinned DR → warn that grants reset."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- monkeypatch.setattr(
- doctor_platform,
- "_macos_desktop_dr",
- lambda app: 'designated => identifier "com.nousresearch.hermes" and cdhash H"97e692f3890f781fa0ad5ad6cb9d769cfaf42628"',
- )
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "TCC grants will reset after every update" in out
- assert "cdhash-pinned" in out
- assert "hermes update" in out
-
- def test_ok_and_repair_info_on_identifier_dr(self, monkeypatch, capsys, tmp_path):
- """Post-#73681 identifier-only DR → stable + stale-grant repair info."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- monkeypatch.setattr(
- doctor_platform,
- "_macos_desktop_dr",
- lambda app: 'designated => identifier "com.nousresearch.hermes"',
- )
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "TCC signing identity is stable" in out
- assert "identifier-pinned" in out
- # Identifier-pinned is stable but not the strongest anchor — the check
- # should point at the cert-anchored upgrade path.
- assert "--setup-tcc-identity" in out
- assert "tccutil reset ScreenCapture com.nousresearch.hermes" in out
- assert "toggle" in out
- assert "relaunch" in out
-
- def test_ok_on_certificate_anchored_dr(self, monkeypatch, capsys, tmp_path):
- """A cert-anchored DR (hermes desktop --setup-tcc-identity, or a
- notarized release) classifies as stable in its own class — no upgrade
- hint, still prints the stale-grant repair info."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- monkeypatch.setattr(
- doctor_platform,
- "_macos_desktop_dr",
- lambda app: 'designated => identifier "com.nousresearch.hermes" and certificate root = H"aabbcc"',
- )
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "TCC signing identity is stable" in out
- assert "certificate-anchored" in out
- assert "--setup-tcc-identity" not in out
- assert "tccutil reset ScreenCapture com.nousresearch.hermes" in out
-
- def test_warns_when_dr_unreadable(self, monkeypatch, capsys, tmp_path):
- """codesign failure → warn, never crash."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- monkeypatch.setattr(doctor_platform, "_macos_desktop_dr", lambda app: None)
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "could not read code-signing requirement" in out
-
- def test_warns_when_dr_empty_string(self, monkeypatch, capsys, tmp_path):
- """Empty DR output must not false-positive as a stable identity."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- monkeypatch.setattr(doctor_platform, "_macos_desktop_dr", lambda app: "")
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "could not read code-signing requirement" in out
- assert "stable" not in out
-
- def test_warns_when_codesign_times_out(self, monkeypatch, capsys, tmp_path):
- """A hanging codesign must degrade to the unreadable-DR warning, never crash."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
-
- def _timeout(*args, **kwargs):
- raise subprocess.TimeoutExpired(cmd=["codesign"], timeout=15)
-
- monkeypatch.setattr(subprocess, "run", _timeout)
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "could not read code-signing requirement" in out
- assert "stable" not in out
-
- def test_warns_when_codesign_missing(self, monkeypatch, capsys, tmp_path):
- """No codesign binary → same graceful unreadable-DR warning."""
- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- doctor_platform,
- "_desktop_app_bundle",
- lambda: tmp_path / "Hermes.app",
- )
- monkeypatch.setattr(shutil, "which", lambda _name: None)
- doctor_platform.check_macos_tcc_grants()
- out = capsys.readouterr().out
- assert "could not read code-signing requirement" in out
- assert "stable" not in out
def test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):
@@ -1852,15 +1394,6 @@ def test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):
assert "Browserbase" in out
-def test_run_doctor_reports_lightpanda_ok(monkeypatch, tmp_path):
- helper = TestDoctorMemoryProviderSection()
-
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: True)
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback.lightpanda_engine_status", lambda: (True, "Browser Use mode"))
- monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: "/opt/lightpanda")
- out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
- assert "Lightpanda" in out
- assert "shadowed" not in out
def test_run_doctor_warns_when_lightpanda_binary_missing(monkeypatch, tmp_path):
diff --git a/tests/hermes_cli/test_doctor_audit_remedy.py b/tests/hermes_cli/test_doctor_audit_remedy.py
index 12bf1360978..c0055f9f98f 100644
--- a/tests/hermes_cli/test_doctor_audit_remedy.py
+++ b/tests/hermes_cli/test_doctor_audit_remedy.py
@@ -14,7 +14,6 @@ import json
import subprocess
from unittest.mock import patch
-import pytest
from hermes_cli import doctor_tools
@@ -48,11 +47,6 @@ def test_root_remedy_never_prescribes_local_audit_fix(capsys):
assert issues == ["Browser tools (agent-browser) has 2 npm vulnerabilities"]
-def test_workspace_remedy_still_names_lockfile_bump(capsys):
- out, _ = _run_audit_one(capsys, ["--workspace", "web"], _audit_json(critical=1))
- assert "run: cd" not in out
- assert "npm audit fix" not in out
- assert "lockfile bump" in out
def test_clean_tree_reports_no_known_vulnerabilities(capsys):
diff --git a/tests/hermes_cli/test_doctor_command_install.py b/tests/hermes_cli/test_doctor_command_install.py
index c6b2da7d150..32d928b0ebe 100644
--- a/tests/hermes_cli/test_doctor_command_install.py
+++ b/tests/hermes_cli/test_doctor_command_install.py
@@ -94,58 +94,7 @@ class TestDoctorCommandInstallation:
assert cmd_link.is_symlink()
assert cmd_link.resolve() == hermes_bin.resolve()
- @pytest.mark.skipif(sys.platform == "win32", reason="Symlink check is Unix-only")
- def test_missing_venv_entry_point_shows_warn(self, monkeypatch, tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir(parents=True, exist_ok=True)
- (home / "config.yaml").write_text("memory: {}\n", encoding="utf-8")
-
- project = tmp_path / "project"
- project.mkdir(exist_ok=True)
- # Do NOT create any venv entry point
-
- monkeypatch.setattr(doctor_mod, "HERMES_HOME", home)
- monkeypatch.setattr(doctor_mod, "PROJECT_ROOT", project)
- monkeypatch.setattr(doctor_mod, "_DHH", str(home))
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
-
- fake_model_tools = types.SimpleNamespace(
- check_tool_availability=lambda *a, **kw: ([], []),
- TOOLSET_REQUIREMENTS={},
- )
- monkeypatch.setitem(sys.modules, "model_tools", fake_model_tools)
- try:
- from hermes_cli import auth as _auth_mod
- monkeypatch.setattr(_auth_mod, "get_nous_auth_status", lambda: {})
- monkeypatch.setattr(_auth_mod, "get_codex_auth_status", lambda: {})
- except Exception:
- pass
- try:
- import httpx
- monkeypatch.setattr(httpx, "get", lambda *a, **kw: types.SimpleNamespace(status_code=200))
- except Exception:
- pass
-
- out = _run_doctor(fix=False)
- assert "Command Installation" in out
- assert "Venv entry point not found" in out
- @pytest.mark.skipif(sys.platform == "win32", reason="Symlink check is Unix-only")
- def test_termux_uses_prefix_bin(self, monkeypatch, tmp_path):
- """On Termux, the command link dir is $PREFIX/bin."""
- prefix_dir = tmp_path / "termux_prefix"
- prefix_bin = prefix_dir / "bin"
- prefix_bin.mkdir(parents=True)
-
- home, project, hermes_bin = _setup_doctor_env(monkeypatch, tmp_path)
-
- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")
- monkeypatch.setenv("PREFIX", str(prefix_dir))
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
-
- out = _run_doctor(fix=False)
- assert "Command Installation" in out
- assert "$PREFIX/bin" in out
diff --git a/tests/hermes_cli/test_doctor_journal_modes.py b/tests/hermes_cli/test_doctor_journal_modes.py
index 0a6ba46faf0..fc0ddf5d466 100644
--- a/tests/hermes_cli/test_doctor_journal_modes.py
+++ b/tests/hermes_cli/test_doctor_journal_modes.py
@@ -15,12 +15,9 @@ import sys
import pytest
-import hermes_cli.doctor as doctor
from hermes_cli.sqlite_safe_read import (
connect_tracked,
has_live_connection,
- track_connection,
- untrack_connection,
)
from hermes_cli import doctor_platform
@@ -115,14 +112,6 @@ class TestReadJournalMode:
assert mode is None
assert error == "file is empty"
- def test_short_file_reports_error(self, tmp_path):
- db = tmp_path / "state.db"
- db.write_bytes(b"SQLite f")
-
- mode, error = doctor_platform._read_journal_mode(db)
-
- assert mode is None
- assert "not a database" in error
def test_corrupt_file_reports_error(self, tmp_path):
db = tmp_path / "state.db"
@@ -133,16 +122,6 @@ class TestReadJournalMode:
assert mode is None
assert "not a database" in error
- def test_locked_database_is_still_readable(self, tmp_path):
- db = tmp_path / "state.db"
- _make_db(db)
- holder = sqlite3.connect(db, isolation_level=None)
- try:
- holder.execute("BEGIN EXCLUSIVE")
-
- assert doctor_platform._read_journal_mode(db) == ("rollback", None)
- finally:
- holder.close()
@pytest.mark.skipif(os.name == "nt", reason="chmod is a no-op on Windows")
@pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")
@@ -183,22 +162,6 @@ class TestLiveConnectionSafety:
so the probe must defer to the registry rather than open the file.
"""
- def test_probe_is_refused_while_a_tracked_connection_is_live(
- self, tmp_path, clean_registry
- ):
- db = tmp_path / "state.db"
- _make_db(db, journal_mode="WAL")
-
- track_connection(db)
- try:
- assert has_live_connection(db)
-
- mode, error = doctor_platform._read_journal_mode(db)
-
- assert mode is None
- assert error == "database is open in this process"
- finally:
- untrack_connection(db)
def test_probe_is_refused_for_a_real_tracked_connection(
self, tmp_path, clean_registry
diff --git a/tests/hermes_cli/test_doctor_live.py b/tests/hermes_cli/test_doctor_live.py
index 49d0f44b0be..c92d12d1b75 100644
--- a/tests/hermes_cli/test_doctor_live.py
+++ b/tests/hermes_cli/test_doctor_live.py
@@ -12,7 +12,6 @@ import pytest
from hermes_cli import doctor_live
from hermes_cli.doctor_live import (
- ProbeResult,
maybe_run_live_checks,
run_live_checks,
)
@@ -40,16 +39,6 @@ def _clean_env(monkeypatch):
class TestLiveFlagGating:
- def test_parser_has_live_flag_default_false(self):
- from hermes_cli.subcommands.doctor import build_doctor_parser
-
- parser = argparse.ArgumentParser()
- sub = parser.add_subparsers(dest="command")
- build_doctor_parser(sub, cmd_doctor=lambda a: None)
- args = parser.parse_args(["doctor"])
- assert args.live is False
- args = parser.parse_args(["doctor", "--live"])
- assert args.live is True
def test_no_live_flag_means_zero_probes(self, monkeypatch):
called = []
@@ -60,22 +49,7 @@ class TestLiveFlagGating:
assert result is None
assert called == []
- def test_missing_live_attr_means_zero_probes(self, monkeypatch):
- called = []
- monkeypatch.setattr(
- doctor_live, "run_live_checks",
- lambda *a, **k: called.append(True))
- assert maybe_run_live_checks(SimpleNamespace(), []) is None
- assert called == []
- def test_live_flag_runs_checks(self, monkeypatch):
- called = []
- monkeypatch.setattr(
- doctor_live, "run_live_checks",
- lambda issues, **k: called.append(issues) or [])
- issues: list[str] = []
- maybe_run_live_checks(_args(live=True), issues)
- assert called == [issues]
def test_live_check_crash_never_propagates(self, monkeypatch, capsys):
def _boom(*a, **k):
@@ -87,10 +61,6 @@ class TestLiveFlagGating:
class TestConfiguredOnlySelection:
- def test_all_unconfigured_all_skipped(self, capsys):
- results = run_live_checks([])
- assert results, "expected one result per backend"
- assert all(r.status == "skip" for r in results)
# No issues appended for skips.
def test_unconfigured_backends_do_not_touch_network(self, monkeypatch):
@@ -124,13 +94,6 @@ class TestConfiguredOnlySelection:
assert results["Firecrawl"].status == "fail"
assert any("FIRECRAWL" in i or "Firecrawl" in i for i in issues)
- def test_fal_probed_when_key_present(self, monkeypatch):
- monkeypatch.setenv("FAL_KEY", "fal-test")
- monkeypatch.setattr(
- doctor_live, "_http_get",
- lambda *a, **k: SimpleNamespace(status_code=200))
- results = {r.name: r for r in run_live_checks([])}
- assert results["FAL"].status == "pass"
def test_mcp_servers_probed_per_configured_server(self, monkeypatch):
monkeypatch.setattr(
@@ -290,23 +253,9 @@ class TestTimeoutHandling:
run_live_checks([])
assert seen["timeout"] == 3
- def test_default_timeout_is_10s(self, monkeypatch):
- monkeypatch.setenv("FIRECRAWL_API_KEY", "fc-test")
- seen = {}
-
- def _get(url, headers=None, timeout=None):
- seen["timeout"] = timeout
- return SimpleNamespace(status_code=200)
-
- monkeypatch.setattr(doctor_live, "_http_get", _get)
- run_live_checks([])
- assert seen["timeout"] == 10.0
class TestReadOnly:
- def test_probe_result_is_plain_record(self):
- r = ProbeResult(name="X", status="skip", detail="not configured")
- assert (r.name, r.status, r.detail) == ("X", "skip", "not configured")
def test_skips_never_append_issues(self, capsys):
issues: list[str] = []
diff --git a/tests/hermes_cli/test_doctor_terminal_backends.py b/tests/hermes_cli/test_doctor_terminal_backends.py
index 27414a39225..ae8f2121ad6 100644
--- a/tests/hermes_cli/test_doctor_terminal_backends.py
+++ b/tests/hermes_cli/test_doctor_terminal_backends.py
@@ -15,22 +15,8 @@ def _joined(capsys) -> str:
return capsys.readouterr().out
-def test_docker_missing_line_names_backend_and_setup_command(monkeypatch, capsys, issues):
- monkeypatch.setattr(doctor_tools, "find_docker", lambda: None)
- doctor_tools._check_docker_backend("docker", False, issues)
- out = _joined(capsys)
- assert "Docker or Podman not installed" in out and "'docker' terminal backend" in out
- assert "TERMINAL_ENV" not in out
- assert issues and "hermes setup terminal" in issues[0] and "Install Docker or Podman" in issues[0]
-def test_docker_daemon_down_line_says_start_docker_or_switch(monkeypatch, capsys, issues):
- monkeypatch.setattr(doctor_tools, "find_docker", lambda: "/usr/bin/docker")
- monkeypatch.setattr(doctor_tools, "_run_ok", lambda cmd, timeout, **kw: False)
- doctor_tools._check_docker_backend("docker", False, issues)
- out = _joined(capsys)
- assert "Docker daemon not running" in out and "'docker' terminal backend" in out
- assert issues and "Start Docker" in issues[0] and "hermes setup terminal" in issues[0]
def test_docker_backend_ready_when_only_podman_resolves(monkeypatch, capsys, issues):
@@ -45,30 +31,7 @@ def test_docker_backend_ready_when_only_podman_resolves(monkeypatch, capsys, iss
assert probed == [["/usr/bin/podman", "version"]]
-def test_podman_down_line_advises_the_machine_not_a_daemon(monkeypatch, capsys, issues):
- """Podman is daemonless: the fix is `podman machine start`, never "start a daemon"."""
- monkeypatch.setattr(doctor_tools, "find_docker", lambda: "/opt/homebrew/bin/podman")
- monkeypatch.setattr(doctor_tools, "_run_ok", lambda cmd, timeout, **kw: False)
- doctor_tools._check_docker_backend("docker", False, issues)
-
- out = _joined(capsys)
- assert "Podman not reachable" in out
- assert issues and "podman machine start" in issues[0] and "hermes setup terminal" in issues[0]
-def test_ssh_host_missing_line_points_at_setup_terminal(monkeypatch, capsys, issues):
- monkeypatch.delenv("TERMINAL_SSH_HOST", raising=False)
- doctor_tools._check_ssh_backend(issues)
- out = _joined(capsys)
- assert "SSH host not configured" in out and "'ssh' terminal backend" in out
- assert "TERMINAL_SSH_HOST" not in out
- assert issues and "hermes setup terminal" in issues[0] and "SSH host and user" in issues[0]
-def test_daytona_key_missing_line_points_at_setup_terminal(monkeypatch, capsys, issues):
- monkeypatch.delenv("DAYTONA_API_KEY", raising=False)
- doctor_tools._check_daytona_backend(issues)
- out = _joined(capsys)
- assert "Daytona API key missing" in out and "'daytona' terminal backend" in out
- assert "DAYTONA_API_KEY" not in out
- assert issues and "hermes setup terminal" in issues[0]
diff --git a/tests/hermes_cli/test_doctor_wal_checkpoint_guard.py b/tests/hermes_cli/test_doctor_wal_checkpoint_guard.py
index 8b97789e3b3..96b10f02f62 100644
--- a/tests/hermes_cli/test_doctor_wal_checkpoint_guard.py
+++ b/tests/hermes_cli/test_doctor_wal_checkpoint_guard.py
@@ -80,7 +80,6 @@ def test_large_wal_warning_under_a_live_writer_never_suggests_a_bare_fix(tmp_pat
finding = Finding()
_state_db_wal(finding, False, _large_wal_db(tmp_path))
assert len(finding.issues) == 1 and not finding.fixed
- assert "normal while Desktop or the gateway is running, or state.db cannot be inspected" in capsys.readouterr().out
assert finding.issues[0].index("stop the profile's gateway") < finding.issues[0].index("hermes doctor --fix")
diff --git a/tests/hermes_cli/test_dump_git_commit.py b/tests/hermes_cli/test_dump_git_commit.py
index 47c9cd9cb9d..f84841c272d 100644
--- a/tests/hermes_cli/test_dump_git_commit.py
+++ b/tests/hermes_cli/test_dump_git_commit.py
@@ -11,22 +11,6 @@ These tests cover both paths plus the failure modes (no git, no baked file).
from unittest.mock import MagicMock, patch
-def test_get_git_commit_uses_live_git_when_available(tmp_path):
- """Source install: ``git rev-parse --short=8 HEAD`` wins; no fallback."""
- from hermes_cli import dump
-
- repo_dir = tmp_path / "repo"
- repo_dir.mkdir()
-
- git_result = MagicMock(returncode=0, stdout="deadbeef\n")
- # build_info should NOT be consulted when live git succeeds.
- with patch("hermes_cli.dump.subprocess.run", return_value=git_result) as mock_run, \
- patch("hermes_cli.build_info.get_build_sha") as mock_build:
- commit = dump._get_git_commit(repo_dir)
-
- assert commit == "deadbeef"
- mock_run.assert_called_once()
- mock_build.assert_not_called()
def test_get_git_commit_output_format_identical_between_sources(tmp_path):
diff --git a/tests/hermes_cli/test_empty_session_hygiene.py b/tests/hermes_cli/test_empty_session_hygiene.py
index 4e4b575d740..9b7bc19019b 100644
--- a/tests/hermes_cli/test_empty_session_hygiene.py
+++ b/tests/hermes_cli/test_empty_session_hygiene.py
@@ -94,9 +94,6 @@ class TestCLIDiscardSessionIfEmpty:
- def test_none_session_id_is_noop(self, db):
- cli = self._make_cli(db)
- assert cli._discard_session_if_empty(None) is False
def test_db_error_swallowed(self, db):
class Boom:
diff --git a/tests/hermes_cli/test_ensure_gateway_service.py b/tests/hermes_cli/test_ensure_gateway_service.py
index 547c24c36e9..a3b7c11ce5a 100644
--- a/tests/hermes_cli/test_ensure_gateway_service.py
+++ b/tests/hermes_cli/test_ensure_gateway_service.py
@@ -95,16 +95,6 @@ class TestEnsureGatewayService:
assert gateway_mod.ensure_gateway_service() is False
assert warned and not calls
- def test_macos_uses_launchd(self, monkeypatch):
- _patch_host(monkeypatch, systemd=False, macos=True)
- monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)
- monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: False)
- calls = []
- monkeypatch.setattr(gateway_mod, "launchd_install", lambda force=False: calls.append("install"))
- monkeypatch.setattr(gateway_mod, "launchd_start", lambda: calls.append("start"))
-
- assert gateway_mod.ensure_gateway_service() is True
- assert calls == ["install", "start"]
def test_never_raises_on_install_failure(self, monkeypatch, capsys):
_patch_host(monkeypatch)
diff --git a/tests/hermes_cli/test_ensure_hermes_home_uid.py b/tests/hermes_cli/test_ensure_hermes_home_uid.py
index 68b20fa047e..9f9328b1da0 100644
--- a/tests/hermes_cli/test_ensure_hermes_home_uid.py
+++ b/tests/hermes_cli/test_ensure_hermes_home_uid.py
@@ -14,9 +14,7 @@ runs after every directory creation in the home-init path).
"""
from __future__ import annotations
-import os
import sys
-from pathlib import Path
from unittest.mock import patch
import pytest
@@ -57,17 +55,6 @@ class TestResolveHermesUidGid:
class TestChownToHermesUid:
- def test_calls_os_chown_when_both_set(self, tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_UID", "1000")
- monkeypatch.setenv("HERMES_GID", "911")
- import hermes_constants as cfg
-
- d = tmp_path / "subdir"
- d.mkdir()
-
- with patch.object(cfg.os, "chown") as mock_chown:
- cfg._chown_to_hermes_uid(d)
- mock_chown.assert_called_once_with(d, 1000, 911)
def test_eperm_is_silently_swallowed(self, tmp_path, monkeypatch):
@@ -89,18 +76,6 @@ class TestChownToHermesUid:
# Must not raise — the catch is non-fatal.
cfg._chown_to_hermes_uid(d)
- def test_attributeerror_swallowed_for_windows_compat(self, tmp_path, monkeypatch):
- """os.chown doesn't exist on Windows. Catching AttributeError keeps
- the helper portable."""
- monkeypatch.setenv("HERMES_UID", "1000")
- monkeypatch.setenv("HERMES_GID", "911")
- import hermes_constants as cfg
-
- d = tmp_path / "subdir"
- d.mkdir()
-
- with patch.object(cfg.os, "chown", side_effect=AttributeError("no chown on this platform")):
- cfg._chown_to_hermes_uid(d) # must not raise
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_env_custom_keys.py b/tests/hermes_cli/test_env_custom_keys.py
index 4f57f5335f9..4e52f252bff 100644
--- a/tests/hermes_cli/test_env_custom_keys.py
+++ b/tests/hermes_cli/test_env_custom_keys.py
@@ -10,7 +10,6 @@ NOT mislabelled custom.
from fastapi.testclient import TestClient
-import hermes_cli.web_server as web_server
import hermes_cli.config as _cfg_mod
import hermes_cli.web_server_messaging as _web_server_messaging
from hermes_cli.web_server import _SESSION_TOKEN, app
@@ -49,7 +48,3 @@ def test_custom_key_is_password_masked(monkeypatch):
assert "s3cret-value" not in str(row)
-def test_every_row_has_custom_flag(monkeypatch):
- """The ``custom`` field is always present so the SPA can branch on it."""
- rows = _env_rows(monkeypatch, {"MY_CUSTOM_THING": "x"})
- assert all("custom" in row for row in rows.values())
diff --git a/tests/hermes_cli/test_env_load_cache.py b/tests/hermes_cli/test_env_load_cache.py
index 3aff62546f0..d326e8c7fcd 100644
--- a/tests/hermes_cli/test_env_load_cache.py
+++ b/tests/hermes_cli/test_env_load_cache.py
@@ -9,42 +9,13 @@ remove_env_value / sanitise_env_file) call invalidate_env_cache().
from __future__ import annotations
-import os
-import tempfile
from pathlib import Path
-from unittest.mock import patch
def _write_env(path: Path, contents: str) -> None:
path.write_text(contents, encoding="utf-8")
-def test_load_env_caches_on_repeat_calls():
- """Repeated load_env() calls on the same file return the cached dict."""
- from hermes_cli.config import invalidate_env_cache, load_env
-
- invalidate_env_cache()
-
- with tempfile.NamedTemporaryFile(
- mode="w", suffix=".env", delete=False, encoding="utf-8"
- ) as f:
- f.write("OPENAI_API_KEY=sk-first\n")
- env_path = Path(f.name)
-
- try:
- with patch("hermes_cli.config.get_env_path", return_value=env_path):
- first = load_env()
- # Even if a writer outside our cache mutates the file, an
- # mtime/size match means the cache still wins. We simulate that
- # by writing identical bytes back — sanity check that the cache
- # is keyed structurally, not on a counter.
- second = load_env()
-
- assert first == second
- assert first.get("OPENAI_API_KEY") == "sk-first"
- finally:
- env_path.unlink(missing_ok=True)
- invalidate_env_cache()
diff --git a/tests/hermes_cli/test_env_loader.py b/tests/hermes_cli/test_env_loader.py
index 05f22348f75..d5ebbb2efe4 100644
--- a/tests/hermes_cli/test_env_loader.py
+++ b/tests/hermes_cli/test_env_loader.py
@@ -1,7 +1,5 @@
import codecs
-import importlib
import os
-import sys
from hermes_cli.env_loader import load_hermes_dotenv
@@ -87,58 +85,10 @@ def test_bom_first_key_is_seen_by_installer_and_scrub_alike(tmp_path, monkeypatc
assert scoped["COMMENTED_KEY"] == os.environ["COMMENTED_KEY"] == "value"
-def test_bomless_utf8_env_still_loads(tmp_path, monkeypatch):
- """BOM-less UTF-8 .env files must keep loading after utf-8-sig."""
- home = tmp_path / "hermes"
- home.mkdir()
- env_file = home / ".env"
- env_file.write_text("OPENAI_API_KEY=sk-plain\nSECOND_KEY=ok\n", encoding="utf-8")
-
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- monkeypatch.delenv("SECOND_KEY", raising=False)
-
- loaded = load_hermes_dotenv(hermes_home=home)
-
- assert loaded == [env_file]
- assert os.getenv("OPENAI_API_KEY") == "sk-plain"
- assert os.getenv("SECOND_KEY") == "ok"
-
-
-def test_latin1_env_falls_back(tmp_path, monkeypatch):
- """Invalid UTF-8 bytes must still load via the latin-1 fallback."""
- home = tmp_path / "hermes"
- home.mkdir()
- env_file = home / ".env"
- # 0xE9 is "é" in latin-1 and not a valid UTF-8 lead sequence alone.
- env_file.write_bytes(b"LATIN1_VALUE=caf\xe9\n")
-
- monkeypatch.delenv("LATIN1_VALUE", raising=False)
-
- loaded = load_hermes_dotenv(hermes_home=home)
-
- assert loaded == [env_file]
- assert os.getenv("LATIN1_VALUE") == "café"
-def test_utf8_bom_preserves_first_api_key_name(tmp_path, monkeypatch):
- """Real-world case: BOM + first line is a provider API key name."""
- home = tmp_path / "hermes"
- home.mkdir()
- env_file = home / ".env"
- env_file.write_bytes(
- b"\xef\xbb\xbfANTHROPIC_API_KEY=sk-test-123\nSECOND_KEY=ok\n"
- )
-
- monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
- monkeypatch.delenv("SECOND_KEY", raising=False)
- monkeypatch.delenv("\ufeffANTHROPIC_API_KEY", raising=False)
- loaded = load_hermes_dotenv(hermes_home=home)
- assert loaded == [env_file]
- assert os.getenv("ANTHROPIC_API_KEY") == "sk-test-123"
- assert os.getenv("SECOND_KEY") == "ok"
- assert os.environ.get("\ufeffANTHROPIC_API_KEY") is None
def test_utf8_bom_plus_invalid_utf8_preserves_first_key(tmp_path, monkeypatch):
@@ -167,21 +117,6 @@ def test_utf8_bom_plus_invalid_utf8_preserves_first_key(tmp_path, monkeypatch):
assert os.getenv("BAD") == "café"
assert os.environ.get("\ufeffANTHROPIC_API_KEY") is None
-def test_bomless_latin1_env_still_loads(tmp_path, monkeypatch):
- """BOM-less cp1252/latin-1 .env files must keep loading after the BOM strip."""
- home = tmp_path / "hermes"
- home.mkdir()
- env_file = home / ".env"
- env_file.write_bytes(b"LATIN1_VALUE=caf\xe9\nOTHER=ok\n")
-
- monkeypatch.delenv("LATIN1_VALUE", raising=False)
- monkeypatch.delenv("OTHER", raising=False)
-
- loaded = load_hermes_dotenv(hermes_home=home)
-
- assert loaded == [env_file]
- assert os.getenv("LATIN1_VALUE") == "café"
- assert os.getenv("OTHER") == "ok"
def test_latin1_fallback_stream_honors_override(tmp_path, monkeypatch):
"""Stream-based latin-1 fallback must honor override= identically to dotenv_path."""
diff --git a/tests/hermes_cli/test_env_sanitize_on_load.py b/tests/hermes_cli/test_env_sanitize_on_load.py
index 9c8c6dadc81..633d8306c81 100644
--- a/tests/hermes_cli/test_env_sanitize_on_load.py
+++ b/tests/hermes_cli/test_env_sanitize_on_load.py
@@ -34,32 +34,6 @@ def test_load_env_preserves_concatenated_text_as_value_data():
env_path.unlink(missing_ok=True)
-def test_load_env_normal_file_unchanged():
- """A well-formed .env file should be parsed identically."""
- from hermes_cli.config import load_env
-
- content = (
- "TELEGRAM_BOT_TOKEN=mytoken123\n"
- "ANTHROPIC_API_KEY=sk-ant-key\n"
- "# comment\n"
- "\n"
- "OPENAI_API_KEY=sk-openai\n"
- )
-
- with tempfile.NamedTemporaryFile(
- mode="w", suffix=".env", delete=False, encoding="utf-8"
- ) as f:
- f.write(content)
- env_path = Path(f.name)
-
- try:
- with patch("hermes_cli.config.get_env_path", return_value=env_path):
- result = load_env()
- assert result["TELEGRAM_BOT_TOKEN"] == "mytoken123"
- assert result["ANTHROPIC_API_KEY"] == "sk-ant-key"
- assert result["OPENAI_API_KEY"] == "sk-openai"
- finally:
- env_path.unlink(missing_ok=True)
def test_env_loader_does_not_split_concatenated_text():
diff --git a/tests/hermes_cli/test_exit_delete_session.py b/tests/hermes_cli/test_exit_delete_session.py
index c8df19cd26a..4cda4dde39c 100644
--- a/tests/hermes_cli/test_exit_delete_session.py
+++ b/tests/hermes_cli/test_exit_delete_session.py
@@ -69,17 +69,9 @@ class TestExitDeleteFlag:
class TestCommandRegistry:
- def test_quit_command_advertises_delete_flag(self):
- """The CommandDef args_hint should surface `--delete` in /help and
- CLI autocomplete."""
- from hermes_cli.commands import resolve_command
- cmd = resolve_command("quit")
- assert cmd is not None
- assert cmd.args_hint == "[--delete]"
def test_exit_alias_resolves_to_quit_with_hint(self):
from hermes_cli.commands import resolve_command
cmd = resolve_command("exit")
assert cmd is not None
assert cmd.name == "quit"
- assert cmd.args_hint == "[--delete]"
diff --git a/tests/hermes_cli/test_exit_watchdog_signal_arm.py b/tests/hermes_cli/test_exit_watchdog_signal_arm.py
index cb7a05ea178..5f14a0c75d7 100644
--- a/tests/hermes_cli/test_exit_watchdog_signal_arm.py
+++ b/tests/hermes_cli/test_exit_watchdog_signal_arm.py
@@ -33,19 +33,9 @@ def _reset_arm_flag(monkeypatch):
class TestSignalArmLogic:
- def test_arms_with_double_cleanup_timeout(self, monkeypatch):
- monkeypatch.setenv("HERMES_EXIT_WATCHDOG_S", "7")
- with patch.object(cli, "_arm_exit_watchdog") as arm:
- cli._arm_exit_watchdog_on_shutdown_signal()
- arm.assert_called_once_with(timeout_s=14.0, from_signal=True)
- def test_bad_env_value_falls_back_to_default(self, monkeypatch):
- monkeypatch.setenv("HERMES_EXIT_WATCHDOG_S", "not-a-number")
- with patch.object(cli, "_arm_exit_watchdog") as arm:
- cli._arm_exit_watchdog_on_shutdown_signal()
- arm.assert_called_once_with(timeout_s=60.0, from_signal=True)
def test_never_raises_even_if_arm_explodes(self, monkeypatch):
monkeypatch.setenv("HERMES_EXIT_WATCHDOG_S", "7")
diff --git a/tests/hermes_cli/test_external_process_auth_status.py b/tests/hermes_cli/test_external_process_auth_status.py
index bc9ac1df827..bae65b7a03d 100644
--- a/tests/hermes_cli/test_external_process_auth_status.py
+++ b/tests/hermes_cli/test_external_process_auth_status.py
@@ -203,14 +203,6 @@ def test_explicit_filter_drops_unverified_external_process_row(tmp_path, monkeyp
# --- Accounts-tab cli_command ------------------------------------------------
-def test_catalog_sign_in_command_is_a_valid_copilot_invocation():
- from hermes_cli.web_server_oauth import _OAUTH_PROVIDER_CATALOG
-
- entry = next(e for e in _OAUTH_PROVIDER_CATALOG if e["id"] == "copilot-acp")
- # `copilot /login` is not a valid invocation — slash-commands only exist
- # inside an interactive session. The catalog must hand users a command
- # that actually starts a login flow.
- assert entry["cli_command"] == "copilot login"
def test_cli_command_reflects_configured_executable(tmp_path, monkeypatch, _clean_copilot_env):
diff --git a/tests/hermes_cli/test_fallback_cmd.py b/tests/hermes_cli/test_fallback_cmd.py
index a20a85293b7..2d462190539 100644
--- a/tests/hermes_cli/test_fallback_cmd.py
+++ b/tests/hermes_cli/test_fallback_cmd.py
@@ -36,9 +36,6 @@ def _read_config(home: Path) -> dict:
# ---------------------------------------------------------------------------
class TestReadChain:
- def test_returns_empty_list_when_unset(self):
- from hermes_cli.fallback_cmd import _read_chain
- assert _read_chain({}) == []
def test_reads_new_list_format(self):
from hermes_cli.fallback_cmd import _read_chain
@@ -86,13 +83,6 @@ class TestExtractFallback:
# ---------------------------------------------------------------------------
class TestListCommand:
- def test_list_empty(self, isolated_home, capsys):
- _write_config(isolated_home, {})
- from hermes_cli.fallback_cmd import cmd_fallback_list
- cmd_fallback_list(types.SimpleNamespace())
- out = capsys.readouterr().out
- assert "No fallback providers configured" in out
- assert "hermes fallback add" in out
def test_list_with_entries(self, isolated_home, capsys):
_write_config(isolated_home, {
@@ -105,7 +95,6 @@ class TestListCommand:
from hermes_cli.fallback_cmd import cmd_fallback_list
cmd_fallback_list(types.SimpleNamespace())
out = capsys.readouterr().out
- assert "Fallback chain (2 entries)" in out
assert "anthropic/claude-sonnet-4.6" in out
assert "Hermes-4" in out
# Primary should be shown too
@@ -117,7 +106,7 @@ class TestListCommand:
# ---------------------------------------------------------------------------
class TestAddCommand:
- def test_add_appends_new_entry(self, isolated_home, capsys):
+ def test_add_appends_new_entry(self, isolated_home):
_write_config(isolated_home, {
"model": {"provider": "anthropic", "default": "claude-sonnet-4-6"},
})
@@ -152,11 +141,9 @@ class TestAddCommand:
"api_mode": "chat_completions",
}
]
- out = capsys.readouterr().out
- assert "Added fallback" in out
- def test_add_rejects_same_as_primary(self, isolated_home, capsys):
+ def test_add_rejects_same_as_primary(self, isolated_home):
_write_config(isolated_home, {
"model": {"provider": "openrouter", "default": "gpt-5.4"},
})
@@ -175,8 +162,6 @@ class TestAddCommand:
cfg = _read_config(isolated_home)
assert "fallback_providers" not in cfg or cfg["fallback_providers"] == []
- out = capsys.readouterr().out
- assert "matches the current primary" in out
def test_add_preserves_primary_when_picker_changes_it(self, isolated_home):
"""The picker mutates config["model"]; fallback_add must restore the primary."""
@@ -297,7 +282,7 @@ class TestAddCommand:
class TestRemoveCommand:
- def test_remove_selected_entry(self, isolated_home, capsys):
+ def test_remove_selected_entry(self, isolated_home):
_write_config(isolated_home, {
"fallback_providers": [
{"provider": "openrouter", "model": "gpt-5.4"},
@@ -316,9 +301,6 @@ class TestRemoveCommand:
{"provider": "openrouter", "model": "gpt-5.4"},
{"provider": "anthropic", "model": "claude-sonnet-4-6"},
]
- out = capsys.readouterr().out
- assert "Removed fallback" in out
- assert "Hermes-4" in out
# ---------------------------------------------------------------------------
@@ -327,7 +309,7 @@ class TestRemoveCommand:
class TestClearCommand:
- def test_clear_with_confirmation(self, isolated_home, capsys, monkeypatch):
+ def test_clear_with_confirmation(self, isolated_home, monkeypatch):
_write_config(isolated_home, {
"fallback_providers": [
{"provider": "openrouter", "model": "gpt-5.4"},
@@ -340,8 +322,6 @@ class TestClearCommand:
cfg = _read_config(isolated_home)
assert cfg.get("fallback_providers") == []
- out = capsys.readouterr().out
- assert "Fallback chain cleared" in out
# ---------------------------------------------------------------------------
@@ -362,27 +342,3 @@ class TestDispatcher:
# argparse wiring — verify the subparser is registered
# ---------------------------------------------------------------------------
-class TestArgparseWiring:
- """Verify `hermes fallback` is wired into main.py's argparse tree.
-
- main() builds the parser inline, so we invoke main([...]) via subprocess
- with --help to introspect registered subcommands without side effects.
- """
-
- def test_fallback_help_lists_subcommands(self):
- import subprocess
- import sys
- result = subprocess.run(
- [sys.executable, "-m", "hermes_cli.main", "fallback", "--help"],
- capture_output=True,
- text=True,
- timeout=30,
- )
- # --help exits 0
- assert result.returncode == 0, f"stderr: {result.stderr}"
- out = result.stdout + result.stderr
- # All four subcommands should appear in help
- assert "list" in out
- assert "add" in out
- assert "remove" in out
- assert "clear" in out
diff --git a/tests/hermes_cli/test_fast_command.py b/tests/hermes_cli/test_fast_command.py
index 203dfe329da..f4f22303966 100644
--- a/tests/hermes_cli/test_fast_command.py
+++ b/tests/hermes_cli/test_fast_command.py
@@ -73,25 +73,6 @@ class TestHandleFastCommand(unittest.TestCase):
self.assertIsNone(stub.agent)
- def test_unsupported_model_does_not_expose_fast(self):
- cli_mod = _import_cli()
- stub = SimpleNamespace(
- service_tier=None,
- provider="openai-codex",
- requested_provider="openai-codex",
- model="gpt-5.3-codex",
- _fast_command_available=lambda: False,
- agent=MagicMock(),
- )
-
- with (
- patch.object(cli_mod, "_cprint") as mock_cprint,
- patch.object(cli_mod, "save_config_value") as mock_save,
- ):
- cli_mod.HermesCLI._handle_fast_command(stub, "/fast")
-
- mock_save.assert_not_called()
- self.assertTrue(mock_cprint.called)
class TestPriorityProcessingModels(unittest.TestCase):
@@ -134,14 +115,6 @@ class TestPriorityProcessingModels(unittest.TestCase):
assert model_supports_fast_mode("grok-4.5") is False
assert resolve_fast_mode_overrides("grok-4.6") == {"service_tier": "priority"}
- def test_resolve_overrides_returns_service_tier(self):
- from hermes_cli.models import resolve_fast_mode_overrides
-
- result = resolve_fast_mode_overrides("gpt-5.4")
- assert result == {"service_tier": "priority"}
-
- result = resolve_fast_mode_overrides("gpt-4.1")
- assert result == {"service_tier": "priority"}
@@ -242,14 +215,6 @@ class TestAnthropicFastMode(unittest.TestCase):
- def test_resolve_overrides_returns_speed_for_anthropic(self):
- from hermes_cli.models import resolve_fast_mode_overrides
-
- result = resolve_fast_mode_overrides("claude-opus-4-8")
- assert result == {"speed": "fast"}
-
- result = resolve_fast_mode_overrides("anthropic/claude-opus-4.8")
- assert result == {"speed": "fast"}
@@ -340,10 +305,3 @@ class TestAnthropicFastModeAdapter(unittest.TestCase):
-class TestConfigDefault(unittest.TestCase):
- def test_default_config_has_service_tier(self):
- from hermes_cli.config import DEFAULT_CONFIG
-
- agent = DEFAULT_CONFIG.get("agent", {})
- self.assertIn("service_tier", agent)
- self.assertEqual(agent["service_tier"], "")
diff --git a/tests/hermes_cli/test_fireworks_provider.py b/tests/hermes_cli/test_fireworks_provider.py
index 14b6a7e5a0c..ef0a8cba403 100644
--- a/tests/hermes_cli/test_fireworks_provider.py
+++ b/tests/hermes_cli/test_fireworks_provider.py
@@ -22,7 +22,7 @@ if "dotenv" not in sys.modules:
sys.modules["dotenv"] = fake_dotenv
from hermes_cli.auth import resolve_api_key_provider_credentials
-from hermes_cli.models import CANONICAL_PROVIDERS, _PROVIDER_LABELS, normalize_provider
+from hermes_cli.models import normalize_provider
@pytest.fixture(autouse=True)
@@ -46,16 +46,6 @@ class TestFireworksAliases:
assert normalize_in_providers(alias) == "fireworks"
-class TestFireworksOrdering:
- """Fireworks participates in the canonical provider catalog."""
-
- def test_present_in_canonical_providers(self):
- slugs = [p.slug for p in CANONICAL_PROVIDERS]
- assert "fireworks" in slugs
-
-
- def test_has_a_label(self):
- assert _PROVIDER_LABELS.get("fireworks") == "Fireworks AI"
class TestFireworksConfigRegistry:
@@ -69,23 +59,9 @@ class TestFireworksConfigRegistry:
assert "FIREWORKS_BASE_URL" not in OPTIONAL_ENV_VARS
-class TestFireworksOverlay:
- def test_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
-
- assert "fireworks" in HERMES_OVERLAYS
- overlay = HERMES_OVERLAYS["fireworks"]
- assert overlay.transport == "openai_chat"
- assert overlay.base_url_override == "https://api.fireworks.ai/inference/v1"
- assert not overlay.base_url_env_var
- assert not overlay.is_aggregator
class TestFireworksDoctor:
- def test_provider_env_hints_include_fireworks(self):
- from hermes_cli.doctor import _PROVIDER_ENV_HINTS
-
- assert "FIREWORKS_API_KEY" in _PROVIDER_ENV_HINTS
def test_slash_form_model_is_not_flagged_as_vendor_prefixed(self, monkeypatch, tmp_path):
"""Fireworks' native model IDs are slash-form (accounts/fireworks/...),
diff --git a/tests/hermes_cli/test_fleet_config_migration_windows_live.py b/tests/hermes_cli/test_fleet_config_migration_windows_live.py
deleted file mode 100644
index 95b5767d8d4..00000000000
--- a/tests/hermes_cli/test_fleet_config_migration_windows_live.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""LIVE Windows E2E for the fleet-wide config migration (wine2e lane).
-
-Real profile homes on the Windows filesystem, real migration pipeline,
-fresh-process semantics via HERMES_HOME env — mirrors the Linux live E2E.
-"""
-import sys
-from pathlib import Path
-
-import pytest
-import yaml
-
-WORKTREE = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(WORKTREE))
-
-pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="live Windows E2E")
-
-
-def test_fleet_config_migration_live_windows(tmp_path, monkeypatch):
- active = tmp_path / "hermes-home"
- profiles = active / "profiles"
- for name, ver in [("research", 12), ("work", 25)]:
- home = profiles / name
- home.mkdir(parents=True)
- (home / "config.yaml").write_text(
- yaml.safe_dump({"_config_version": ver, "model": {"provider": "nous"}}),
- encoding="utf-8",
- )
- active.mkdir(exist_ok=True)
- (active / "config.yaml").write_text(
- yaml.safe_dump({"_config_version": 12}), encoding="utf-8"
- )
- monkeypatch.setenv("HERMES_HOME", str(active))
-
- import hermes_cli.update_cmd as update_cmd
- from hermes_cli.config import DEFAULT_CONFIG
-
- latest = int(DEFAULT_CONFIG["_config_version"])
- migrated = update_cmd._migrate_sibling_profile_configs()
-
- by_name = {m[0]: m for m in migrated}
- assert set(by_name) == {"research", "work"}, migrated
- assert by_name["research"][1] == 12 and by_name["research"][2] == latest
-
- for name in ("research", "work"):
- on_disk = yaml.safe_load((profiles / name / "config.yaml").read_text())
- assert on_disk["_config_version"] == latest
- assert on_disk["model"]["provider"] == "nous"
-
- # active untouched; idempotent second run
- assert yaml.safe_load((active / "config.yaml").read_text())["_config_version"] == 12
- assert update_cmd._migrate_sibling_profile_configs() == []
diff --git a/tests/hermes_cli/test_focus_view.py b/tests/hermes_cli/test_focus_view.py
index c8808be1586..26887e87f8f 100644
--- a/tests/hermes_cli/test_focus_view.py
+++ b/tests/hermes_cli/test_focus_view.py
@@ -24,10 +24,7 @@ from hermes_cli.focus_view import (
FOCUS_STATUSBAR_LABEL,
FOCUS_TOOL_PROGRESS_MODE,
focus_statusbar_segment,
- format_focus_status,
- format_focus_toggle_message,
format_hidden_line,
- normalize_tool_progress_mode,
resolve_focus_arg,
would_display_tool_line,
)
@@ -65,9 +62,6 @@ class TestToggleStateMachine:
class TestComposesWithVerboseModes:
- def test_focus_on_snaps_to_the_existing_off_mode(self):
- # Focus view must reuse the tool_progress "off" path, not invent a mode.
- assert FOCUS_TOOL_PROGRESS_MODE == "off"
def test_new_mode_skips_consecutive_repeats_like_the_renderer(self):
assert would_display_tool_line("new", "terminal", "terminal") is False
@@ -89,8 +83,6 @@ class TestHiddenCountFormatter:
- def test_line_always_names_the_recovery_command(self):
- assert "/focus off" in format_hidden_line(2)
@@ -125,7 +117,6 @@ class TestHiddenCounterAccumulation:
host._emit_focus_recovery_line()
assert printer.call_count == 1
- assert "2 tool lines hidden" in printer.call_args[0][0]
assert "/focus off" in printer.call_args[0][0]
# Reset so the next turn starts from zero.
assert host._focus_hidden_lines == 0
@@ -354,14 +345,6 @@ class TestModelFacingMessagesUnchanged:
class TestCommandRegistration:
- def test_focus_is_registered_with_the_sibling_toggle_convention(self):
- from hermes_cli.commands import resolve_command
-
- cmd = resolve_command("focus")
- assert cmd is not None
- assert cmd.category == "Configuration"
- assert cmd.args_hint == "[on|off|status]"
- assert set(cmd.subcommands) == {"on", "off", "status"}
def test_verbose_cycle_releases_focus_view(self):
# /verbose is the explicit tool-progress control; cycling it must clear
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index 0b1313b2de9..fcfce8cb039 100644
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@ -5,7 +5,7 @@ import os
import subprocess
import sys
import textwrap
-from types import ModuleType, SimpleNamespace
+from types import SimpleNamespace
import pytest
@@ -28,42 +28,6 @@ def inert_task_scheduler_probe():
mp.undo()
-def _install_fake_gateway_run(monkeypatch, start_gateway):
- module = ModuleType("gateway.run")
- module.start_gateway = start_gateway
-
- def _exit_after_graceful_shutdown(code):
- if code:
- raise SystemExit(code)
-
- setattr(module, "_exit_after_graceful_shutdown", _exit_after_graceful_shutdown)
- monkeypatch.setitem(sys.modules, "gateway.run", module)
- # ``run_gateway()`` calls ``refresh_systemd_unit_if_needed()`` on every
- # invocation so that restart settings stay current after exit-code-75
- # respawns. That helper writes to ``Path.home() / ".config/systemd/user
- # /hermes-gateway.service"`` and runs ``systemctl --user daemon-reload``
- # — both target the *real* user environment because the conftest only
- # sandboxes ``HERMES_HOME``, not ``HOME``. Tests that drive
- # ``run_gateway()`` end-to-end with a fake ``start_gateway`` MUST stub
- # the refresh call too, or every run rewrites the developer's installed
- # unit (baking in the test's pytest-tmp ``HERMES_HOME`` value, which
- # systemd then uses on the next boot — silently breaking the gateway
- # for the developer).
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(
- gateway, "refresh_systemd_unit_if_needed", lambda system=False: False
- )
- # Neutralize the supervised-gateway conflict guard by default so these
- # end-to-end tests don't trip over a launchd/systemd gateway that happens
- # to be installed+running on the developer's machine. Conflict-guard tests
- # override this snapshot after calling the helper.
- monkeypatch.setattr(
- gateway,
- "get_gateway_runtime_snapshot",
- lambda *a, **k: gateway.GatewayRuntimeSnapshot(manager="manual process"),
- )
-
-
def _run_native_windows_gateway_start_diag(
tmp_path, breakaway_marker: str | None
):
@@ -161,8 +125,6 @@ def test_windows_gateway_start_diag_reports_detach_state(
assert diag["breakaway"] is expected_breakaway
-
-
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX PTY coverage")
@pytest.mark.parametrize(
("stdin_is_tty", "outcome", "expected_exit"),
@@ -253,23 +215,6 @@ def test_gateway_run_subprocess_preserves_daemon_exit_codes(
assert completed.returncode == expected_exit, completed.stderr
-
-
-def _clear_supervisor_markers(monkeypatch):
- """Make ``_running_under_gateway_supervisor()`` report a plain shell."""
- monkeypatch.delenv("INVOCATION_ID", raising=False)
- monkeypatch.delenv("HERMES_S6_SUPERVISED_CHILD", raising=False)
- # Interactive macOS shells inherit XPC_SERVICE_NAME="0"; launchd jobs get
- # the real label. Default to the shell sentinel so the guard can fire.
- monkeypatch.setenv("XPC_SERVICE_NAME", "0")
-
-
-def _running_snapshot(manager="systemd (user)"):
- return gateway.GatewayRuntimeSnapshot(
- manager=manager, service_installed=True, service_running=True
- )
-
-
def test_s6_runtime_snapshot_reports_supervised_service(monkeypatch, tmp_path):
service_dir = tmp_path / "gateway-default"
service_dir.mkdir()
@@ -297,10 +242,6 @@ def test_s6_runtime_snapshot_reports_supervised_service(monkeypatch, tmp_path):
assert snapshot.gateway_pids == (123,)
-
-
-
-
class TestSystemdLingerStatus:
def test_reports_enabled(self, monkeypatch):
monkeypatch.setattr(gateway, "is_linux", lambda: True)
@@ -376,7 +317,7 @@ def test_spawn_detached_gateway_timestamps_stderr(monkeypatch, tmp_path):
sys.platform == "win32",
reason="systemd user-linger is Linux-only (drives os.getuid())",
)
-def test_systemd_install_checks_linger_status(monkeypatch, tmp_path, capsys):
+def test_systemd_install_checks_linger_status(monkeypatch, tmp_path):
unit_path = tmp_path / "systemd" / "user" / "hermes-gateway.service"
monkeypatch.setattr(gateway, "get_systemd_unit_path", lambda system=False: unit_path)
@@ -403,22 +344,12 @@ def test_systemd_install_checks_linger_status(monkeypatch, tmp_path, capsys):
gateway.systemd_install(force=False)
- out = capsys.readouterr().out
assert unit_path.exists()
assert [cmd for cmd, _ in calls] == [
["systemctl", "--user", "daemon-reload"],
["systemctl", "--user", "enable", gateway.get_service_name()],
]
assert helper_calls == [True]
- assert "User service installed and enabled" in out
-
-
-
-
-
-
-
-
def test_gateway_install_noninteractive_skips_legacy_unit_prompt(monkeypatch, tmp_path):
@@ -453,16 +384,6 @@ def test_gateway_install_noninteractive_skips_legacy_unit_prompt(monkeypatch, tm
assert all(c[0] != "prompt" for c in calls)
-
-
-
-
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# _wait_for_gateway_exit
# ---------------------------------------------------------------------------
@@ -472,7 +393,6 @@ class TestWaitForGatewayExit:
"""PID-based wait with force-kill on timeout."""
-
def test_force_kills_after_grace_period(self, monkeypatch):
"""When the process doesn't exit, force-kill the saved PID."""
@@ -583,98 +503,7 @@ class TestRestartWaitsForApiServerPort:
class TestStopProfileGateway:
- def test_windows_stop_drains_marker_before_force_termination(self, monkeypatch):
- """Windows must let the marker watcher run before escalating (#112750)."""
- import hermes_cli.gateway_windows as gateway_windows
- pid = 12345
- calls = []
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: pid)
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
- monkeypatch.setattr(
- gateway_windows,
- "_drain_gateway_pid",
- lambda target, timeout: calls.append(("drain", target, timeout)) or True,
- )
- monkeypatch.setattr(
- gateway_windows,
- "_force_terminate_known_gateway_pids",
- lambda pids: calls.append(("force", pids)),
- )
- monkeypatch.setattr(gateway.os, "kill", lambda *_: calls.append(("kill",)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda target: False)
- monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)
- monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
-
- assert gateway.stop_profile_gateway() is True
- assert calls == [("drain", pid, 7.0)]
-
- def test_windows_stop_force_terminates_only_after_drain_timeout(self, monkeypatch):
- """A wedged Windows gateway still has a bounded force-stop fallback (#112750)."""
- import hermes_cli.gateway_windows as gateway_windows
-
- pid = 12345
- calls = []
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: pid)
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
- monkeypatch.setattr("gateway.status.get_process_start_time", lambda target: 100)
- monkeypatch.setattr(
- gateway_windows,
- "_drain_gateway_pid",
- lambda target, timeout: calls.append(("drain", target, timeout)) or False,
- )
- monkeypatch.setattr(
- gateway_windows,
- "_force_terminate_known_gateway_pids",
- lambda pids: calls.append(("force", pids)),
- )
- monkeypatch.setattr(gateway.os, "kill", lambda *_: calls.append(("kill",)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda target: False)
- monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)
- monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
-
- assert gateway.stop_profile_gateway() is True
- assert calls == [("drain", pid, 7.0), ("force", {pid: 100})]
-
- def test_windows_stop_force_kill_carries_pre_drain_identity(self, monkeypatch):
- """The post-drain taskkill must be guarded by the start time captured BEFORE the <=30 s drain:
- a PID recycled during the wait shows a different start time, so ``terminate_pid``'s mismatch
- refusal fires instead of killing an unrelated process. Reading it at kill time is a vacuous
- self-comparison."""
- import gateway.status as status
- import hermes_cli.gateway_windows as gateway_windows
-
- pid = 4242
- calls = []
- clock = {"now": 0.0}
- alive = {"value": True}
-
- monkeypatch.setattr(gateway_windows.time, "monotonic", lambda: clock["now"])
- monkeypatch.setattr(
- gateway_windows.time, "sleep", lambda _s: clock.__setitem__("now", clock["now"] + 10.0)
- )
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
- monkeypatch.setattr(status, "get_running_pid", lambda: pid if alive["value"] else None)
- monkeypatch.setattr(status, "write_planned_stop_marker", lambda target: None)
- monkeypatch.setattr(status, "_pid_exists", lambda target: alive["value"])
- # The original gateway (start time 100) exits during the drain and its PID is recycled (999).
- monkeypatch.setattr(
- status, "get_process_start_time", lambda target: 100 if clock["now"] < 7.0 else 999
- )
-
- def _terminate(target, force=False, expected_start_time=None):
- calls.append((target, force, expected_start_time))
- alive["value"] = False
-
- monkeypatch.setattr(status, "terminate_pid", _terminate)
- monkeypatch.setattr(status, "remove_pid_file", lambda: None)
- monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
-
- assert gateway.stop_profile_gateway() is True
- assert calls == [(pid, True, 100)]
def test_stop_profile_gateway_keeps_pid_file_when_process_still_running(self, monkeypatch):
calls = {"kill": 0, "alive_probes": 0, "remove": 0, "reap_calls": 0}
@@ -708,7 +537,6 @@ class TestStopProfileGateway:
assert gateway.stop_profile_gateway() is True
assert calls["kill"] == 1 # one SIGTERM
- assert calls["alive_probes"] == 20 # 20 liveness polls over the 2s window
assert calls["remove"] == 0
assert calls["reap_calls"] == 1 # orphan sweep ran after kill
@@ -735,251 +563,6 @@ class TestStopProfileGateway:
assert killed_pid in reap_extra_excludes[0]
-class TestReapUnsupervisedGatewayOrphansMacOS:
- """Tests that the orphan reaper excludes launchd-managed PIDs on macOS.
-
- Regression guard: without the ``is_macos()`` exclusion of
- ``_get_service_pids()``, the reaper would SIGTERM the launchd-supervised
- gateway every time Hermes Desktop opens (``hermes serve`` calls
- ``_reap_unsupervised_gateway_orphans`` during startup).
- """
-
- def test_macos_excludes_launchd_pid_from_kill(self, monkeypatch):
- """A launchd-managed PID must not appear in the orphan kill list."""
- launchd_pid = 52615
-
- # Pretend we're on macOS — supports_systemd_services() returns False
- # so the function does NOT short-circuit and proceeds to the scan.
- monkeypatch.setattr(gateway, "is_macos", lambda: True)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
-
- # _get_service_pids returns the launchd-managed gateway PID.
- # (accepts all_profiles: the reaper asks for the whole fleet, #74075)
- monkeypatch.setattr(
- gateway, "_get_service_pids", lambda all_profiles=False: {launchd_pid}
- )
- # No pidfile-recorded gateway in this scenario.
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
-
- # find_gateway_pids returns the launchd PID plus a real orphan.
- # The reaper should only kill the orphan, not the launchd PID.
- orphan_pid = 99998
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [p for p in [launchd_pid, orphan_pid] if p not in (exclude_pids or set())],
- )
-
- killed_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
- monkeypatch.setattr("gateway.status.write_planned_stop_marker", lambda pid: None)
- monkeypatch.setattr("time.sleep", lambda _: None)
- monkeypatch.setattr("time.monotonic", lambda: 1.0)
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is True # at least one orphan was reaped
- killed = [pid for pid, _ in killed_pids]
- assert orphan_pid in killed # the real orphan was killed
- assert launchd_pid not in killed # the launchd PID was NOT killed
-
- def test_macos_no_orphans_when_only_launchd_gateway_running(self, monkeypatch):
- """If the only gateway PID is launchd-managed, reaper returns False."""
- launchd_pid = 52615
-
- monkeypatch.setattr(gateway, "is_macos", lambda: True)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(
- gateway, "_get_service_pids", lambda all_profiles=False: {launchd_pid}
- )
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
-
- # find_gateway_pids would return the launchd PID, but it's excluded.
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [p for p in [launchd_pid] if p not in (exclude_pids or set())],
- )
-
- killed_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is False # no orphans reaped
- assert killed_pids == [] # nothing was killed
-
-
-class TestReapUnsupervisedGatewayOrphansWindows:
- """Tests that the orphan reaper spares the recorded gateway PID and its
- supervision chain on Windows.
-
- Regression guard: without the Windows exemption of the recorded healthy
- gateway PID (and its parent chain), the reaper would SIGTERM/SIGKILL a
- Scheduled-Task-supervised gateway every time Hermes Desktop opens
- (``hermes serve`` calls ``_reap_unsupervised_gateway_orphans`` during
- startup). The Scheduled-Task bootstrap's argv matches the gateway scan,
- so it is reaped as an "orphan" — and when the bootstrap dies, the
- detached gateway it spawned exits with it (#86098).
- """
-
- @staticmethod
- def _install_fake_psutil(monkeypatch, chain):
- """Install a fake psutil module exposing the given process chain."""
- by_pid = {proc.pid: proc for proc in chain}
- fake_psutil = SimpleNamespace(Process=lambda pid: by_pid[pid])
- monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
-
- def test_windows_excludes_recorded_pid_and_bootstrap_from_kill(self, monkeypatch):
- """The recorded gateway PID and its bootstrap parent must not be killed."""
- recorded_pid = 52615 # detached gateway recorded in gateway.pid
- bootstrap_pid = 52616 # Scheduled-Task bootstrap (argv matches scan)
- orphan_pid = 99998 # a real orphan that should still be reaped
-
- # Pretend we're on Windows — supports_systemd_services() returns
- # False so the function does NOT short-circuit and proceeds to the
- # scan, and is_macos() is False so the launchd branch is skipped.
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
-
- # gateway.pid records the detached gateway; its parent is the
- # Scheduled-Task bootstrap whose argv matches the gateway scan.
- bootstrap = SimpleNamespace(pid=bootstrap_pid, parent=lambda: None)
- recorded = SimpleNamespace(pid=recorded_pid, parent=lambda: bootstrap)
- self._install_fake_psutil(monkeypatch, [recorded, bootstrap])
-
- # get_running_pid() returns the recorded healthy gateway PID.
- monkeypatch.setattr(
- "gateway.status.get_running_pid", lambda cleanup_stale=True: recorded_pid
- )
-
- # find_gateway_pids returns the recorded PID, its bootstrap parent
- # and a real orphan. The reaper should only kill the orphan.
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [
- p
- for p in [recorded_pid, bootstrap_pid, orphan_pid]
- if p not in (exclude_pids or set())
- ],
- )
-
- killed_pids = []
- marked_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
- monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)
- monkeypatch.setattr("time.sleep", lambda _: None)
- monkeypatch.setattr("time.monotonic", lambda: 1.0)
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is True # at least one orphan was reaped
- assert marked_pids == [orphan_pid] # the real orphan was asked to drain
- assert killed_pids == [] # Windows SIGTERM must not TerminateProcess
-
- def test_windows_no_orphans_when_only_recorded_gateway_running(self, monkeypatch):
- """If the only gateway processes are the recorded one and its
- bootstrap parent, the reaper returns False and kills nothing."""
- recorded_pid = 52615
- bootstrap_pid = 52616
-
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
-
- bootstrap = SimpleNamespace(pid=bootstrap_pid, parent=lambda: None)
- recorded = SimpleNamespace(pid=recorded_pid, parent=lambda: bootstrap)
- self._install_fake_psutil(monkeypatch, [recorded, bootstrap])
-
- monkeypatch.setattr(
- "gateway.status.get_running_pid", lambda cleanup_stale=True: recorded_pid
- )
-
- # find_gateway_pids would return the recorded PID and its bootstrap
- # parent, but both are excluded.
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [
- p
- for p in [recorded_pid, bootstrap_pid]
- if p not in (exclude_pids or set())
- ],
- )
-
- killed_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is False # no orphans reaped
- assert killed_pids == [] # nothing was killed
-
- def test_windows_raw_record_supplies_exclusion_when_validation_fails(
- self, monkeypatch
- ):
- """A registration that fails liveness VALIDATION must still shield
- the recorded PID from the sweep.
-
- get_running_pid returns None whenever the record fails validation
- (start-time mismatch, argv drift, lock hiccup) — regardless of
- cleanup_stale, which only controls unlinking. The exclusion set is
- therefore built from the RAW pidfile/lock records: a stale recorded
- PID at worst spares one process, while a validation false-negative
- would TerminateProcess a healthy standalone gateway (#87158).
- """
- recorded_pid = 52615
-
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
-
- recorded = SimpleNamespace(pid=recorded_pid, parent=lambda: None)
- self._install_fake_psutil(monkeypatch, [recorded])
-
- # The raw record is present on disk; the validated probe rejects it.
- monkeypatch.setattr(
- "gateway.status._read_pid_record", lambda *a, **k: {"pid": recorded_pid}
- )
- monkeypatch.setattr(
- "gateway.status._read_gateway_lock_record", lambda *a, **k: None
- )
- probe_kwargs = []
-
- def failing_validation(*a, cleanup_stale=True, **k):
- probe_kwargs.append(cleanup_stale)
- return None
-
- monkeypatch.setattr(
- "gateway.status.get_running_pid", failing_validation
- )
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [
- p for p in [recorded_pid] if p not in (exclude_pids or set())
- ],
- )
-
- killed_pids = []
- monkeypatch.setattr(
- gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig))
- )
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert probe_kwargs == [False], (
- "the fallback probe must still be non-destructive so the sweep "
- f"never unlinks the record it just read, got {probe_kwargs}"
- )
- assert result is False
- assert killed_pids == [] # the standalone gateway survived
-
-
class TestReaperCandidateIsSupervisorOwned:
"""Regression for the Windows pidfile-less supervisor-owned case (#83683).
@@ -992,102 +575,6 @@ class TestReaperCandidateIsSupervisorOwned:
there (#51325, #75936).
"""
- @staticmethod
- def _install_fake_psutil(monkeypatch, by_pid):
- fake_psutil = SimpleNamespace(Process=lambda pid: by_pid[pid])
- monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
-
- def test_windows_scheduled_task_gateway_spared_without_pidfile(self, monkeypatch):
- """A Windows gateway launched by the Scheduled Task is spared even when
- gateway.pid is missing — the supervisor-owned backstop catches it."""
- gateway_pid = 52615
- bootstrap_pid = 52616 # Task-launched `hermes gateway run` bootstrap
- orphan_pid = 99998 # a genuine orphan that SHOULD be reaped
-
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- # No pidfile => get_running_pid() returns None.
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
- # _get_service_pids() is empty on Windows.
- monkeypatch.setattr(gateway, "_get_service_pids", lambda: set())
-
- # Parent chain: gateway -> bootstrap -> services.exe (Task Scheduler).
- services = SimpleNamespace(pid=4, parent=lambda: None, name=lambda: "services.exe")
- bootstrap = SimpleNamespace(
- pid=bootstrap_pid, parent=lambda: services, name=lambda: "hermes-gateway.exe"
- )
- gw = SimpleNamespace(
- pid=gateway_pid, parent=lambda: bootstrap, name=lambda: "hermes-gateway.exe"
- )
- # Genuine Windows orphan: its parent exited; Windows does NOT reparent,
- # so psutil reports parent() is None — the chain never reaches
- # services.exe and the orphan is reaped.
- orphan = SimpleNamespace(pid=orphan_pid, parent=lambda: None, name=lambda: "hermes-gateway.exe")
- by_pid = {gateway_pid: gw, bootstrap_pid: bootstrap, orphan_pid: orphan}
- self._install_fake_psutil(monkeypatch, by_pid)
-
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [
- p for p in [gateway_pid, bootstrap_pid, orphan_pid]
- if p not in (exclude_pids or set())
- ],
- )
-
- killed_pids = []
- marked_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
- monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)
- monkeypatch.setattr("time.sleep", lambda _: None)
- monkeypatch.setattr("time.monotonic", lambda: 1.0)
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is True # the genuine orphan was reaped
- assert marked_pids == [orphan_pid] # only the genuine orphan is asked to drain
- assert killed_pids == [] # no Windows SIGTERM before the drain wait
-
- def test_macos_orphan_reparented_to_launchd_is_still_reaped(self, monkeypatch):
- """POSIX inertness guard: a genuine macOS orphan is reparented directly
- to launchd (PID 1) — supervisor-name ancestry must NOT spare it, or the
- reaper becomes a permanent no-op on macOS/WSL (#51325, #75936)."""
- orphan_pid = 99998
-
- monkeypatch.setattr(gateway, "is_macos", lambda: True)
- monkeypatch.setattr(gateway, "is_windows", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
- monkeypatch.setattr(gateway, "_get_service_pids", lambda: set())
-
- # Realistic macOS topology: the orphan's parent IS launchd (PID 1).
- launchd = SimpleNamespace(pid=1, parent=lambda: None, name=lambda: "launchd")
- orphan = SimpleNamespace(pid=orphan_pid, parent=lambda: launchd, name=lambda: "Python")
- self._install_fake_psutil(monkeypatch, {orphan_pid: orphan, 1: launchd})
-
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [
- p for p in [orphan_pid] if p not in (exclude_pids or set())
- ],
- )
-
- killed_pids = []
- marked_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
- monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)
- monkeypatch.setattr("time.sleep", lambda _: None)
- monkeypatch.setattr("time.monotonic", lambda: 1.0)
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is True
- assert orphan_pid in [pid for pid, _ in killed_pids]
-
def test_backstop_is_inert_on_posix(self, monkeypatch):
"""Direct unit guard: on non-Windows the backstop returns False without
touching psutil, even for a launchd/init-ancestored process."""
@@ -1099,21 +586,6 @@ class TestReaperCandidateIsSupervisorOwned:
monkeypatch.setitem(sys.modules, "psutil", SimpleNamespace(Process=_boom))
assert gateway._reaper_candidate_is_supervisor_owned(12345) is False
- def test_windows_backstop_fails_open_when_bootstrap_exited(self, monkeypatch):
- """Documented limitation: if the Task bootstrap already exited, the
- chain breaks before services.exe (Windows does not reparent) and the
- candidate is treated as a reapable orphan."""
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- stranded = SimpleNamespace(pid=4242, parent=lambda: None, name=lambda: "hermes-gateway.exe")
- self._install_fake_psutil(monkeypatch, {4242: stranded})
- assert gateway._reaper_candidate_is_supervisor_owned(4242) is False
-
-
-def test_module_has_logger():
- """Verify module has a logger instance (regression guard for #27154)."""
- assert hasattr(gateway, "logger")
- assert gateway.logger.name == "hermes_cli.gateway"
-
class TestWindowsScheduledTaskSupervisorGuard:
"""The reaper must skip when the profile's scheduled task is still a
@@ -1129,102 +601,6 @@ class TestWindowsScheduledTaskSupervisorGuard:
A2A/messaging on every desktop-app launch (#86098, #87001).
"""
- def test_running_task_skips_reap(self, monkeypatch):
- """Hermes_Gateway_* is Running => reaper returns False, kills nothing."""
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- # The guard must query the PROFILE-AWARE install-time task name from
- # gateway_windows.get_task_name(), never a hardcoded literal — a
- # hardcoded "HermesGateway" would leave the guard dormant on every
- # standard install (task name is Hermes_Gateway / Hermes_Gateway_<p>).
- import hermes_cli.gateway_windows as gateway_windows
-
- monkeypatch.setattr(
- gateway_windows, "get_task_name", lambda: "Hermes_Gateway_testprof"
- )
- queried = []
-
- def _fake_supervises(name):
- queried.append(name)
- return True
-
- monkeypatch.setattr(
- gateway, "_windows_scheduled_task_supervises", _fake_supervises
- )
-
- # Guard: if the task check were bypassed, these would be reaped.
- def _boom_find_gateway_pids(exclude_pids=None):
- raise AssertionError("must not scan when scheduled task supervises")
-
- monkeypatch.setattr(gateway, "find_gateway_pids", _boom_find_gateway_pids)
- killed_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is False
- assert killed_pids == []
- assert queried == ["Hermes_Gateway_testprof"]
-
- def test_ready_task_skips_reap(self, monkeypatch):
- """Ready is the post-launcher steady state — still supervised (#87001)."""
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- import hermes_cli.gateway_windows as gateway_windows
-
- monkeypatch.setattr(
- gateway_windows, "get_task_name", lambda: "Hermes_Gateway_testprof"
- )
- monkeypatch.setattr(
- gateway, "_windows_scheduled_task_state", lambda name: "Ready"
- )
-
- def _boom_find_gateway_pids(exclude_pids=None):
- raise AssertionError("must not scan when scheduled task is Ready")
-
- monkeypatch.setattr(gateway, "find_gateway_pids", _boom_find_gateway_pids)
- killed_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is False
- assert killed_pids == []
-
- def test_disabled_or_missing_task_still_reaps_real_orphan(self, monkeypatch):
- """Disabled / missing task => reaper behaves as before and still
- reaps a genuine orphan."""
- orphan_pid = 99998
-
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
- monkeypatch.setattr(gateway, "is_macos", lambda: False)
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(gateway, "_windows_scheduled_task_supervises", lambda name: False)
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
- monkeypatch.setattr(gateway, "_get_service_pids", lambda: set())
-
- monkeypatch.setattr(
- gateway,
- "find_gateway_pids",
- lambda exclude_pids=None: [
- p for p in [orphan_pid] if p not in (exclude_pids or set())
- ],
- )
- killed_pids = []
- marked_pids = []
- monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
- monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)
- monkeypatch.setattr("time.sleep", lambda _: None)
- monkeypatch.setattr("time.monotonic", lambda: 1.0)
-
- result = gateway._reap_unsupervised_gateway_orphans()
-
- assert result is True
- assert marked_pids == [orphan_pid]
- assert killed_pids == []
def test_windows_scheduled_task_running_returns_false_off_windows(
self, monkeypatch, inert_task_scheduler_probe
@@ -1241,7 +617,6 @@ class TestWindowsScheduledTaskSupervisorGuard:
assert gateway._windows_scheduled_task_state("HermesGateway") is None
def test_supervises_ready_and_queued_but_not_disabled(self, monkeypatch):
- monkeypatch.setattr(gateway, "is_windows", lambda: True)
states = {"Running": True, "Ready": True, "Queued": True, "Disabled": False, "MISSING": False}
for state, expected in states.items():
@@ -1249,97 +624,6 @@ class TestWindowsScheduledTaskSupervisorGuard:
assert gateway._windows_scheduled_task_supervises("Hermes_Gateway") is expected, state
-def test_find_windows_gateway_services_maps_verified_pid_tree(monkeypatch):
- """Only an SCM service whose subtree contains a validated gateway PID is returned."""
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- profile = SimpleNamespace(profile="default", pid=300, create_time=300.0)
-
- class FakeService:
- def __init__(self, name, pid, status="running"):
- self.name = name
- self.pid = pid
- self.status = status
-
- def as_dict(self):
- return {
- "name": self.name,
- "pid": self.pid,
- "status": self.status,
- }
-
- class FakeProcess:
- def __init__(self, pid):
- self.pid = pid
-
- def parents(self):
- return [FakeProcess(200), FakeProcess(100)]
-
- def children(self, recursive=False):
- assert self.pid == 100
- assert recursive is True
- return [FakeProcess(200), FakeProcess(300)]
-
- def create_time(self):
- return float(self.pid)
-
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: [
- FakeService("HermesGateway", 100),
- FakeService("UnrelatedService", 900, "stop_pending"),
- ],
- Process=FakeProcess,
- )
-
- result = gateway.find_windows_gateway_services(
- psutil_module=fake_psutil,
- profile_processes=[profile],
- )
-
- assert result == [
- gateway.WindowsGatewayService(
- name="HermesGateway",
- profile="default",
- service_pid=100,
- gateway_pid=300,
- descendant_pids=frozenset({200, 300}),
- descendant_identities=((200, 200.0), (300, 300.0)),
- service_create_time=100.0,
- gateway_create_time=300.0,
- )
- ]
-
-
-def test_find_windows_gateway_services_rejects_transitional_ancestor(monkeypatch):
- """A transitional service in the gateway ancestry remains fail-closed."""
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- profile = SimpleNamespace(profile="default", pid=300, create_time=300.0)
-
- class FakeService:
- def as_dict(self):
- return {"name": "HermesGateway", "pid": 100, "status": "stop_pending"}
-
- class FakeProcess:
- def __init__(self, pid):
- self.pid = pid
-
- def parents(self):
- return [FakeProcess(100)]
-
- def create_time(self):
- return float(self.pid)
-
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: [FakeService()],
- Process=FakeProcess,
- )
-
- with pytest.raises(RuntimeError, match="indeterminate status: stop_pending"):
- gateway.find_windows_gateway_services(
- psutil_module=fake_psutil,
- profile_processes=[profile],
- )
-
-
@pytest.mark.windows_only
def test_find_windows_gateway_services_ignores_task_scheduler_ancestor(monkeypatch):
"""gateway <- cmd.exe <- svchost.exe(Schedule) <- services.exe: the Task Scheduler host is not the
@@ -1399,110 +683,6 @@ def test_find_windows_gateway_services_ignores_task_scheduler_ancestor(monkeypat
assert [(s.name, s.service_pid, s.gateway_pid) for s in named] == [("HermesGateway", 2360, 18480)]
-def test_find_windows_gateway_services_rejects_shared_service_host_pid(monkeypatch):
- """A shared host PID cannot prove which service owns the gateway subtree."""
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- profile = SimpleNamespace(profile="default", pid=300, create_time=300.0)
-
- class FakeService:
- def __init__(self, name):
- self.name = name
-
- def as_dict(self):
- return {"name": self.name, "pid": 100, "status": "running"}
-
- class FakeProcess:
- def __init__(self, pid):
- self.pid = pid
-
- def parents(self):
- return [FakeProcess(100)]
-
- def children(self, recursive=False):
- return [FakeProcess(300)]
-
- def create_time(self):
- return float(self.pid)
-
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: [
- FakeService("HermesGatewayA"),
- FakeService("HermesGatewayB"),
- ],
- Process=FakeProcess,
- )
-
- with pytest.raises(RuntimeError, match="shared SCM host"):
- gateway.find_windows_gateway_services(
- psutil_module=fake_psutil,
- profile_processes=[profile],
- )
-
-
-def test_find_windows_gateway_services_fails_closed_on_service_access_error(
- monkeypatch,
-):
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- profile = SimpleNamespace(profile="default", pid=300, create_time=300.0)
-
- class InaccessibleService:
- def as_dict(self):
- raise PermissionError("access denied")
-
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: [InaccessibleService()],
- )
-
- with pytest.raises(RuntimeError, match="SCM"):
- gateway.find_windows_gateway_services(
- psutil_module=fake_psutil,
- profile_processes=[profile],
- )
-
-
-def test_find_windows_gateway_services_skips_unrelated_service_with_unreadable_config(monkeypatch):
- """An unrelated service whose QueryServiceConfigW fails with a plain OSError (WinError 15100 MUI
- loader, WinError 0 from OpenServiceW behind endpoint-security agents) is not Hermes's and must be
- skipped, not turned into "SCM service enumeration failed" that aborts `hermes update` (#116173)."""
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- import hermes_cli.gateway_windows as gateway_windows
-
- monkeypatch.setattr(gateway_windows, "hermes_service_roots", lambda: (r"C:\hermes\hermes-agent",))
-
- class MuiBrokenService:
- def name(self):
- return "IsolationSession"
-
- def binpath(self):
- raise OSError(15100, "The resource loader failed to find MUI file")
-
- class AccessDenied(Exception):
- pass
-
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: [MuiBrokenService()],
- AccessDenied=AccessDenied,
- )
-
- assert gateway.find_windows_gateway_services(psutil_module=fake_psutil, profile_processes=[]) == []
-
-
-def test_find_windows_gateway_services_fails_closed_when_scm_scan_is_indeterminate(
- monkeypatch,
-):
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- profile = SimpleNamespace(profile="default", pid=300, create_time=300.0)
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: (_ for _ in ()).throw(OSError("SCM unavailable")),
- )
-
- with pytest.raises(RuntimeError, match="SCM"):
- gateway.find_windows_gateway_services(
- psutil_module=fake_psutil,
- profile_processes=[profile],
- )
-
-
def test_find_profile_gateway_processes_strict_propagates_profile_listing_failure(
monkeypatch,
):
diff --git a/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py
index 7b404c8a14f..eb6aaec38f6 100644
--- a/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py
+++ b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py
@@ -50,10 +50,9 @@ def test_fires_for_secondary_when_default_root_has_multiplex_on(topology, monkey
)
monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice"))
- fired, out = _run()
+ fired, _ = _run()
assert fired is True
- assert "SECONDARY profile" in out
def test_the_retired_opt_out_still_warns_a_secondary(topology, monkeypatch):
@@ -65,10 +64,9 @@ def test_the_retired_opt_out_still_warns_a_secondary(topology, monkeypatch):
)
monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice"))
- fired, out = _run()
+ fired, _ = _run()
assert fired is True
- assert "SECONDARY profile of a multiplexed gateway" in out
def test_silent_for_default_profile_even_with_multiplex_on(topology, monkeypatch):
diff --git a/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py b/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py
index 93f95d2d858..712532b952c 100644
--- a/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py
+++ b/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py
@@ -29,13 +29,7 @@ class TestPathExistsSafe:
# A foreign /run/user/0/bus is unreadable, not "reachable".
assert gateway_cli._path_exists_safe(Path("/run/user/0/bus")) is False
- def test_returns_true_when_present(self, monkeypatch):
- monkeypatch.setattr(Path, "exists", lambda self: True)
- assert gateway_cli._path_exists_safe(Path("/run/user/1001/bus")) is True
- def test_returns_false_when_absent(self, monkeypatch):
- monkeypatch.setattr(Path, "exists", lambda self: False)
- assert gateway_cli._path_exists_safe(Path("/run/user/1001/bus")) is False
class TestRuntimeDirIsOurs:
diff --git a/tests/hermes_cli/test_gateway_linger.py b/tests/hermes_cli/test_gateway_linger.py
index 7a70ef8b38e..ff119129177 100644
--- a/tests/hermes_cli/test_gateway_linger.py
+++ b/tests/hermes_cli/test_gateway_linger.py
@@ -19,8 +19,6 @@ class TestEnsureLingerEnabled:
gateway._ensure_linger_enabled()
- out = capsys.readouterr().out
- assert "Systemd linger is enabled" in out
assert calls == []
@@ -42,9 +40,6 @@ class TestEnsureLingerEnabled:
gateway._ensure_linger_enabled()
- out = capsys.readouterr().out
- assert "Enabling linger" in out
- assert "Linger enabled" in out
assert run_calls == [(["loginctl", "enable-linger", "testuser"], True, True, False)]
@@ -160,14 +155,12 @@ def test_systemd_install_calls_linger_helper(monkeypatch, tmp_path, capsys):
gateway.systemd_install(force=False)
- out = capsys.readouterr().out
assert unit_path.exists()
assert [cmd for cmd, _ in calls] == [
["systemctl", "--user", "daemon-reload"],
["systemctl", "--user", "enable", gateway.get_service_name()],
]
assert helper_calls == [True]
- assert "User service installed and enabled" in out
@pytest.mark.parametrize("user", ["alice", "root"])
diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py
index 7961c2cfbc7..b0b40a96221 100644
--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py
+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py
@@ -820,39 +820,8 @@ def test_plan_names_every_process_it_will_sigterm_before_it_signals_anything(fle
assert fleet.ops == [] and fleet.pids == {"coder": 4101, "ops": 4102}
-def test_there_is_no_standalone_rollback_command(fleet):
- """(3) ``--standalone`` is gone from the parser: per-profile gateways are not a supported target."""
- import argparse
- from hermes_cli.subcommands.gateway import build_gateway_parser
- parser = argparse.ArgumentParser()
- build_gateway_parser(parser.add_subparsers(dest="command"),
- cmd_gateway=lambda a: None, cmd_proxy=lambda a: None,
- cmd_gateway_enroll=lambda a: None)
- with pytest.raises(SystemExit):
- parser.parse_args(["gateway", "migrate", "--standalone"])
- args = parser.parse_args(["gateway", "migrate", "--multiplex", "--dry-run"])
- assert args.multiplex and args.dry_run and not hasattr(args, "standalone")
-
-
-def test_a_windows_scheduled_task_secondary_is_detected_and_removed(fleet, monkeypatch, capsys):
- """Windows was refused outright ("not migrated automatically"), which left Windows users with
- no convergence path at all. The task (or its Startup-folder fallback) counts as an installed
- per-profile gateway, and is removed through the same service seam as a systemd unit."""
- from hermes_cli import gateway as gw
- monkeypatch.setattr(gw, "is_windows", lambda: True)
- monkeypatch.setattr(gw, "is_macos", lambda: False)
- monkeypatch.setattr(gw, "is_linux", lambda: False)
- fleet.services = {"coder": ("windows", False), "ops": ("windows", False)}
- plan = gm.build_migration_plan()
- assert [p.service_label() for p in plan.standalone_secondaries] == [
- "Windows scheduled task", "Windows scheduled task"]
- assert "Windows scheduled task" in "\n".join(gm.format_plan(plan, dry_run=True))
- assert gm.apply_migration(plan, served_wait=5.0) is True
- assert fleet.services == {"default": ("windows", False)}, "one host task, both secondaries gone"
- assert ("coder", "uninstall") in fleet.ops and ("ops", "uninstall") in fleet.ops
- assert "serves 3 profiles" in capsys.readouterr().out
def test_windows_task_detection_reads_both_the_task_and_the_startup_fallback(monkeypatch):
@@ -878,8 +847,7 @@ def test_windows_is_migratable_and_only_s6_is_refused(monkeypatch):
monkeypatch.setattr(gw, "_running_under_s6", lambda: True)
reason = gm._host_supports_migration()
- assert reason is not None and "Restart the container" in reason
- assert "nothing on this host was changed" in reason
+ assert reason is not None
def test_standalone_profile_is_listed_left_alone_and_not_a_fold_target(fleet):
@@ -895,5 +863,4 @@ def test_standalone_profile_is_listed_left_alone_and_not_a_fold_target(fleet):
payload = json.loads(json.dumps(plan.to_dict()))
assert payload["standalone_by_config"] == list(plan.standalone_by_config)
assert "ops" not in [p["profile"] for p in payload["profiles"]]
- lines = gm.format_plan(plan, dry_run=True)
- assert any("Standalone by config (gateway.standalone: true), left alone: ops" in line for line in lines)
+ assert any("ops" in line for line in gm.format_plan(plan, dry_run=True))
diff --git a/tests/hermes_cli/test_gateway_multiplex_mode.py b/tests/hermes_cli/test_gateway_multiplex_mode.py
index 64481097b0c..7cda76c18f3 100644
--- a/tests/hermes_cli/test_gateway_multiplex_mode.py
+++ b/tests/hermes_cli/test_gateway_multiplex_mode.py
@@ -20,7 +20,6 @@ import hermes_constants
from gateway.config import GatewayConfig, load_gateway_config
from hermes_cli import gateway_migrate as gm
from hermes_cli import gateway_multiplex_mode as mode
-from hermes_cli.config_defaults import DEFAULT_CONFIG
@pytest.fixture
@@ -53,7 +52,6 @@ def _name(home: Path) -> str:
def test_default_config_is_on_but_the_loader_leaves_an_unset_flag_undecided():
"""DEFAULT_CONFIG says on; GatewayConfig keeps "unset" distinguishable from "chosen" so the boot
guard can tell them apart (an explicit value must survive verbatim)."""
- assert DEFAULT_CONFIG["gateway"]["multiplex_profiles"] is True
assert GatewayConfig.from_dict({}).multiplex_profiles is None
assert not GatewayConfig.from_dict({}).multiplex_profiles # readers treat undecided as off
assert GatewayConfig.from_dict({"gateway": {"multiplex_profiles": False}}).multiplex_profiles is False
diff --git a/tests/hermes_cli/test_gateway_multiplex_refusal.py b/tests/hermes_cli/test_gateway_multiplex_refusal.py
index bc2517d4557..59192022beb 100644
--- a/tests/hermes_cli/test_gateway_multiplex_refusal.py
+++ b/tests/hermes_cli/test_gateway_multiplex_refusal.py
@@ -51,9 +51,8 @@ def test_standalone_named_home_still_served_by_host_record_is_refused_with_resca
monkeypatch.setattr(gw, "named_profile_served_by_running_multiplexer", lambda name=None: True)
refused, out = _refusal(gw)
assert refused is True
- assert "still serves profile 'coder'" in out
assert "gateway.standalone" in out
- assert "rescan-profiles" in out and "30s" in out
+ assert "rescan-profiles" in out
assert "--force" not in out
@@ -62,9 +61,7 @@ def test_non_standalone_refusal_names_the_opt_out(standalone_home):
(home / "config.yaml").write_text("{}\n", encoding="utf-8")
refused, out = _refusal(gw)
assert refused is True
- assert "Temporary compatibility path" in out
assert "gateway.standalone: true" in out
- assert "temporary compatibility shim" in out # the deprecation notice rides every mention
def test_setup_stale_host_record_names_rescan(standalone_home, monkeypatch, capsys):
diff --git a/tests/hermes_cli/test_gateway_multiplex_status.py b/tests/hermes_cli/test_gateway_multiplex_status.py
index 9cdf9d54a62..5b9e369da7b 100644
--- a/tests/hermes_cli/test_gateway_multiplex_status.py
+++ b/tests/hermes_cli/test_gateway_multiplex_status.py
@@ -102,20 +102,3 @@ def test_standalone_profile_status_reports_standalone_by_config(monkeypatch, tmp
assert "via the default-profile multiplexer" not in out
-def test_default_status_lists_standalone_profiles(monkeypatch, tmp_path):
- """The default (host) profile's status names the profiles that opted out by config."""
- import hermes_constants
-
- (tmp_path / "profiles" / "beta").mkdir(parents=True)
- (tmp_path / "profiles" / "beta" / "config.yaml").write_text("gateway:\n standalone: true\n", encoding="utf-8")
- (tmp_path / "config.yaml").write_text("gateway:\n multiplex_profiles: true\n", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)
- from hermes_cli import gateway as gw
-
- buf = io.StringIO()
- with redirect_stdout(buf):
- gw._gateway_command_inner(
- SimpleNamespace(gateway_command="status", deep=False, full=False, system=False)
- )
- assert "standalone by config (temporary compatibility shim): beta" in buf.getvalue()
diff --git a/tests/hermes_cli/test_gateway_platform_gating.py b/tests/hermes_cli/test_gateway_platform_gating.py
index e1c4dabe256..7d280ff8a18 100644
--- a/tests/hermes_cli/test_gateway_platform_gating.py
+++ b/tests/hermes_cli/test_gateway_platform_gating.py
@@ -16,18 +16,6 @@ import pytest
class TestMatrixHiddenOnWindows:
- @pytest.mark.linux_only
- def test_matrix_present_on_linux(self):
- """Sanity: matrix is still in the picker on Linux.
-
- Linux-gated because the assertion is the negative of the Windows
- gate — it only means anything when the host really is not Windows.
- """
- import hermes_cli.gateway as gateway_mod
-
- platforms = gateway_mod._all_platforms()
- keys = {p["key"] for p in platforms}
- assert "matrix" in keys, "matrix must be available on Linux"
@pytest.mark.windows_only
def test_matrix_absent_on_windows(self):
@@ -43,17 +31,3 @@ class TestMatrixHiddenOnWindows:
keys = {p["key"] for p in platforms}
assert "matrix" not in keys, "matrix must be hidden on Windows"
- @pytest.mark.windows_only
- def test_other_platforms_unaffected_on_windows(self):
- """Gating must only drop matrix, not collateral damage."""
- import hermes_cli.gateway as gateway_mod
-
- platforms = gateway_mod._all_platforms()
- keys = {p["key"] for p in platforms}
- # A representative sample of platforms that have no Windows
- # blockers — picker should still surface them.
- for must_have in ("telegram", "discord", "slack", "mattermost"):
- assert must_have in keys, (
- f"{must_have} disappeared from Windows picker — gate is "
- "over-filtering"
- )
diff --git a/tests/hermes_cli/test_gateway_proc_fallback.py b/tests/hermes_cli/test_gateway_proc_fallback.py
index b11fecad1f3..6156c0c9ff4 100644
--- a/tests/hermes_cli/test_gateway_proc_fallback.py
+++ b/tests/hermes_cli/test_gateway_proc_fallback.py
@@ -114,198 +114,14 @@ class TestProcFallback:
mock_ps.assert_not_called() # /proc dir existed, so ps not called
-class TestPsFallbackBsdCompat:
- """Verify the ps fallback command uses BSD/macOS-compatible flags.
-
- The old ``ps -A eww`` command fails on macOS/BSD because the BSD ``e``
- flag (show environment) is not valid there. The fix replaces it with
- ``ps -Aww`` which works on both BSD and procps ps.
- """
-
- def test_ps_flags_are_bsd_compatible(self):
- """ps is called with ``-Aww``, not ``-A eww``."""
- with (
- patch("hermes_cli.gateway.is_windows", return_value=False),
- patch("os.path.isdir", side_effect=lambda p: p != "/proc"),
- patch("hermes_cli.gateway._get_ancestor_pids", return_value=set()),
- patch("subprocess.run") as mock_run,
- ):
- # Return a failing rc=1 so the scan finishes quickly.
- mock_run.return_value = MagicMock(
- returncode=1, stdout="", stderr=""
- )
- pids = gateway_mod._scan_gateway_pids(set())
-
- assert not pids # rc=1 → empty result
- # Find the ps call among all subprocess.run invocations
- ps_call = None
- for call_args in mock_run.call_args_list:
- args = call_args[0][0] if call_args[0] else []
- if args and args[0] == "ps":
- ps_call = args
- break
- assert ps_call is not None, "ps was not invoked at all"
- assert "-Aww" in ps_call, (
- f"Expected ps -Aww, got: {ps_call}"
- )
- assert "eww" not in " ".join(ps_call), (
- f"ps eww flag still present: {ps_call}"
- )
-
- def test_ps_command_includes_pid_and_command_columns(self):
- """The ps command requests ``pid=,command=`` output columns."""
- with (
- patch("hermes_cli.gateway.is_windows", return_value=False),
- patch("os.path.isdir", side_effect=lambda p: p != "/proc"),
- patch("hermes_cli.gateway._get_ancestor_pids", return_value=set()),
- patch("subprocess.run") as mock_run,
- ):
- mock_run.return_value = MagicMock(
- returncode=0, stdout=" 123 gateway run\n", stderr=""
- )
- gateway_mod._scan_gateway_pids(set())
-
- ps_call = None
- for call_args in mock_run.call_args_list:
- args = call_args[0][0] if call_args[0] else []
- if args and args[0] == "ps":
- ps_call = args
- break
- assert ps_call is not None
- assert "-o" in ps_call and "pid=,command=" in ps_call, (
- f"Missing -o pid=,command= in: {ps_call}"
- )
class TestGetServicePidsAllProfiles:
"""_get_service_pids(all_profiles=...) discovery across profiles."""
- def test_default_scope_uses_current_profile_label(self):
- """Without all_profiles, only the current profile's launchd agent is
- located (per-label domain-explicit probe, #73627)."""
- located = []
-
- def _fake_locate(label):
- located.append(label)
- return ("gui/501", 123)
- with (
- patch("hermes_cli.gateway.is_macos", return_value=True),
- patch("hermes_cli.gateway.supports_systemd_services", return_value=False),
- patch(
- "hermes_cli.gateway.get_launchd_label",
- return_value="ai.hermes.gateway.myprofile",
- ),
- patch(
- "hermes_cli.gateway._locate_launchd_gateway_service",
- side_effect=_fake_locate,
- ),
- patch("subprocess.run") as mock_run,
- ):
- pids = gateway_mod._get_service_pids()
-
- assert pids == {123}
- # Default scope: exactly the current profile's label, no fleet
- # enumeration and no bare `launchctl list` scan.
- assert located == ["ai.hermes.gateway.myprofile"]
- launchctl_calls = [
- c[0][0]
- for c in mock_run.call_args_list
- if c[0] and c[0][0] and c[0][0][0] == "launchctl"
- ]
- assert launchctl_calls == []
-
- def test_all_profiles_enumerates_all_gateway_labels(self):
- """With all_profiles=True, every install-derived gateway label is
- located (#73627), and the bare ``launchctl list`` prefix scan still
- widens the EXCLUDE set with unmapped ai.hermes.gateway* agents
- (#74075 belt-and-suspenders)."""
- located = []
- label_pids = {
- "ai.hermes.gateway": 123,
- "ai.hermes.gateway-profile-b": 456,
- }
- def _fake_locate(label):
- located.append(label)
- pid = label_pids.get(label)
- return ("gui/501", pid) if pid else (None, None)
- with (
- patch("hermes_cli.gateway.is_macos", return_value=True),
- patch("hermes_cli.gateway.supports_systemd_services", return_value=False),
- patch(
- "hermes_cli.gateway.get_launchd_label",
- return_value="ai.hermes.gateway",
- ),
- patch(
- "hermes_cli.gateway.launchd_gateway_labels_for_install",
- return_value=["ai.hermes.gateway", "ai.hermes.gateway-profile-b"],
- ),
- patch(
- "hermes_cli.gateway._locate_launchd_gateway_service",
- side_effect=_fake_locate,
- ),
- patch("subprocess.run") as mock_run,
- ):
- mock_run.return_value = MagicMock(
- returncode=0,
- stdout=(
- "999\t0\tai.hermes.gateway-unmapped\n"
- "789\t0\tcom.apple.some.other.agent\n"
- ),
- stderr="",
- )
- pids = gateway_mod._get_service_pids(all_profiles=True)
-
- # Label-derived fleet + prefix-scan stragglers; non-gateway excluded.
- assert pids == {123, 456, 999}
- assert 789 not in pids
- assert sorted(located) == [
- "ai.hermes.gateway",
- "ai.hermes.gateway-profile-b",
- ]
- launchctl_calls = [
- c[0][0]
- for c in mock_run.call_args_list
- if c[0] and c[0][0] and c[0][0][0] == "launchctl"
- ]
- assert launchctl_calls == [["launchctl", "list"]]
-
- def test_all_profiles_empty_when_no_gateway_labels(self):
- """When no ai.hermes.gateway* labels exist, all_profiles returns empty."""
- with (
- patch("hermes_cli.gateway.is_macos", return_value=True),
- patch("hermes_cli.gateway.supports_systemd_services", return_value=False),
- patch("subprocess.run") as mock_run,
- ):
- mock_run.return_value = MagicMock(
- returncode=0,
- stdout="789\t0\tcom.apple.some.other.agent\n",
- stderr="",
- )
- pids = gateway_mod._get_service_pids(all_profiles=True)
-
- assert pids == set()
-
- def test_all_profiles_handles_broken_pid_column(self):
- """Non-integer PID entries are silently skipped."""
- with (
- patch("hermes_cli.gateway.is_macos", return_value=True),
- patch("hermes_cli.gateway.supports_systemd_services", return_value=False),
- patch("subprocess.run") as mock_run,
- ):
- mock_run.return_value = MagicMock(
- returncode=0,
- stdout=(
- "-\t0\tai.hermes.gateway.broken\n"
- " 123 \t0\tai.hermes.gateway.ok\n"
- ),
- stderr="",
- )
- pids = gateway_mod._get_service_pids(all_profiles=True)
-
- assert pids == {123}
def test_all_profiles_preserves_systemd_behavior(self):
"""systemd scope is unaffected by the all_profiles switch — it already
diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.py
index ca2e000cf3e..560fc60f42f 100644
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@ -102,14 +102,6 @@ class TestGatewayLifecyclePattern:
def test_launchctl_submit_bootstrap_commands(self, text):
assert _contains_gateway_lifecycle_command(text), f"Should match: {text!r}"
- def test_launchctl_bootout_verb_is_caught(self):
- """`bootout` was missing from Branch B's verb list entirely — the
- 2026-08-02 incident command used exactly this verb (it deregisters
- the job outright, unlike stop/kickstart) and slipped past both this
- check and the missing-verb rule in tools/approval.py."""
- assert _contains_gateway_lifecycle_command(
- "launchctl bootout gui/501/ai.hermes.gateway"
- )
def test_label_defined_before_verb_is_caught(self):
"""2026-08-02 incident reproduction: the label comes from a shell
@@ -364,11 +356,6 @@ class TestProfileFlagGatewayLifecycle:
# the profile flag (#30719 rationale).
assert not _contains_gateway_lifecycle_command(text), f"Should allow: {text!r}"
- def test_adjacent_form_still_blocked(self):
- # Branch A remains unconditional — the profile-flag check is an
- # additional layer, not a replacement.
- assert _contains_gateway_lifecycle_command("hermes gateway restart")
- assert _contains_gateway_lifecycle_command("hermes gateway stop")
def test_hermes_home_derived_profile(self, monkeypatch):
# Without HERMES_PROFILE the guard falls back to the HERMES_HOME-
@@ -421,7 +408,6 @@ class TestCronCreateLifecycleBlock:
assert rc == 1
out = capsys.readouterr().out
assert "Blocked" in out
- assert "#30719" in out
def test_block_script_with_lifecycle_command(self, tmp_path, capsys, monkeypatch):
@@ -452,30 +438,6 @@ class TestCronCreateLifecycleBlock:
assert "Blocked" in out
- def test_allow_empty_prompt(self, capsys):
- """Empty prompt (no lifecycle content) should pass the filter — the
- API will still reject it for lacking prompt+skill, but that's a
- separate validation, not the lifecycle guard."""
- args = Namespace(
- cron_command="create",
- schedule="30m",
- prompt=None,
- name=None,
- deliver=None,
- repeat=None,
- skill=None,
- skills=None,
- script=None,
- workdir=None,
- profile=None,
- no_agent=False,
- )
- rc = cron_command(args)
- # The lifecycle guard passes (no gateway command in prompt).
- # The API rejects it for "requires prompt or skill" → rc 1, but
- # the error message is about prompt/skill, NOT about "Blocked".
- out = capsys.readouterr().out
- assert "Blocked" not in out
# ---------------------------------------------------------------------------
@@ -614,22 +576,6 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 1
assert "referenced script" in result["error"]
- def test_blocks_launchctl_submit_inside_gateway(self, monkeypatch, tmp_path):
- import tools.terminal_tool as tt
-
- script = tmp_path / "health-check.sh"
- script.write_text("#!/bin/bash\nprintf 'healthy\\n'\n", encoding="utf-8")
- self._patch_env(monkeypatch, self._make_fake_env(), inside_gateway=True)
-
- result = json.loads(tt.terminal_tool(
- command=(
- "launchctl submit -l ai.hermes.delayed-ops -- "
- f"/bin/bash {script}"
- )
- ))
-
- assert result["exit_code"] == 1
- assert "KeepAlive" in result["error"]
def test_oversized_root_skips_launchctl_prescan_and_fails_closed(
self, monkeypatch
@@ -932,23 +878,6 @@ class TestTerminalToolGatewayLifecycleGuard:
class TestLifecycleGuardModule:
"""Direct tests for cron.lifecycle_guard.check_gateway_lifecycle."""
- def test_dot_operator_sourced_script_is_scanned(self, tmp_path):
- """`. ./script.sh` must reach the referenced-script scan.
-
- The dot operator and `source` are the same POSIX builtin, but the
- executable test compared only `Path(executable).name` — and
- `Path(".").name` is the empty string, so `source` was caught while a
- bare `.` slipped through and the sourced script was never scanned.
- """
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- script = tmp_path / "restart.sh"
- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")
- assert (
- contains_gateway_lifecycle_command_or_referenced_script(f". {script}")
- is True
- )
def test_nul_padded_script_is_still_scanned(self, tmp_path):
"""A NUL byte in a *text* script must not disable the scan.
@@ -968,30 +897,7 @@ class TestLifecycleGuardModule:
is True
)
- def test_source_builtin_sourced_script_is_scanned(self, tmp_path):
- """The `source` spelling must stay blocked (it already was)."""
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- script = tmp_path / "restart.sh"
- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")
- assert (
- contains_gateway_lifecycle_command_or_referenced_script(f"source {script}")
- is True
- )
- def test_dot_operator_clean_script_not_blocked(self, tmp_path):
- """Widening the dot check must not false-block an innocent sourced
- script — e.g. sourcing a venv activate or an env file."""
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- script = tmp_path / "activate.sh"
- script.write_text("#!/bin/bash\nexport PATH=/usr/bin:$PATH\n", encoding="utf-8")
- assert (
- contains_gateway_lifecycle_command_or_referenced_script(f". {script}")
- is False
- )
def test_nul_padded_script_without_shebang_is_scanned(self, tmp_path):
"""Same bypass without a shebang — bash still runs it, so still scan.
@@ -1009,21 +915,6 @@ class TestLifecycleGuardModule:
is True
)
- def test_elf_binary_is_not_scanned_as_script(self, tmp_path):
- """#76762 must stay fixed: a real binary is nothing-to-scan, no crash.
-
- Its decoded machine code must never be tokenized as shell text, and the
- guard must not fail closed on an innocent interpreter invocation.
- """
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- binary = tmp_path / "tool"
- binary.write_bytes(b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 64 + b"/usr/bin/x\x00")
- assert (
- contains_gateway_lifecycle_command_or_referenced_script(f"{binary} --version")
- is False
- )
def test_macho_binary_is_not_scanned_as_script(self, tmp_path):
"""Same for Mach-O, including the universal/fat signature (macOS)."""
@@ -1059,28 +950,12 @@ class TestLifecycleGuardModule:
is True
)
- def test_clean_script_without_lifecycle_command_not_blocked(self, tmp_path):
- """Sanity: the change must not false-block innocent scripts."""
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- script = tmp_path / "safe.sh"
- script.write_bytes(b"#!/bin/bash\necho hello\n")
- assert (
- contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")
- is False
- )
def test_prompt_with_command_raises(self):
from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle
- with pytest.raises(GatewayLifecycleBlocked) as exc:
+ with pytest.raises(GatewayLifecycleBlocked):
check_gateway_lifecycle("please run hermes gateway restart", None)
- assert "#30719" in str(exc.value)
- def test_clean_prompt_does_not_raise(self):
- from cron.lifecycle_guard import check_gateway_lifecycle
- check_gateway_lifecycle("research the gateway architecture", None)
- check_gateway_lifecycle("check server health and restart watchers", None)
def test_script_with_command_raises(self, tmp_path, monkeypatch):
from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle
@@ -1089,14 +964,6 @@ class TestLifecycleGuardModule:
with pytest.raises(GatewayLifecycleBlocked):
check_gateway_lifecycle("clean prompt", str(script))
- def test_script_with_launchctl_submit_raises(self, tmp_path):
- from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle
- script = tmp_path / "persistent.sh"
- script.write_text(
- "#!/bin/bash\nlaunchctl submit -l ai.hermes.loop -- /bin/true\n"
- )
- with pytest.raises(GatewayLifecycleBlocked):
- check_gateway_lifecycle("clean prompt", str(script))
@pytest.mark.parametrize("line", [
# #62891: neutral labels defeat any label-anchored regex, so cron
@@ -1113,14 +980,6 @@ class TestLifecycleGuardModule:
with pytest.raises(GatewayLifecycleBlocked):
check_gateway_lifecycle("clean prompt", str(script))
- def test_split_across_prompt_and_script_still_blocks(self, tmp_path):
- """Concatenated scan prevents splitting the command between prompt and
- script to slip through."""
- from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle
- script = tmp_path / "ops.sh"
- script.write_text("hermes gateway stop\n", encoding="utf-8")
- with pytest.raises(GatewayLifecycleBlocked):
- check_gateway_lifecycle("daily ops job", str(script))
def test_binary_script_does_not_silently_bypass(self, tmp_path):
"""Non-UTF-8 bytes used to be swallowed by UnicodeDecodeError; now we
@@ -1179,53 +1038,8 @@ class TestLifecycleGuardModule:
with pytest.raises(GatewayLifecycleBlocked):
check_gateway_lifecycle("clean prompt", str(script))
- def test_absolute_path_binary_does_not_crash_guard(self):
- """#76762: a terminal command invoking a binary by absolute path
- (e.g. /usr/bin/python3) must not crash the guard with
- ValueError: embedded null byte.
-
- Before the fix, the walk read the binary's bytes, decoded them as
- text, and re-tokenized machine code containing NUL bytes; the
- recursion then called Path.resolve() on a path with an embedded NUL
- and only OSError was caught. Binaries are now skipped as
- "nothing to scan" and ValueError is tolerated at resolve time.
- """
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- result = contains_gateway_lifecycle_command_or_referenced_script(
- '/usr/bin/python3 -c "print(1)"'
- )
- assert result is False
-
- def test_nul_byte_in_path_token_does_not_crash_guard(self):
- """Residual #76762 class: when a NUL byte survives into the *path
- token itself* (tokenized binary-adjacent command text), ``os.open``
- raises ValueError — not OSError — inside
- ``_read_referenced_script``. The guard must treat it as "nothing to
- scan", never crash.
- """
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- result = contains_gateway_lifecycle_command_or_referenced_script(
- "bash ./run\x00me.sh", cwd="/tmp"
- )
- assert result is False
-
- def test_read_referenced_script_tolerates_nul_in_path(self):
- """#77703: _read_referenced_script opens by path. A path with an
- embedded NUL byte (a binary's bytes mis-tokenized into a bogus path by
- the recursion) makes os.open raise ValueError — not OSError — which used
- to escape the OSError-only guard and crash the whole terminal tool. It
- is now caught and reported as nothing-to-scan."""
- from pathlib import Path
- from cron.lifecycle_guard import _read_referenced_script
- text, unsafe = _read_referenced_script(Path("/tmp/hermes\x00binary"))
- assert text is None
- assert unsafe is False
def test_remote_read_fallback_binary_does_not_crash_guard(self):
"""#77703: in the gateway the referenced-script walk carries a
@@ -1339,27 +1153,6 @@ class TestLifecycleGuardModule:
str(script)
) is True
- def test_read_referenced_script_choke_point_refuses_cloud_paths(
- self, tmp_path, monkeypatch
- ):
- """The cloud refusal lives in _read_referenced_script itself so EVERY
- caller (terminal walk AND cron-script scan) is covered — not just the
- walk-level short-circuit in _contains_unsafe_gateway_action."""
- import cron.lifecycle_guard as lifecycle_guard
-
- cloud_dir = tmp_path / "Library" / "CloudStorage" / "OneDrive" / "s"
- cloud_dir.mkdir(parents=True)
- script = cloud_dir / "job.sh"
- script.write_text("#!/bin/sh\necho safe\n", encoding="utf-8")
-
- def forbid_open(path, flags, *args, **kwargs): # pragma: no cover
- pytest.fail("choke point opened a cloud placeholder path")
-
- monkeypatch.setattr(lifecycle_guard.os, "open", forbid_open)
-
- text, unsafe = lifecycle_guard._read_referenced_script(script)
- assert text is None
- assert unsafe is True
def test_cron_script_scan_blocks_cloud_script_without_opening(
self, tmp_path, monkeypatch
@@ -1402,17 +1195,6 @@ class TestLifecycleGuardModule:
# -- Whole-class regression tests (tilllt's T1-T4 on PR #79454) --------
- def test_tilde_nul_candidate_does_not_crash_terminal_walk(self):
- """T1: ``Path('~user\\x00...').expanduser()`` raises ValueError one
- frame *before* ``os.open`` — the per-syscall guards never see it. The
- ingestion-boundary sanitizer must reject the candidate instead."""
- from cron.lifecycle_guard import (
- contains_gateway_lifecycle_command_or_referenced_script,
- )
- result = contains_gateway_lifecycle_command_or_referenced_script(
- "'~jenkins\x00broken/payload.sh' arg", cwd="/tmp"
- )
- assert result is False
def test_tilde_nul_candidate_does_not_crash_cron_script_resolution(self):
"""T2: the same ``expanduser`` crash via the cron ``script`` path
@@ -1758,14 +1540,6 @@ class TestRelativePathDoesNotDisableDataExemption:
def test_relative_path_does_not_open_an_execution_route(self, command):
assert self._scan(command) is True
- @pytest.mark.parametrize("command", [
- # Real dot-commands must still defeat the exemption.
- 'sqlite3 db ".shell hermes gateway restart"',
- 'sqlite3 db ".system systemctl restart hermes-gateway"',
- 'psql -c "\\! systemctl restart hermes-gateway"',
- ])
- def test_dot_commands_still_block(self, command):
- assert self._scan(command) is True
class TestCreateJobBlocksLifecycleCommands:
@@ -1954,40 +1728,6 @@ class TestTerminalToolGatewayLifecycleGuardRemote:
assert "cannot restart, stop, or uninstall" not in result["error"]
-class TestCronCreateLifecycleBlockExtra:
- """Additional cron create lifecycle guard coverage."""
-
- @pytest.fixture(autouse=True)
- def _setup_cron_dir(self, tmp_path, monkeypatch):
- monkeypatch.setattr("cron.jobs.CRON_DIR", tmp_path / "cron")
- monkeypatch.setattr("cron.jobs.JOBS_FILE", tmp_path / "cron" / "jobs.json")
- monkeypatch.setattr("cron.jobs.OUTPUT_DIR", tmp_path / "cron" / "output")
-
- def test_cron_nested_wrapper_script_is_scanned(self, tmp_path, capsys, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- scripts_dir = tmp_path / ".hermes" / "scripts"
- scripts_dir.mkdir(parents=True)
- (scripts_dir / "inner.sh").write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")
- (scripts_dir / "outer.sh").write_text("#!/bin/bash\n/bin/bash inner.sh\n", encoding="utf-8")
- args = Namespace(
- cron_command="create",
- schedule="1h",
- prompt=None,
- name=None,
- deliver=None,
- repeat=None,
- skill=None,
- skills=None,
- script="outer.sh",
- workdir=None,
- profile=None,
- no_agent=True,
- )
- rc = cron_command(args)
- assert rc == 1
- out = capsys.readouterr().out
- assert "Blocked" in out
-
class TestLifecycleGuardDataArgumentExemption:
"""Lifecycle words inside DATA arguments (SQL text, grep patterns) must
not block; the same words in command position must. Reproduces the two
@@ -2105,33 +1845,6 @@ class TestLifecycleGuardNeverRaises:
)
assert self._scan(f"source {zshrc}") is False
- def test_fstat_directory_mode_is_not_unsafe(self, tmp_path, monkeypatch):
- """#86753 Unix contract: os.open(dir) succeeds, fstat is not S_ISREG.
-
- Windows raises OSError on os.open(dir) and already returns
- nothing-to-scan. Linux/macOS open the directory and used to
- return unsafe=True, blocking sourced zshrcs that mention
- ``~/.docker/completions``.
- """
- import os
- import stat as statmod
-
- from cron.lifecycle_guard import _read_referenced_script
-
- probe = tmp_path / "probe"
- probe.write_text("echo hi\n", encoding="utf-8")
- orig = os.fstat
-
- def _dir_fstat(fd):
- orig(fd)
- class _DirStat:
- st_mode = statmod.S_IFDIR | 0o755
- return _DirStat()
-
- monkeypatch.setattr(os, "fstat", _dir_fstat)
- text, unsafe = _read_referenced_script(probe)
- assert text is None
- assert unsafe is False
def test_directory_and_dev_null_fail_closed_not_crash(self, tmp_path):
# Directories are not scripts (#86753). Devices stay fail-closed
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index e27048a761a..26d5344f43d 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -316,12 +316,6 @@ class TestGeneratedSystemdUnits:
assert expected > 60
assert self._expected_timeout_stop_sec() in unit
- def test_timeout_stop_sec_follows_a_raised_cron_drain_timeout(self, monkeypatch):
- monkeypatch.setattr(gateway_cli, "_get_restart_drain_timeout", lambda: 0.0)
- monkeypatch.setattr(gateway_cli, "_get_cron_drain_timeout", lambda: 60.0)
-
- unit = gateway_cli.generate_systemd_unit(system=False)
- assert f"TimeoutStopSec={resolve_systemd_timeout_stop_sec(0.0, 60.0)}" in unit
def test_timeout_stop_sec_keeps_the_floor_when_cron_drain_is_opted_out(
self, monkeypatch
@@ -362,19 +356,6 @@ class TestGeneratedSystemdUnits:
monkeypatch.delenv("LD_LIBRARY_PATH")
assert "LD_LIBRARY_PATH" not in gateway_cli.generate_systemd_unit(system=False)
- def test_unit_stop_budget_beats_drain_only_formula_with_real_loaders(
- self, monkeypatch
- ):
- monkeypatch.delenv("HERMES_RESTART_DRAIN_TIMEOUT", raising=False)
- monkeypatch.delenv("HERMES_CRON_DRAIN_TIMEOUT", raising=False)
- drain = gateway_cli._get_restart_drain_timeout()
- cron = gateway_cli._get_cron_drain_timeout()
- unit = gateway_cli.generate_systemd_unit(system=False)
- expected = resolve_systemd_timeout_stop_sec(drain, cron)
- assert f"TimeoutStopSec={expected}" in unit
- old_drain_only = int(max(60, int(drain or 0) + 30))
- if cron > 0 and drain <= 0:
- assert expected > old_drain_only
def test_user_unit_does_not_leak_profile_node_symlink_target(self, tmp_path, monkeypatch):
# Regression for the multi-profile gateway restart-loop flap (#48700):
@@ -756,18 +737,6 @@ class TestLaunchdServiceRecovery:
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
assert gateway_cli._launchd_domain() == "user/501"
-
- # ── PID parsing ──────────────────────────────────────────────────────
-
-
- # ── Probe requires PID ───────────────────────────────────────────────
-
-
- # ── Unsupport marker lifecycle ───────────────────────────────────────
-
-
- # ── launchd_status with active supervision ───────────────────────────
-
def test_launchd_status_reports_fallback_when_unsupported_and_pid_running(self, tmp_path, monkeypatch, capsys):
"""When the unsupported marker exists and a fallback PID is running."""
plist_path = tmp_path / "ai.hermes.gateway.plist"
@@ -791,10 +760,7 @@ class TestLaunchdServiceRecovery:
gateway_cli.launchd_status()
out = capsys.readouterr().out
- assert "cannot manage the gateway on this macos version" in out.lower()
- assert "Detached fallback process is running" in out
- assert "PID 88888" in out
- assert "NOT available" in out
+ assert "88888" in out # the running detached-fallback PID is reported
class TestLaunchdDomainDetection:
@@ -1547,7 +1513,7 @@ class TestSystemUnitRefreshSyncsHermesHome:
# Correct installed unit (operator's HERMES_HOME + drain timeout).
monkeypatch.setenv("HERMES_HOME", str(alice_hermes))
good_unit = gateway_cli.generate_systemd_unit(system=True, run_as_user="alice")
- assert "TimeoutStopSec=210" in good_unit
+ assert f"TimeoutStopSec={resolve_systemd_timeout_stop_sec(180.0, DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT)}" in good_unit
unit_path.write_text(good_unit, encoding="utf-8")
# Simulate sudo without inherited HERMES_HOME (falls back to root).
@@ -1557,90 +1523,7 @@ class TestSystemUnitRefreshSyncsHermesHome:
assert os.environ["HERMES_HOME"] == str(alice_hermes)
assert gateway_cli.systemd_unit_is_current(system=True) is True
- def test_is_current_syncs_before_reading_unit(self, tmp_path, monkeypatch):
- """CHOKEPOINT INVARIANT: systemd_unit_is_current() must adopt the
- unit's pinned HERMES_HOME *before* it reads/compares the unit.
-
- This is the single site that enforces sync-before-compare for every
- path (refresh gates on it; status/install call it). If a future edit
- moves the sync after the read (or drops it), this test fails.
- """
- order = []
- unit_path = tmp_path / "hermes-gateway.service"
- unit_path.write_text("[Unit]\n", encoding="utf-8")
-
- monkeypatch.setattr(gateway_cli, "get_systemd_unit_path", lambda system=False: unit_path)
- real_read_text = Path.read_text
-
- def tracking_sync(system):
- order.append("sync")
-
- def tracking_read_text(self, *a, **k):
- if self == unit_path:
- order.append("read")
- return real_read_text(self, *a, **k)
-
- monkeypatch.setattr(gateway_cli, "_sync_hermes_home_from_systemd_unit", tracking_sync)
- monkeypatch.setattr(Path, "read_text", tracking_read_text)
- # Avoid a real generate/compare — we only assert sync precedes read.
- monkeypatch.setattr(gateway_cli, "generate_systemd_unit", lambda **k: "[Unit]\n")
- monkeypatch.setattr(gateway_cli, "_read_systemd_user_from_unit", lambda p: None)
-
- gateway_cli.systemd_unit_is_current(system=True)
-
- assert order, "systemd_unit_is_current did not run sync or read"
- assert order[0] == "sync", f"sync must precede unit read; got {order}"
- assert "read" in order and order.index("sync") < order.index("read")
-
- def test_start_and_restart_delegate_sync_to_chokepoint(self, monkeypatch):
- """start/restart must NOT pre-sync at the callsite — the sync is owned
- by the systemd_unit_is_current chokepoint that refresh gates on. This
- pins the single-chokepoint design so a future edit can't reintroduce a
- redundant (or, worse, out-of-order) callsite sync.
- """
- for entry in ("systemd_start", "systemd_restart"):
- calls = []
- monkeypatch.setattr(gateway_cli, "_select_systemd_scope", lambda system=False: True)
- monkeypatch.setattr(gateway_cli, "_require_root_for_system_service", lambda action: None)
- monkeypatch.setattr(
- gateway_cli, "_require_service_installed", lambda action, system=False: None
- )
- monkeypatch.setattr(
- gateway_cli,
- "_sync_hermes_home_from_systemd_unit",
- lambda system: calls.append("sync"),
- )
- monkeypatch.setattr(
- gateway_cli,
- "refresh_systemd_unit_if_needed",
- lambda system=False: calls.append("refresh"),
- )
- monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
- monkeypatch.setattr(gateway_cli, "_systemd_main_pid", lambda system=False: None)
- monkeypatch.setattr(
- gateway_cli,
- "_run_systemctl",
- lambda args, **kwargs: calls.append("systemctl")
- or SimpleNamespace(returncode=0, stdout="", stderr=""),
- )
- monkeypatch.setattr(
- gateway_cli,
- "_wait_for_systemd_service_restart",
- lambda system=False, previous_pid=None: True,
- )
-
- getattr(gateway_cli, entry)(system=True)
-
- # refresh runs; the callsite adds NO separate sync before it (the
- # chokepoint inside refresh->is_current owns the sync). Here refresh
- # is mocked out, so no "sync" should appear at all for the refresh
- # phase — proving the callsite pre-sync was removed.
- assert "refresh" in calls, f"{entry} must call refresh_systemd_unit_if_needed"
- assert calls.count("sync") == 0, (
- f"{entry} should delegate sync to the chokepoint, not pre-sync "
- f"at the callsite; got {calls}"
- )
class TestHermesHomeForTargetUser:
@@ -1671,20 +1554,6 @@ class TestGeneratedUnitUsesDetectedVenv:
assert "/venv/" not in unit or "/.venv/" in unit
-class TestGeneratedUnitIncludesLocalBin:
- """~/.local/bin must be in PATH so uvx/pipx tools are discoverable."""
-
- def test_system_unit_includes_local_bin_in_path(self, monkeypatch):
- monkeypatch.setattr(
- gateway_cli,
- "_build_user_local_paths",
- lambda home_path, existing: [str(home_path / ".local" / "bin")],
- )
- unit = gateway_cli.generate_systemd_unit(system=True)
- # System unit uses the resolved home dir from _system_service_identity
- assert "/.local/bin" in unit
-
-
class TestSystemServiceIdentityRootHandling:
"""Root user handling in _system_service_identity()."""
@@ -1708,19 +1577,6 @@ class TestSystemServiceIdentityRootHandling:
assert username == "root"
assert home == root_info.pw_dir
- def test_non_root_user_passes_through(self, monkeypatch):
- """Normal non-root user works as before."""
-
- monkeypatch.delenv("SUDO_USER", raising=False)
- monkeypatch.setenv("USER", "nobody")
- monkeypatch.setenv("LOGNAME", "nobody")
-
- try:
- username, group, home, _uid = gateway_cli._system_service_identity(run_as_user=None)
- assert username == "nobody"
- except ValueError as e:
- # "nobody" might not exist on all systems
- assert "Unknown user" in str(e)
class TestEnsureUserSystemdEnv:
@@ -1740,13 +1596,6 @@ class TestEnsureUserSystemdEnv:
assert os.environ["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={bus_socket}"
- def test_systemctl_cmd_calls_ensure_for_user_mode(self, monkeypatch):
- calls = []
- monkeypatch.setattr(gateway_cli, "_ensure_user_systemd_env", lambda: calls.append("called"))
-
- result = gateway_cli._systemctl_cmd(system=False)
- assert result == ["systemctl", "--user"]
- assert calls == ["called"]
class TestPreflightUserSystemd:
@@ -1986,20 +1835,6 @@ class TestDockerAwareGateway:
with pytest.raises(SystemctlUnavailableError):
gateway_cli._run_systemctl(["start", "hermes-gateway"])
- def test_run_systemctl_passes_through_on_success(self, monkeypatch):
- """_run_systemctl delegates to subprocess.run when systemctl exists."""
- calls = []
-
- def fake_run(cmd, **kwargs):
- calls.append(cmd)
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
-
- result = gateway_cli._run_systemctl(["status", "hermes-gateway"])
- assert result.returncode == 0
- assert len(calls) == 1
- assert "status" in calls[0]
def test_install_in_container_prints_docker_guidance(self, monkeypatch, capsys):
"""'hermes gateway install' inside Docker exits 0 with container guidance."""
@@ -2146,16 +1981,6 @@ class TestLegacyHermesUnitDetection:
results = gateway_cli._find_legacy_hermes_units()
assert len(results) == 1, f"Variant {i} not detected: {execstart!r}"
- def test_print_legacy_unit_warning_shows_migration_hint(self, tmp_path, monkeypatch, capsys):
- user_dir, _ = self._setup_search_paths(tmp_path, monkeypatch)
- (user_dir / "hermes.service").write_text(self._OUR_UNIT_TEXT, encoding="utf-8")
-
- gateway_cli.print_legacy_unit_warning()
- out = capsys.readouterr().out
-
- assert "Legacy" in out
- assert "hermes.service" in out
- assert "hermes gateway migrate-legacy" in out
class TestRemoveLegacyHermesUnits:
@@ -2228,32 +2053,6 @@ class TestRemoveLegacyHermesUnits:
class TestMigrateLegacyCommand:
"""Tests for the `hermes gateway migrate-legacy` subcommand dispatch."""
- def test_migrate_legacy_subparser_accepts_dry_run_and_yes(self):
- """Verify the argparse subparser is registered and parses flags."""
- import hermes_cli.main as cli_main
-
- parser = cli_main.build_parser() if hasattr(cli_main, "build_parser") else None
- # Fall back to calling main's setup helper if direct access isn't exposed
- # The key thing: the subparser must exist. We verify by constructing
- # a namespace through argparse directly — but if build_parser isn't
- # public, just confirm that `hermes gateway --help` shows it.
- import subprocess
- import sys
-
- project_root = cli_main.PROJECT_ROOT if hasattr(cli_main, "PROJECT_ROOT") else None
- if project_root is None:
- import hermes_cli.gateway as gw
- project_root = gw.PROJECT_ROOT
-
- result = subprocess.run(
- [sys.executable, "-m", "hermes_cli.main", "gateway", "--help"],
- cwd=str(project_root),
- capture_output=True,
- text=True,
- timeout=15,
- )
- assert result.returncode == 0
- assert "migrate-legacy" in result.stdout
def test_gateway_command_migrate_legacy_dispatches(
self, tmp_path, monkeypatch, capsys
@@ -2278,37 +2077,6 @@ class TestMigrateLegacyCommand:
assert called == {"interactive": False, "dry_run": False}
-class TestGatewayStatusParser:
- def test_gateway_status_subparser_accepts_full_flag(self):
- import subprocess
- import sys
-
- result = subprocess.run(
- [sys.executable, "-m", "hermes_cli.main", "gateway", "status", "-l", "--help"],
- cwd=str(gateway_cli.PROJECT_ROOT),
- capture_output=True,
- text=True,
- timeout=15,
- )
-
- assert result.returncode == 0
- assert "unrecognized arguments" not in result.stderr
-
- def test_migrate_legacy_on_unsupported_platform_prints_message(
- self, monkeypatch, capsys
- ):
- monkeypatch.setattr(gateway_cli, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(gateway_cli, "is_macos", lambda: False)
-
- args = SimpleNamespace(
- gateway_command="migrate-legacy", dry_run=False, yes=True
- )
- gateway_cli.gateway_command(args)
-
- out = capsys.readouterr().out
- assert "only applies to systemd" in out
-
-
class TestSystemdInstallOffersLegacyRemoval:
"""Verify that systemd_install prompts to remove legacy units first."""
@@ -2453,12 +2221,11 @@ class TestSystemScopeRequiresRootError:
with pytest.raises(gateway_cli.SystemScopeRequiresRootError) as excinfo:
gateway_cli._require_root_for_system_service("start")
- assert excinfo.value.args[0] == "System gateway start requires root. Re-run with sudo."
+ assert "start" in excinfo.value.args[0]
assert excinfo.value.args[1] == "start"
# str(e) renders only the message, not the tuple repr, so that
# wizard format strings like f"Failed: {e}" print cleanly.
- assert str(excinfo.value) == "System gateway start requires root. Re-run with sudo."
- assert f"Failed: {excinfo.value}" == "Failed: System gateway start requires root. Re-run with sudo."
+ assert str(excinfo.value) == excinfo.value.args[0]
def test_error_is_runtime_error_subclass(self):
"""Wizards use ``except Exception`` guards — the error must be a
@@ -2507,24 +2274,6 @@ class TestSystemScopeWizardPreCheck:
assert gateway_cli._system_scope_wizard_would_need_root(system=True) is True
-class TestSystemScopeRemediationOutput:
- """Tests for _print_system_scope_remediation — the actionable guidance
- shown when the wizard detects a system-scope-only setup as non-root.
- """
-
- def test_start_remediation_mentions_sudo_systemctl_and_uninstall(self, capsys, monkeypatch):
- monkeypatch.setattr(gateway_cli, "get_service_name", lambda: "hermes-gateway")
-
- gateway_cli._print_system_scope_remediation("start")
- out = capsys.readouterr().out
-
- assert "system-wide service" in out
- assert "start requires root" in out
- assert "sudo systemctl start hermes-gateway" in out
- assert "sudo hermes gateway uninstall --system" in out
- assert "hermes gateway install" in out
-
-
class TestGatewayCommandCatchesSystemScopeError:
"""The direct CLI path (``hermes gateway start --system`` etc.) must
still exit 1 with a clean message when non-root. The top-level
@@ -2556,7 +2305,7 @@ class TestGatewayCommandCatchesSystemScopeError:
assert excinfo.value.code == 1
out = capsys.readouterr().out
# Renders the message, NOT the ``('msg', 'action')`` tuple repr
- assert "System gateway start requires root. Re-run with sudo." in out
+ assert "requires root" in out
assert "('" not in out # no tuple repr leaking through
@@ -2894,8 +2643,9 @@ class TestTimeoutStopSecCoversCronFloor:
monkeypatch,
"agent:\n restart_drain_timeout: 0\n cron_drain_timeout: 120\n",
)
- # cron floor 120 + reserve 10 + cleanup 30 = 160 > the old formula's 60.
- assert "TimeoutStopSec=160" in unit
+ expected = resolve_systemd_timeout_stop_sec(0.0, 120.0)
+ assert f"TimeoutStopSec={expected}" in unit
+ assert expected > 60 # the old drain-only formula's leash
def test_restart_drain_still_dominates_when_larger(self, tmp_path, monkeypatch):
unit = self._unit_with_config(
@@ -2903,12 +2653,9 @@ class TestTimeoutStopSecCoversCronFloor:
monkeypatch,
"agent:\n restart_drain_timeout: 60\n",
)
- # An explicit restart drain above the default cron floor (30+10=40)
- # keeps the old formula's result — no regression for
- # restart-drain-dominated installs. (Default installs differ from
- # main: restart_drain_timeout defaults to 0, so the cron floor 40+30
- # raises the leash from 60 to 70 — see the PR description.)
- assert "TimeoutStopSec=90" in unit
+ # An explicit restart drain above the default cron floor keeps the old
+ # formula's result — no regression for restart-drain-dominated installs.
+ assert "TimeoutStopSec=90" in unit # 60s drain + 30s cleanup: same as the pre-cron formula
def test_env_override_extends_the_leash(self, tmp_path, monkeypatch):
unit = self._unit_with_config(
@@ -2917,7 +2664,7 @@ class TestTimeoutStopSecCoversCronFloor:
"agent:\n restart_drain_timeout: 0\n",
env={"HERMES_CRON_DRAIN_TIMEOUT": "200"},
)
- assert "TimeoutStopSec=240" in unit
+ assert f"TimeoutStopSec={resolve_systemd_timeout_stop_sec(0.0, 200.0)}" in unit
class TestUnitAnchoredServiceIdentity:
diff --git a/tests/hermes_cli/test_gateway_task_probe.py b/tests/hermes_cli/test_gateway_task_probe.py
deleted file mode 100644
index c0cf2df56e0..00000000000
--- a/tests/hermes_cli/test_gateway_task_probe.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""The startup supervisor probe must not load the slow CIM ScheduledTasks module."""
-
-import subprocess
-import uuid
-from unittest.mock import patch
-
-import pytest
-
-from hermes_cli.gateway import _windows_scheduled_task_state
-
-
-def test_task_query_without_powershell_module_autoload():
- real_run = subprocess.run
-
- def run_without_modules(command, **kwargs):
- command = list(command)
- command[-1] = ("$ErrorActionPreference='Stop'; $PSModuleAutoLoadingPreference='None'; "
- + command[-1])
- result = real_run(command, **kwargs)
- assert result.returncode == 0, result.stderr
- return result
-
- # A random absent task exercises real COM/RPC and task-name quoting without
- # creating, stopping or changing any scheduled task on the developer's host.
- task_name = "Hermes_test_'" + uuid.uuid4().hex
- with patch("hermes_cli.gateway.subprocess.run", side_effect=run_without_modules):
- assert _windows_scheduled_task_state(task_name) == "MISSING"
diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.py
index e243875ae6c..aa525058e4c 100644
--- a/tests/hermes_cli/test_gateway_windows.py
+++ b/tests/hermes_cli/test_gateway_windows.py
@@ -245,42 +245,6 @@ class TestStableWindowsGatewayWorkingDir:
-def _arrange_startup_fallback(monkeypatch, tmp_path, running_pids):
- script_path = tmp_path / "Hermes_Gateway_alice.cmd"
- startup_entry = tmp_path / "Startup" / "Hermes_Gateway_alice.cmd"
- calls = []
-
- monkeypatch.setattr(gateway_windows, "_prompt_install_choices", lambda *args, **kwargs: (False, True))
- monkeypatch.setattr(gateway_windows, "_assert_windows", lambda: None)
- monkeypatch.setattr(gateway_windows, "get_task_name", lambda: "Hermes_Gateway_alice")
- monkeypatch.setattr(gateway_windows, "_write_task_script", lambda: script_path)
- monkeypatch.setattr(
- gateway_windows,
- "_install_scheduled_task",
- lambda task_name, script_path: (
- False,
- "schtasks /Create failed (code 1): ERROR: Access is denied.",
- ),
- )
- monkeypatch.setattr(gateway_windows, "_should_fall_back", lambda code, detail: True)
- monkeypatch.setattr(gateway_windows, "_is_running_as_admin", lambda: True)
- monkeypatch.setattr(
- gateway_windows,
- "_launch_elevated_install",
- lambda force=False, start_now=None, start_on_login=None: calls.append(("elevate", force, start_now, start_on_login)) or True,
- )
-
- def fake_install_startup_entry(path: Path) -> Path:
- calls.append(("install_startup", path))
- return startup_entry
-
- monkeypatch.setattr(gateway_windows, "_install_startup_entry", fake_install_startup_entry)
- monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda path: calls.append(("spawn", path)) or 12345)
- monkeypatch.setattr(gateway_windows, "_report_gateway_start", lambda via: calls.append(("report_start", via)))
- monkeypatch.setattr(gateway_windows, "_print_next_steps", lambda: calls.append(("next_steps", None)))
- monkeypatch.setattr(gateway, "find_gateway_pids", lambda: running_pids)
- monkeypatch.setattr(gateway, "_profile_arg", lambda: "--profile alice")
- return script_path, calls
diff --git a/tests/hermes_cli/test_gateway_wsl.py b/tests/hermes_cli/test_gateway_wsl.py
index bc10b33e52e..893e857ce49 100644
--- a/tests/hermes_cli/test_gateway_wsl.py
+++ b/tests/hermes_cli/test_gateway_wsl.py
@@ -1,8 +1,7 @@
"""Tests for WSL detection and WSL-aware gateway behavior."""
-import subprocess
from types import SimpleNamespace
-from unittest.mock import patch, MagicMock, mock_open
+from unittest.mock import patch, mock_open
import pytest
@@ -36,23 +35,6 @@ class TestIsWsl:
assert hermes_constants.is_wsl() is False
-# =============================================================================
-# _wsl_systemd_operational() in gateway
-# =============================================================================
-
-class TestWslSystemdOperational:
- """Test the WSL systemd check."""
-
- def test_running(self, monkeypatch):
- monkeypatch.setattr(
- gateway.subprocess, "run",
- lambda *a, **kw: SimpleNamespace(
- returncode=0, stdout="running\n", stderr=""
- ),
- )
- assert gateway._wsl_systemd_operational() is True
-
-
# =============================================================================
# supports_systemd_services() WSL integration
# =============================================================================
@@ -118,37 +100,7 @@ class TestGatewayCommandWSLMessages:
out = capsys.readouterr().out
assert "WSL detected" in out
- assert "systemd is not running" in out
assert "hermes gateway run" in out
- assert "tmux" in out
- @pytest.mark.linux_only
- def test_status_wsl_running_manual(self, monkeypatch, capsys):
- """hermes gateway status on WSL with manual process shows WSL note.
-
- Linux-gated for the same reason as the install case: the WSL note is
- printed only after the macOS/Windows service branches decline.
- """
- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
- monkeypatch.setattr(gateway, "is_termux", lambda: False)
- monkeypatch.setattr(gateway, "is_wsl", lambda: True)
- monkeypatch.setattr(gateway, "find_gateway_pids", lambda: [12345])
- monkeypatch.setattr(gateway, "_runtime_health_lines", lambda: [])
- # Stub out the systemd unit path check
- monkeypatch.setattr(
- gateway, "get_systemd_unit_path",
- lambda system=False: SimpleNamespace(exists=lambda: False),
- )
- monkeypatch.setattr(
- gateway, "get_launchd_plist_path",
- lambda: SimpleNamespace(exists=lambda: False),
- )
-
- args = SimpleNamespace(gateway_command="status", deep=False, system=False)
- gateway.gateway_command(args)
-
- out = capsys.readouterr().out
- assert "WSL note" in out
- assert "tmux or screen" in out
diff --git a/tests/hermes_cli/test_gemini_provider.py b/tests/hermes_cli/test_gemini_provider.py
index deb5c3876eb..0dcb9bd7178 100644
--- a/tests/hermes_cli/test_gemini_provider.py
+++ b/tests/hermes_cli/test_gemini_provider.py
@@ -3,25 +3,14 @@
import pytest
from unittest.mock import patch, MagicMock
-from hermes_cli.auth import PROVIDER_REGISTRY, resolve_provider, resolve_api_key_provider_credentials
-from hermes_cli.models import _PROVIDER_MODELS, _PROVIDER_LABELS, _PROVIDER_ALIASES, normalize_provider
+from hermes_cli.auth import resolve_provider, resolve_api_key_provider_credentials
+from hermes_cli.models import normalize_provider
from hermes_cli.model_normalize import normalize_model_for_provider, detect_vendor
-from agent.model_metadata import get_model_context_length
-from agent.models_dev import PROVIDER_TO_MODELS_DEV, list_agentic_models, _NOISE_PATTERNS
+from agent.models_dev import list_agentic_models
# ── Provider Registry ──
-class TestGeminiProviderRegistry:
- def test_gemini_in_registry(self):
- assert "gemini" in PROVIDER_REGISTRY
-
- def test_gemini_config(self):
- pconfig = PROVIDER_REGISTRY["gemini"]
- assert pconfig.id == "gemini"
- assert pconfig.name == "Google AI Studio"
- assert pconfig.auth_type == "api_key"
- assert pconfig.inference_base_url == "https://generativelanguage.googleapis.com/v1beta"
# ── Provider Aliases ──
@@ -44,10 +33,6 @@ class TestGeminiAliases:
assert resolve_provider("gemini") == "gemini"
- def test_models_py_aliases(self):
- assert _PROVIDER_ALIASES.get("google") == "gemini"
- assert _PROVIDER_ALIASES.get("google-gemini") == "gemini"
- assert _PROVIDER_ALIASES.get("google-ai-studio") == "gemini"
def test_normalize_provider(self):
assert normalize_provider("google") == "gemini"
@@ -99,13 +84,6 @@ class TestGeminiCredentials:
# ── Model Catalog ──
-class TestGeminiModelCatalog:
- def test_provider_entry_exists(self):
- """Gemini provider has a model catalog entry. Specific model names
- are data that changes with Google releases and don't belong in tests.
- """
- assert "gemini" in _PROVIDER_MODELS
- assert len(_PROVIDER_MODELS["gemini"]) >= 1
# ── Model Normalization ──
@@ -124,14 +102,6 @@ class TestGeminiModelNormalization:
# ── Context Length ──
-class TestGeminiContextLength:
- def test_gemma_4_31b_context(self):
- # Mock external API lookups to test against hardcoded defaults
- # (models.dev and OpenRouter may return different values like 262144).
- with patch("agent.models_dev.lookup_models_dev_context", return_value=None), \
- patch("agent.model_metadata.fetch_model_metadata", return_value={}):
- ctx = get_model_context_length("gemma-4-31b-it", provider="gemini")
- assert ctx == 256000
# ── Agent Init (no SyntaxError) ──
@@ -170,8 +140,6 @@ class TestGeminiAgentInit:
# ── models.dev Integration ──
class TestGeminiModelsDev:
- def test_gemini_mapped_to_google(self):
- assert PROVIDER_TO_MODELS_DEV.get("gemini") == "google"
diff --git a/tests/hermes_cli/test_gitlock_tmp_packs.py b/tests/hermes_cli/test_gitlock_tmp_packs.py
index 2cb3a0d79d5..9e0849ab3d3 100644
--- a/tests/hermes_cli/test_gitlock_tmp_packs.py
+++ b/tests/hermes_cli/test_gitlock_tmp_packs.py
@@ -100,23 +100,6 @@ def test_no_git_dir_is_a_noop(tmp_path):
assert clear_stale_tmp_packs(tmp_path) == []
-def test_never_raises_on_unlink_failure(tmp_path, monkeypatch):
- repo = _mkrepo(tmp_path)
- monkeypatch.setattr("hermes_cli.gitlock._git_proc_running", lambda: False)
- pack = repo / ".git" / "objects" / "pack"
- p = pack / "tmp_pack_stuck"
- p.write_bytes(b"x")
- _age(p, STALE_TMP_PACK_MIN_AGE_SECONDS + 60)
-
- real_unlink = Path.unlink
-
- def failing_unlink(self, *a, **k):
- if self.name == "tmp_pack_stuck":
- raise OSError(13, "Permission denied")
- return real_unlink(self, *a, **k)
-
- monkeypatch.setattr(Path, "unlink", failing_unlink)
- assert clear_stale_tmp_packs(repo) == [] # skipped, not raised
@pytest.mark.windows_only
diff --git a/tests/hermes_cli/test_global_auth_store_memo.py b/tests/hermes_cli/test_global_auth_store_memo.py
index a8f062cfce3..ffe33ff1e27 100644
--- a/tests/hermes_cli/test_global_auth_store_memo.py
+++ b/tests/hermes_cli/test_global_auth_store_memo.py
@@ -57,29 +57,6 @@ def _make_global_store(tmp_path) -> "os.PathLike[str]":
class TestLoadGlobalAuthStoreMemo:
- def test_repeated_calls_read_store_once(self, tmp_path, monkeypatch):
- """Repeated calls must not re-read/re-parse the global store."""
- global_path = _make_global_store(tmp_path)
- monkeypatch.setattr(
- auth_mod, "_global_auth_file_path", lambda: global_path
- )
- reads = {"n": 0}
- orig = auth_mod._load_auth_store
-
- def counting_load(store_path=None):
- reads["n"] += 1
- return orig(store_path)
-
- monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)
-
- first = auth_mod._load_global_auth_store()
- for _ in range(10):
- auth_mod._load_global_auth_store()
- assert reads["n"] == 1, (
- "repeated calls must be memo hits (store read once), "
- f"got {reads['n']}"
- )
- assert first.get("providers", {}).get("openai") == {"api_key": "sk-x"}
def test_mtime_change_re_reads_once(self, tmp_path, monkeypatch):
"""A store file change on disk invalidates the memo."""
diff --git a/tests/hermes_cli/test_gmi_provider.py b/tests/hermes_cli/test_gmi_provider.py
index 732dab2986d..6ac3ff0a034 100644
--- a/tests/hermes_cli/test_gmi_provider.py
+++ b/tests/hermes_cli/test_gmi_provider.py
@@ -19,10 +19,6 @@ if "dotenv" not in sys.modules:
from hermes_cli.auth import resolve_provider
from hermes_cli.config import load_config
from hermes_cli.models import (
- CANONICAL_PROVIDERS,
- _PROVIDER_LABELS,
- _PROVIDER_MODELS,
- normalize_provider,
provider_model_ids,
)
from agent.auxiliary_client import resolve_provider_client
@@ -51,9 +47,6 @@ class TestGmiAliases:
monkeypatch.setenv("GMI_API_KEY", "gmi-test-key")
assert resolve_provider(alias) == "gmi"
- def test_models_normalize_provider(self):
- assert normalize_provider("gmi-cloud") == "gmi"
- assert normalize_provider("gmicloud") == "gmi"
def test_providers_normalize_provider(self):
from hermes_cli.providers import normalize_provider as normalize_provider_in_providers
@@ -67,22 +60,15 @@ class TestGmiConfigRegistry:
from hermes_cli.config import OPTIONAL_ENV_VARS
assert "GMI_API_KEY" in OPTIONAL_ENV_VARS
- assert OPTIONAL_ENV_VARS["GMI_API_KEY"]["category"] == "provider"
assert OPTIONAL_ENV_VARS["GMI_API_KEY"]["password"] is True
- assert OPTIONAL_ENV_VARS["GMI_API_KEY"]["url"] == "https://www.gmicloud.ai/"
assert "GMI_BASE_URL" in OPTIONAL_ENV_VARS
- assert OPTIONAL_ENV_VARS["GMI_BASE_URL"]["category"] == "provider"
- assert OPTIONAL_ENV_VARS["GMI_BASE_URL"]["password"] is False
# ENV_VARS_BY_VERSION entries are not needed for providers added after
# _config_version 22 (the current baseline) — users discover GMI via
# hermes model, not via upgrade prompts.
class TestGmiModelCatalog:
- def test_canonical_provider_entry(self):
- slugs = [p.slug for p in CANONICAL_PROVIDERS]
- assert "gmi" in slugs
def test_provider_model_ids_prefers_live_api(self, monkeypatch):
monkeypatch.setattr(
@@ -108,27 +94,9 @@ class TestGmiModelCatalog:
]
-class TestGmiProvidersModule:
- def test_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
-
- assert "gmi" in HERMES_OVERLAYS
- overlay = HERMES_OVERLAYS["gmi"]
- assert overlay.transport == "openai_chat"
- assert overlay.extra_env_vars == ("GMI_API_KEY",)
- assert overlay.base_url_override == "https://api.gmi-serving.com/v1"
- assert overlay.base_url_env_var == "GMI_BASE_URL"
- assert not overlay.is_aggregator
-
- def test_provider_label(self):
- assert _PROVIDER_LABELS["gmi"] == "GMI Cloud"
class TestGmiDoctor:
- def test_provider_env_hints_include_gmi(self):
- from hermes_cli.doctor import _PROVIDER_ENV_HINTS
-
- assert "GMI_API_KEY" in _PROVIDER_ENV_HINTS
def test_run_doctor_checks_gmi_models_endpoint(self, monkeypatch, tmp_path):
from hermes_cli import doctor as doctor_mod
@@ -198,16 +166,11 @@ class TestGmiDoctor:
doctor_mod.run_doctor(Namespace(fix=False))
out = buf.getvalue()
- assert "API key or custom endpoint configured" in out
assert "GMI Cloud" in out
assert any(url == "https://api.gmi-serving.com/v1/models" for url, _, _ in calls)
class TestGmiModelMetadata:
- def test_url_to_provider(self):
- from agent.model_metadata import _URL_TO_PROVIDER
-
- assert _URL_TO_PROVIDER.get("api.gmi-serving.com") == "gmi"
def test_known_gmi_endpoint_still_uses_endpoint_metadata(self):
@@ -243,7 +206,7 @@ class TestGmiAuxiliary:
client, model = resolve_provider_client("gmi")
assert client is not None
- assert model == "google/gemini-3.1-flash-lite-preview"
+ assert model
assert mock_openai.call_args.kwargs["api_key"] == "gmi-test-key"
assert mock_openai.call_args.kwargs["base_url"] == "https://api.gmi-serving.com/v1"
# GMI profile declares default_headers with a HermesAgent User-Agent
@@ -252,16 +215,6 @@ class TestGmiAuxiliary:
headers = mock_openai.call_args.kwargs.get("default_headers", {})
assert headers.get("User-Agent", "").startswith("HermesAgent/")
- def test_gmi_profile_declares_hermes_user_agent(self):
- """The GMI plugin sets a HermesAgent/<ver> User-Agent on its profile."""
- from providers import get_provider_profile
-
- profile = get_provider_profile("gmi")
- assert profile is not None
- ua = profile.default_headers.get("User-Agent", "")
- assert ua.startswith("HermesAgent/"), (
- f"expected GMI profile User-Agent to start with 'HermesAgent/', got {ua!r}"
- )
class TestGmiMainFlow:
diff --git a/tests/hermes_cli/test_goal_gates.py b/tests/hermes_cli/test_goal_gates.py
index aa229bce6bb..ff892d0b2d6 100644
--- a/tests/hermes_cli/test_goal_gates.py
+++ b/tests/hermes_cli/test_goal_gates.py
@@ -3,7 +3,6 @@
import json
import subprocess
import sys
-import time
from unittest.mock import patch
import pytest
@@ -15,8 +14,6 @@ from hermes_cli.goals import (
GoalManager,
GoalState,
run_gate,
- save_goal,
- load_goal,
)
@@ -148,10 +145,6 @@ def test_gates_persist_and_reload():
assert reloaded.state.gates[0].command == "echo persisted"
-def test_status_line_mentions_gates():
- mgr = _mgr_with_goal("gate-status-sid")
- mgr.add_gate("echo g")
- assert "1 gate" in mgr.status_line()
# ──────────────────────────────────────────────────────────────────────
diff --git a/tests/hermes_cli/test_goal_judge_delegations.py b/tests/hermes_cli/test_goal_judge_delegations.py
index 28d38c30826..69303294d4a 100644
--- a/tests/hermes_cli/test_goal_judge_delegations.py
+++ b/tests/hermes_cli/test_goal_judge_delegations.py
@@ -25,8 +25,7 @@ def test_judge_prompt_states_active_delegations_and_a_wait_branch_for_them():
verdict, _reason, parse_failed, directive, _transport = goals.judge_goal(
"refactor everything", "Waiting on 4 workers; nothing to dispatch.", active_delegations=4)
text = str(seen["prompt"])
- assert "Active delegations: the agent has 4 delegated subagent batch(es) still running" in text
- assert "delegated subagents still running" in goals.JUDGE_SYSTEM_PROMPT
+ assert "Active delegations" in text
assert (verdict, parse_failed) == ("wait", False) and directive.get("seconds") == 900
with patch("agent.auxiliary_client.call_llm", side_effect=fake_call_llm):
diff --git a/tests/hermes_cli/test_goals.py b/tests/hermes_cli/test_goals.py
index 7fc8f790b75..9ba59b495d0 100644
--- a/tests/hermes_cli/test_goals.py
+++ b/tests/hermes_cli/test_goals.py
@@ -96,22 +96,6 @@ class TestJudgeGoal:
assert verdict == "done"
assert reason == "achieved"
- def test_judge_is_told_to_quote_errors_verbatim_and_never_infer_a_service(self):
- """A bare provider 401 in the response must not become 'the GitHub token is invalidated' in
- the block reason (#114012): the system prompt the judge actually receives carries the rule."""
- from hermes_cli import goals
-
- seen = {}
-
- def fake_call_llm(*a, **kw):
- seen["messages"] = kw.get("messages") or a
- return MagicMock(choices=[MagicMock(message=MagicMock(content='{"verdict": "blocked", "reason": "x"}'))])
-
- with patch("agent.auxiliary_client.call_llm", side_effect=fake_call_llm):
- goals.judge_goal("ship it", "HTTP 401: invalidated oauth token (code: token_revoked)")
- system_text = str(seen["messages"])
- assert "quote the error text verbatim" in system_text
- assert "Never infer one the response does not name" in system_text
# ──────────────────────────────────────────────────────────────────────
@@ -160,21 +144,8 @@ class TestGoalManager:
# ──────────────────────────────────────────────────────────────────────
-def test_goal_command_in_registry():
- from hermes_cli.commands import resolve_command
-
- cmd = resolve_command("goal")
- assert cmd is not None
- assert cmd.name == "goal"
-def test_goal_command_dispatches_in_cli_registry_helpers():
- """goal shows up in autocomplete / help categories alongside other Session cmds."""
- from hermes_cli.commands import COMMANDS, COMMANDS_BY_CATEGORY
-
- assert "/goal" in COMMANDS
- session_cmds = COMMANDS_BY_CATEGORY.get("Session", {})
- assert "/goal" in session_cmds
# ──────────────────────────────────────────────────────────────────────
@@ -209,9 +180,8 @@ class TestJudgeParseFailureAutoPause:
def test_auto_pause_after_three_consecutive_parse_failures(self, hermes_home):
"""N=3 consecutive parse failures → auto-pause with config pointer."""
from hermes_cli import goals
- from hermes_cli.goals import GoalManager, DEFAULT_MAX_CONSECUTIVE_PARSE_FAILURES
+ from hermes_cli.goals import GoalManager
- assert DEFAULT_MAX_CONSECUTIVE_PARSE_FAILURES == 3
mgr = GoalManager(session_id="parse-fail-sid-1", default_max_turns=20)
mgr.set("do a thing")
@@ -230,10 +200,6 @@ class TestJudgeParseFailureAutoPause:
assert d3["should_continue"] is False
assert d3["status"] == "paused"
assert mgr.state.consecutive_parse_failures == 3
- # Message points at the config surface so the user can fix it.
- assert "auxiliary" in d3["message"]
- assert "goal_judge" in d3["message"]
- assert "config.yaml" in d3["message"]
@@ -382,7 +348,6 @@ class TestJudgeGoalWithSubgoals:
assert "Additional criteria" in user_msg
assert "1. write tests" in user_msg
assert "2. update docs" in user_msg
- assert "every additional criterion" in user_msg
assert verdict == "done"
def test_judge_uses_original_template_when_no_subgoals(self, hermes_home):
@@ -410,16 +375,6 @@ class TestJudgeGoalWithSubgoals:
assert "ship it" in user_msg
-class TestStatusLineSubgoalCount:
-
- def test_status_line_with_subgoals(self, hermes_home):
- from hermes_cli.goals import GoalManager
- mgr = GoalManager(session_id="sl-with")
- mgr.set("ship it")
- mgr.add_subgoal("a")
- mgr.add_subgoal("b")
- line = mgr.status_line()
- assert "2 subgoals" in line
# ──────────────────────────────────────────────────────────────────────
@@ -853,7 +808,6 @@ class TestJudgeWithContract:
)
assert "completion contract" in user_msg.lower()
assert "pytest -q passes" in user_msg
- assert "concrete evidence" in user_msg
class TestDraftContract:
diff --git a/tests/hermes_cli/test_gpt56_registration.py b/tests/hermes_cli/test_gpt56_registration.py
index c3cf5a3be22..cd53c0a4746 100644
--- a/tests/hermes_cli/test_gpt56_registration.py
+++ b/tests/hermes_cli/test_gpt56_registration.py
@@ -41,7 +41,7 @@ class TestGpt56PricingRoute:
route = resolve_billing_route("gpt-5.6-sol", provider="openai")
entry = _lookup_official_docs_pricing(route)
assert entry is not None
- assert entry.input_cost_per_million == Decimal("5.00")
+ assert entry.input_cost_per_million is not None
def test_cache_write_is_1_25x_input_for_56_series(self):
diff --git a/tests/hermes_cli/test_gpt6_tiers_registration.py b/tests/hermes_cli/test_gpt6_tiers_registration.py
index bb06907f116..f502382eedd 100644
--- a/tests/hermes_cli/test_gpt6_tiers_registration.py
+++ b/tests/hermes_cli/test_gpt6_tiers_registration.py
@@ -10,7 +10,6 @@ Invariant tests only, no list snapshots. They pin what would silently regress:
gpt-5.6 effort ladder (``max`` allowed).
"""
-from decimal import Decimal
from agent.auxiliary_client import _compression_threshold_for_model
from agent.model_metadata import (
@@ -19,10 +18,8 @@ from agent.model_metadata import (
strip_codex_context_variant_suffix,
)
from agent.reasoning_effort import CODEX_GPT56_EFFORTS, codex_supported_efforts
-from agent.usage_pricing import _OFFICIAL_DOCS_PRICING
from hermes_cli.codex_models import _finalize_codex_models
from hermes_cli.model_switch import _model_sort_key
-from hermes_cli.models import OPENROUTER_MODELS, _PROVIDER_MODELS
GPT6_TIERS = ("gpt-6-sol", "gpt-6-luna") # terra: never published by OpenAI, not on OpenRouter/Codex (2026-09-22)
@@ -48,21 +45,5 @@ def test_gpt6_tiers_share_the_codex_900k_contract_with_56():
assert codex_supported_efforts(f"openai/{base}") == CODEX_GPT56_EFFORTS
-def test_gpt6_tiers_replace_56_in_aggregator_catalogs_with_pricing_aliases():
- for provider, listed in (("nous", set(_PROVIDER_MODELS["nous"])), ("openrouter", {m for m, _ in OPENROUTER_MODELS})):
- assert {f"openai/{t}" for t in GPT6_TIERS} <= listed, provider
- assert not {m for m in listed if "gpt-5.6" in m}, provider
- for base in ("gpt-6-sol", "gpt-6-luna"): # Terra has no published pricing page yet
- entry = _OFFICIAL_DOCS_PRICING[("openai", base)]
- assert entry.input_cost_per_million is not None, base
- assert entry.cache_write_cost_per_million == entry.input_cost_per_million * Decimal("1.25"), base
- for suffix in ("pro", "900k"):
- assert _OFFICIAL_DOCS_PRICING[("openai", f"{base}-{suffix}")] is entry, (base, suffix)
-def test_codex_forward_compat_only_synthesizes_published_gpt6_tiers():
- """Forward-compat synthesis puts names in the picker before the account catalog lists them, so it
- must stay within tiers OpenAI has actually published (sol, luna; astra is discovery-only). A guessed
- name such as gpt-6-terra shipped as a live picker choice once."""
- synthesized = {m for m in _finalize_codex_models(["gpt-5.5"]) if m.startswith("gpt-6-")}
- assert synthesized == {f"{base}{suffix}" for base in GPT6_TIERS for suffix in ("", "-900k")}
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index 89666abf785..68910df96ed 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -14,8 +14,6 @@ import pytest
from hermes_cli import main as cli_main
from hermes_cli import main_desktop
-from hermes_cli import main_install_repair
-from hermes_cli import main_web_build
@pytest.fixture(autouse=True)
@@ -149,8 +147,6 @@ def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):
monkeypatch.setattr(main_desktop, "_desktop_exe_integrity_error", lambda _: None)
install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)
- pack_ok = subprocess.CompletedProcess(["npm", "run", "pack"], 0)
- launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)
with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=install_ok) as mock_install, \
@@ -235,21 +231,9 @@ def test_gui_install_env_prepends_managed_node_on_bare_path(tmp_path, monkeypatc
assert "/usr/bin" in path_parts # the bare updater PATH is preserved, just after managed Node
-
-
-
-
-
-
# ── Content-hash stamp tests ──────────────────────────────────────────
-
-
-
-
-
-
# ── Electron build-cache recovery tests ───────────────────────────────
@@ -294,8 +278,6 @@ def test_purge_electron_build_cache_clears_all_zips_and_unpacked_dir(tmp_path, m
assert not unpacked.exists()
-
-
def test_gui_does_not_retry_after_packaged_executable_exists(tmp_path, monkeypatch, capsys):
"""A build that already produced a packaged executable did NOT fail from the
Electron-download problem the cache purge + mirror retries exist to repair.
@@ -334,7 +316,6 @@ def test_gui_does_not_retry_after_packaged_executable_exists(tmp_path, monkeypat
mock_purge.assert_not_called()
mock_dl.assert_not_called()
assert mock_run.call_count == 1
- assert "Desktop GUI build failed" in capsys.readouterr().out
def _make_electron_dist(root: Path) -> Path:
@@ -439,15 +420,12 @@ def test_gui_still_retries_via_mirror_when_electron_dist_is_missing(tmp_path, mo
assert not attempts[0].get("ELECTRON_MIRROR")
assert not attempts[1].get("ELECTRON_MIRROR")
assert attempts[2].get("ELECTRON_MIRROR") == main_desktop._ELECTRON_FALLBACK_MIRROR
- assert "looks blocked" in capsys.readouterr().out
# And the mirror run reached the dist re-download, mirror in hand.
assert mock_purge.called
assert any(a.kwargs.get("mirror") == main_desktop._ELECTRON_FALLBACK_MIRROR
for a in mock_dl.call_args_list)
-
-
# ── electronDist (re)download helper tests (#47266) ───────────────────
@@ -521,40 +499,6 @@ def test_electron_dist_binary_basename_macos():
)
-
-
-
-
-
-
-
-
-class _FakeProc:
- """Minimal psutil.Process stand-in for the lock-breaker tests."""
-
- def __init__(self, pid: int, exe: str | None):
- self.pid = pid
- self.info = {"pid": pid, "exe": exe}
- self.terminated = False
- self.killed = False
-
- def terminate(self):
- self.terminated = True
-
- def kill(self):
- self.killed = True
-
-
-
-
-
-
-
-
-
-
-
-
# --- macOS TCC-stable local signing (relaunch fixup) -----------------------
@@ -620,50 +564,6 @@ def test_desktop_macos_local_codesign_signs_native_binaries(tmp_path, monkeypatc
assert str(app / "Contents" / "Frameworks" / "chrome_crashpad_handler") in signed
-
-
-def test_relaunchable_fixup_falls_back_to_legacy_adhoc_on_failure(tmp_path, monkeypatch, capsys):
- """A failing stable sign must still leave a launchable (deep ad-hoc) bundle.
-
- The stable signer raising routes into the legacy deep ad-hoc fallback;
- with the fallback sign and strict verification succeeding, the fixup
- reports ``True`` per its documented contract.
-
- ``macos_only``: the subject is ``codesign`` against a real ``.app`` bundle
- layout (``exe.parents[2]``), which only the macOS packaged tree produces.
- """
- root = _make_desktop_tree(tmp_path)
- desktop_dir = root / "apps" / "desktop"
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- monkeypatch.delenv("CSC_LINK", raising=False)
- monkeypatch.delenv("APPLE_SIGNING_IDENTITY", raising=False)
- exe = _make_packaged_executable(root, monkeypatch)
- app = exe.parents[2]
-
- calls = []
-
- def fake_run(cmd, **kwargs):
- calls.append(list(cmd))
- return subprocess.CompletedProcess(cmd, 0)
-
- monkeypatch.setattr(
- cli_main.shutil, "which", lambda name: "/usr/bin/codesign" if name == "codesign" else None
- )
- monkeypatch.setattr(cli_main.subprocess, "run", fake_run)
- monkeypatch.setattr(main_desktop, "_desktop_macos_has_valid_real_signature", lambda a: False)
- monkeypatch.setattr(main_desktop, "_desktop_macos_local_signing_identity", lambda: None)
-
- def boom(*a, **kw):
- raise subprocess.CalledProcessError(1, ["codesign"])
-
- monkeypatch.setattr(main_desktop, "_desktop_macos_local_codesign", boom)
-
- assert cli_main._desktop_macos_relaunchable_fixup(desktop_dir) is True
- assert ["xattr", "-cr", str(app)] in calls
- assert ["/usr/bin/codesign", "--force", "--deep", "--sign", "-", str(app)] in calls
-
-
# --- desktop --setup-tcc-identity ------------------------------------------
@@ -671,9 +571,9 @@ def _fake_proc(cmd, returncode=0, stdout="", stderr=""):
return subprocess.CompletedProcess(cmd, returncode, stdout=stdout, stderr=stderr)
def test_setup_tcc_identity_creates_cert_imports_trusts_and_configures(tmp_path, monkeypatch, capsys):
"""Fresh identity: openssl generates, security imports + trusts, config is written."""
- monkeypatch.setattr(cli_main.sys, "platform", "darwin")
monkeypatch.setattr(
cli_main.shutil,
"which",
@@ -707,9 +607,6 @@ def test_setup_tcc_identity_creates_cert_imports_trusts_and_configures(tmp_path,
assert main_desktop._desktop_macos_setup_tcc_identity(identity) is True
- out = capsys.readouterr().out
- assert "created, imported, and trusted self-signed identity" in out
- assert "set desktop.macos_signing_identity" in out
# openssl cert generation + pkcs12 export + security import + trust all ran.
assert any(c[0] == "/usr/bin/openssl" and "req" in c for c in calls)
assert any(c[0] == "/usr/bin/openssl" and "pkcs12" in c for c in calls)
@@ -722,10 +619,10 @@ def test_setup_tcc_identity_creates_cert_imports_trusts_and_configures(tmp_path,
assert not list(tmp_path.glob("hermes-tcc-*"))
def test_setup_tcc_identity_retries_pkcs12_with_legacy_on_mac_verification_failure(tmp_path, monkeypatch, capsys):
"""OpenSSL 3: first import fails with the MAC-verification signature, the
-legacy re-export imports cleanly (the exact failure @ctaylor86 hit live)."""
- monkeypatch.setattr(cli_main.sys, "platform", "darwin")
monkeypatch.setattr(
cli_main.shutil,
"which",
@@ -772,10 +669,10 @@ def test_setup_tcc_identity_retries_pkcs12_with_legacy_on_mac_verification_failu
assert len([c for c in calls if c[0] == "/usr/bin/security" and c[1] == "import"]) == 2
def test_setup_tcc_identity_fails_when_trust_step_fails(tmp_path, monkeypatch, capsys):
"""A cert that imports but cannot be trusted for codeSign is a failure,
not a silent success."""
- monkeypatch.setattr(cli_main.sys, "platform", "darwin")
monkeypatch.setattr(
cli_main.shutil,
"which",
@@ -793,14 +690,13 @@ def test_setup_tcc_identity_fails_when_trust_step_fails(tmp_path, monkeypatch, c
monkeypatch.setattr(cli_main.subprocess, "run", fake_run)
assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is False
- assert "could not trust the certificate" in capsys.readouterr().out
def test_setup_tcc_identity_fails_when_identity_never_becomes_valid(tmp_path, monkeypatch, capsys):
"""Postcondition gate: import + trust both 'succeed' but find-identity -v
still lists nothing → report failure with guidance (the silent-success bug
from the original PR)."""
- monkeypatch.setattr(cli_main.sys, "platform", "darwin")
monkeypatch.setattr(
cli_main.shutil,
"which",
@@ -816,12 +712,11 @@ def test_setup_tcc_identity_fails_when_identity_never_becomes_valid(tmp_path, mo
monkeypatch.setattr(cli_main.subprocess, "run", fake_run)
assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is False
- assert "not a VALID code-signing identity" in capsys.readouterr().out
def test_setup_tcc_identity_skips_generation_when_already_valid(tmp_path, monkeypatch, capsys):
"""Idempotent: an existing VALID identity is reused, not regenerated."""
- monkeypatch.setattr(cli_main.sys, "platform", "darwin")
monkeypatch.setattr(
cli_main.shutil,
"which",
@@ -844,18 +739,16 @@ def test_setup_tcc_identity_skips_generation_when_already_valid(tmp_path, monkey
assert main_desktop._desktop_macos_setup_tcc_identity("Hermes Local Signing") is True
- out = capsys.readouterr().out
- assert "already valid in keychain" in out
# No openssl generation, no security import — only find-identity + config.
assert not any(c[0] == "/usr/bin/openssl" for c in calls)
assert not any(c[0] == "/usr/bin/security" and c[1] == "import" for c in calls)
def test_setup_tcc_identity_untrusted_existing_cert_is_repaired(tmp_path, monkeypatch, capsys):
"""A cert that EXISTS but is not valid (CSSMERR_TP_NOT_TRUSTED) is repaired
— regenerated/trusted — instead of being reported as already done. The
original name-in-output probe treated this state as success."""
- monkeypatch.setattr(cli_main.sys, "platform", "darwin")
monkeypatch.setattr(
cli_main.shutil,
"which",
@@ -888,14 +781,6 @@ def test_setup_tcc_identity_untrusted_existing_cert_is_repaired(tmp_path, monkey
assert any(c[0] == "/usr/bin/security" and c[1] == "add-trusted-cert" for c in calls)
-def test_setup_tcc_identity_non_macos_skips(tmp_path, monkeypatch, capsys):
- """On non-macOS the setup is a no-op failure (not a crash)."""
- monkeypatch.setattr(cli_main.sys, "platform", "linux")
-
- assert main_desktop._desktop_macos_setup_tcc_identity() is False
- assert "macOS-only" in capsys.readouterr().out
-
-
def test_cmd_gui_setup_tcc_identity_exits_before_build(tmp_path, monkeypatch):
"""`hermes desktop --setup-tcc-identity` calls the setup and exits 0/1
without building or launching the app."""
@@ -913,8 +798,6 @@ def test_cmd_gui_setup_tcc_identity_exits_before_build(tmp_path, monkeypatch):
mock_install.assert_not_called()
-
-
@pytest.mark.macos_only
def test_relaunchable_fixup_stable_identity_never_touches_keychain(tmp_path, monkeypatch):
"""A successful stable-identity re-sign must NOT delete the safeStorage item.
@@ -934,8 +817,7 @@ def test_relaunchable_fixup_stable_identity_never_touches_keychain(tmp_path, mon
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
monkeypatch.delenv("CSC_LINK", raising=False)
monkeypatch.delenv("APPLE_SIGNING_IDENTITY", raising=False)
- exe = _make_packaged_executable(root, monkeypatch)
- app = exe.parents[2]
+ _make_packaged_executable(root, monkeypatch)
calls: list[list[str]] = []
monkeypatch.setattr(main_desktop, "_desktop_macos_has_valid_real_signature", lambda a: False)
@@ -951,38 +833,6 @@ def test_relaunchable_fixup_stable_identity_never_touches_keychain(tmp_path, mon
assert not any("delete-generic-password" in c for c in calls)
-def test_relaunchable_fixup_default_noconfig_success_never_touches_keychain(tmp_path, monkeypatch):
- """Default no-config path (identity == '-') must not delete the keychain item.
-
- Witness for the default ad-hoc success path: with no
- ``desktop.macos_signing_identity`` configured, the fixup signs ad-hoc with
- identifier-pinned requirements and must leave the safeStorage item alone.
-
- ``macos_only``: the fixup no-ops on non-macOS (sys.platform guard), and
- the subject is codesign against a real ``.app`` bundle layout.
- """
- root = _make_desktop_tree(tmp_path)
- desktop_dir = root / "apps" / "desktop"
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- monkeypatch.delenv("CSC_LINK", raising=False)
- monkeypatch.delenv("APPLE_SIGNING_IDENTITY", raising=False)
- exe = _make_packaged_executable(root, monkeypatch)
- app = exe.parents[2]
-
- calls: list[list[str]] = []
- monkeypatch.setattr(main_desktop, "_desktop_macos_has_valid_real_signature", lambda a: False)
- monkeypatch.setattr(main_desktop, "_desktop_macos_local_signing_identity", lambda: None)
- monkeypatch.setattr(main_desktop, "_desktop_macos_local_codesign", lambda app, **kw: True)
- monkeypatch.setattr(
- cli_main.subprocess, "run",
- lambda cmd, **kw: calls.append(list(cmd)) or subprocess.CompletedProcess(cmd, 0),
- )
-
- assert cli_main._desktop_macos_relaunchable_fixup(desktop_dir) is True
- assert not any("delete-generic-password" in c for c in calls)
-
-
@pytest.mark.macos_only
def test_relaunchable_fixup_legacy_adhoc_failure_never_touches_keychain(tmp_path, monkeypatch):
"""A failed fallback re-sign must preserve the keychain item (no deletion).
@@ -1081,8 +931,6 @@ def test_relaunchable_fixup_legacy_adhoc_success_still_verifies_and_never_delete
# --- desktop.* launch options (config.yaml) -------------------------------
-
-
# --- Linux launcher entry registration ------------------------------------
@@ -1183,30 +1031,6 @@ def test_gui_launches_even_when_desktop_entry_install_fails(tmp_path, monkeypatc
assert launched == [str(packaged_exe)]
-def test_gui_skips_desktop_entry_off_linux(tmp_path, monkeypatch):
- root = _make_desktop_tree(tmp_path)
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- packaged_exe = _make_packaged_executable(root, monkeypatch)
-
- monkeypatch.setattr("hermes_cli.linux_desktop_entry.is_supported", lambda: False)
-
- def fail(_project_root):
- raise AssertionError("must not install a desktop entry off Linux")
-
- monkeypatch.setattr("hermes_cli.linux_desktop_entry.install_desktop_entry", fail)
-
- launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)
-
- with patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \
- patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \
- patch("hermes_cli.main.subprocess.run", return_value=launch_ok), \
- pytest.raises(SystemExit) as exc:
- cli_main.cmd_gui(_ns())
-
- assert exc.value.code == 0
-
@pytest.mark.parametrize(
"raw,expected",
[
@@ -1243,11 +1067,6 @@ def test_desktop_launch_options_normalizes_ozone_hint(raw, expected):
assert hint == expected
-def test_desktop_launch_options_ozone_hint_defaults_auto():
- with patch("hermes_cli.config.load_config", return_value={}):
- assert main_desktop._desktop_launch_options()[3] == "auto"
-
-
def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
"""COSMIC HUD: ``desktop.ozone_platform_hint: x11`` sets
``ELECTRON_OZONE_PLATFORM_HINT`` on the launched Electron process."""
@@ -1592,7 +1411,6 @@ def test_swap_staged_desktop_app_stops_live_renderer_before_rename(tmp_path):
def test_stop_desktop_processes_locking_build_posix_swap_bypasses_early_return(tmp_path, monkeypatch):
"""#109643: also_posix=True must run the scan on POSIX (the default pack-time
call stays Windows-only — the staging pack never touches the live tree)."""
- monkeypatch.setattr(main_desktop.sys, "platform", "darwin")
root = _make_desktop_tree(tmp_path)
desktop_dir = root / "apps" / "desktop"
live_exe = desktop_dir / "release" / _packaged_exe_rel()
@@ -1657,8 +1475,6 @@ def test_gui_failed_pack_leaves_previous_app_untouched(tmp_path, monkeypatch, ca
assert live_exe.read_text(encoding="utf-8") == "good build"
assert not list(desktop_dir.glob(".staging-*"))
assert not list((desktop_dir / "release").glob("*.previous"))
- out = capsys.readouterr().out
- assert "previous desktop app was left untouched" in out
def test_gui_successful_pack_swaps_new_app_into_release(tmp_path, monkeypatch):
@@ -1706,4 +1522,3 @@ def test_gui_zero_exit_pack_without_artifact_keeps_previous_app(tmp_path, monkey
assert exc.value.code == 1
assert live_exe.read_text(encoding="utf-8") == "good build"
assert not list(desktop_dir.glob(".staging-*"))
- assert "produced no launchable app" in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_gui_uninstall.py b/tests/hermes_cli/test_gui_uninstall.py
index 12a1f7956a1..224b10921ff 100644
--- a/tests/hermes_cli/test_gui_uninstall.py
+++ b/tests/hermes_cli/test_gui_uninstall.py
@@ -34,20 +34,6 @@ def _make_gui_build(hermes_home: Path) -> None:
(hermes_home / "desktop-build-stamp.json").write_text("{}")
-def _make_user_data(hermes_home: Path) -> None:
- (hermes_home / "config.yaml").write_text("x: 1\n")
- (hermes_home / ".env").write_text("KEY=secret\n")
- (hermes_home / "sessions").mkdir()
-
-
-
-
-
-
-
-
-
-
def test_gui_install_summary_shape(tmp_path, monkeypatch):
hermes_home = tmp_path / ".hermes"
_make_agent(hermes_home)
@@ -65,22 +51,8 @@ def test_gui_install_summary_shape(tmp_path, monkeypatch):
assert summary["platform"] == sys.platform
-
-
-
-
-def test_linux_discovery_includes_launcher_entry(tmp_path, monkeypatch):
- """The launcher entry that `hermes desktop` installs is removable."""
- monkeypatch.setattr(gu.sys, "platform", "linux")
- monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
-
- from hermes_cli import linux_desktop_entry as lde
-
- assert lde.desktop_entry_path() in gu.packaged_gui_app_paths()
-
-
def test_uninstall_removes_launcher_entry_and_refreshes_cache(tmp_path, monkeypatch):
- monkeypatch.setattr(gu.sys, "platform", "linux")
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
from hermes_cli import linux_desktop_entry as lde
@@ -111,21 +83,6 @@ def test_uninstall_removes_launcher_entry_and_refreshes_cache(tmp_path, monkeypa
assert (hermes_home / "hermes-agent" / "hermes_cli").is_dir()
-def test_uninstall_skips_cache_refresh_when_no_launcher_entry(tmp_path, monkeypatch):
- monkeypatch.setattr(gu.sys, "platform", "linux")
- monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
-
- from hermes_cli import linux_desktop_entry as lde
-
- refreshed: list[Path] = []
- monkeypatch.setattr(lde, "refresh_desktop_databases", lambda d: refreshed.append(d) or [])
- monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "none")
-
- gu.uninstall_gui(tmp_path / ".hermes")
-
- assert refreshed == []
-
-
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX symlink semantics")
def test_remove_path_handles_symlink(tmp_path):
target = tmp_path / "real"
@@ -138,22 +95,6 @@ def test_remove_path_handles_symlink(tmp_path):
assert target.exists()
-class _Args:
- """Minimal argparse-Namespace stand-in for run_uninstall."""
-
- def __init__(self, *, yes=False, full=False, gui=False, gui_summary=False):
- self.yes = yes
- self.full = full
- self.gui = gui
- self.gui_summary = gui_summary
-
-
-
-
-
-
-
-
def test_uninstall_args_namespace_mode_mapping():
"""_UninstallArgs maps mode → the gui/full flags run_uninstall reads."""
import hermes_cli.uninstall as uninstall
diff --git a/tests/hermes_cli/test_hatch_prompt_thread_safety.py b/tests/hermes_cli/test_hatch_prompt_thread_safety.py
index 119674ed64a..85c26636a9f 100644
--- a/tests/hermes_cli/test_hatch_prompt_thread_safety.py
+++ b/tests/hermes_cli/test_hatch_prompt_thread_safety.py
@@ -35,5 +35,3 @@ def test_bare_hatch_uses_thread_aware_prompt_not_raw_input(capsys):
CLICommandsMixin._handle_hatch_command(stand_in, "/hatch")
assert calls, "expected /hatch to route through _prompt_text_input"
- out = capsys.readouterr().out
- assert "Usage: /hatch" in out # cancelled prompt falls through to usage
diff --git a/tests/hermes_cli/test_heartbeat.py b/tests/hermes_cli/test_heartbeat.py
index 4d3496b0088..59a306001cc 100644
--- a/tests/hermes_cli/test_heartbeat.py
+++ b/tests/hermes_cli/test_heartbeat.py
@@ -90,7 +90,6 @@ def test_render_prompt_contains_instruction_and_interval():
rendered = s.render_prompt()
assert "check the deploy" in rendered
assert "10m" in rendered
- assert "Heartbeat" in rendered
# ──────────────────────────────────────────────────────────────────────
diff --git a/tests/hermes_cli/test_hooks_cli.py b/tests/hermes_cli/test_hooks_cli.py
index 470600be82d..3511e540295 100644
--- a/tests/hermes_cli/test_hooks_cli.py
+++ b/tests/hermes_cli/test_hooks_cli.py
@@ -43,10 +43,6 @@ def _run(sub_args: SimpleNamespace) -> str:
class TestHooksList:
- def test_empty_config(self, tmp_path):
- with patch("hermes_cli.config.load_config", return_value={}):
- out = _run(SimpleNamespace(hooks_action="list"))
- assert "No shell hooks or outbound webhooks configured" in out
def test_shows_configured_and_consent_status(self, tmp_path):
script = _hook_script(
diff --git a/tests/hermes_cli/test_ignore_user_config_flags.py b/tests/hermes_cli/test_ignore_user_config_flags.py
index b04a885ab6d..b604eea78fb 100644
--- a/tests/hermes_cli/test_ignore_user_config_flags.py
+++ b/tests/hermes_cli/test_ignore_user_config_flags.py
@@ -18,7 +18,6 @@ from __future__ import annotations
import os
import textwrap
-import importlib
import pytest
@@ -113,91 +112,8 @@ class TestIgnoreUserConfigEnvGate:
assert cfg["model"]["default"] == "test-vendor/ignore-user-config-sentinel"
-class TestIgnoreRulesEnvGate:
- """The constructor / env var must propagate to ``HermesCLI.ignore_rules``
- so ``AIAgent`` is built with ``skip_context_files=True`` and
- ``skip_memory=True``.
- """
-
- def test_env_var_enables_ignore_rules(self, monkeypatch):
- """Setting HERMES_IGNORE_RULES=1 flips HermesCLI.ignore_rules True."""
- monkeypatch.setenv("HERMES_IGNORE_RULES", "1")
-
- # Import HermesCLI lazily — cli.py has heavy module-init side effects
- # that we don't want to run at test collection time.
- import cli
- importlib.reload(cli)
-
- # Build only enough of HermesCLI to reach the ignore_rules assignment.
- # The full __init__ pulls in provider/auth/session DB, so we cheat:
- # create the object via object.__new__ and manually run the assignment
- # the same way the real constructor does.
- obj = object.__new__(cli.HermesCLI)
- # Replicate the exact logic from cli.py HermesCLI.__init__:
- ignore_rules = False # constructor default
- obj.ignore_rules = ignore_rules or os.environ.get("HERMES_IGNORE_RULES") == "1"
-
- assert obj.ignore_rules is True
-
-
-class TestCmdChatWiring:
- """The wiring inside ``cmd_chat()`` in ``hermes_cli/main.py`` must set
- both env vars before importing ``cli`` (which evaluates
- ``load_cli_config()`` at module import).
- """
-
- def _simulate_cmd_chat_env_setup(self, args):
- """Replicate the exact snippet from cmd_chat in main.py."""
- if getattr(args, "ignore_user_config", False):
- os.environ["HERMES_IGNORE_USER_CONFIG"] = "1"
- if getattr(args, "ignore_rules", False):
- os.environ["HERMES_IGNORE_RULES"] = "1"
- def test_both_flags_set_both_env_vars(self, monkeypatch):
- monkeypatch.delenv("HERMES_IGNORE_USER_CONFIG", raising=False)
- monkeypatch.delenv("HERMES_IGNORE_RULES", raising=False)
- class FakeArgs:
- ignore_user_config = True
- ignore_rules = True
- self._simulate_cmd_chat_env_setup(FakeArgs())
-
- assert os.environ.get("HERMES_IGNORE_USER_CONFIG") == "1"
- assert os.environ.get("HERMES_IGNORE_RULES") == "1"
-
-
- def test_flags_absent_sets_nothing(self, monkeypatch):
- monkeypatch.delenv("HERMES_IGNORE_USER_CONFIG", raising=False)
- monkeypatch.delenv("HERMES_IGNORE_RULES", raising=False)
-
- class FakeArgs:
- pass # no attributes at all — getattr fallback must handle
-
- self._simulate_cmd_chat_env_setup(FakeArgs())
-
- assert "HERMES_IGNORE_USER_CONFIG" not in os.environ
- assert "HERMES_IGNORE_RULES" not in os.environ
-
-
-class TestArgparseFlagsRegistered:
- """Verify the `chat` subparser actually exposes --ignore-user-config
- and --ignore-rules. This is the contract test for the CLI surface.
- """
- def test_flags_present_in_chat_parser(self):
- """Parse a synthetic chat invocation and check both attributes exist."""
- # Minimal argparse tree matching the real chat subparser shape for the
- # two flags under test. If someone removes the flag from main.py, this
- # test keeps passing in isolation — but the E2E test below catches it.
- import argparse
- parser = argparse.ArgumentParser(prog="hermes")
- subs = parser.add_subparsers(dest="command")
- chat = subs.add_parser("chat")
- chat.add_argument("--ignore-user-config", action="store_true", default=False)
- chat.add_argument("--ignore-rules", action="store_true", default=False)
-
- args = parser.parse_args(["chat", "--ignore-user-config", "--ignore-rules"])
- assert args.ignore_user_config is True
- assert args.ignore_rules is True
diff --git a/tests/hermes_cli/test_image_gen_picker.py b/tests/hermes_cli/test_image_gen_picker.py
index 70968d553db..147bc6f225e 100644
--- a/tests/hermes_cli/test_image_gen_picker.py
+++ b/tests/hermes_cli/test_image_gen_picker.py
@@ -57,17 +57,6 @@ def _reset_registry():
class TestPluginPickerInjection:
- def test_plugin_providers_returns_registered(self, monkeypatch):
- from hermes_cli import tools_config
-
- image_gen_registry.register_provider(_FakeProvider("myimg"))
-
- rows = tools_config._plugin_image_gen_providers()
- names = [r["name"] for r in rows]
- plugin_names = [r.get("image_gen_plugin_name") for r in rows]
-
- assert "Myimg" in names
- assert "myimg" in plugin_names
def test_visible_providers_includes_plugins_for_image_gen(self, monkeypatch):
@@ -81,14 +70,6 @@ class TestPluginPickerInjection:
assert "someimg" in plugin_names
- def test_post_setup_omitted_when_not_declared(self, monkeypatch):
- from hermes_cli import tools_config
-
- image_gen_registry.register_provider(_FakeProvider("plain_img"))
-
- rows = tools_config._plugin_image_gen_providers()
- match = next(r for r in rows if r.get("image_gen_plugin_name") == "plain_img")
- assert "post_setup" not in match
class TestPluginCatalog:
diff --git a/tests/hermes_cli/test_in_dir_msys_paths.py b/tests/hermes_cli/test_in_dir_msys_paths.py
deleted file mode 100644
index de1e3e129db..00000000000
--- a/tests/hermes_cli/test_in_dir_msys_paths.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""``--in`` accepts Git Bash / MSYS-style paths on Windows.
-
-Under Git Bash, ``hermes chat --in ~`` reaches the native CLI as
-``/c/Users/<user>`` — the shell expands ``~`` to an MSYS POSIX path and
-MSYS2's automatic argument conversion is disabled for native executables.
-The resolver must translate the MSYS/Cygwin/WSL drive-root spellings to
-native form before the isdir check, or every Git Bash invocation dies with
-"--in directory not found" (hit live by the Bot Mode agent-messaging flow,
-whose SOUL protocol tells agents to deliver with ``--in ~``).
-
-The translation itself (``_msys_to_windows_path``) has exhaustive unit
-coverage in tests/tools/test_local_env_windows_msys.py; this pins the
-``--in`` call site actually applying it.
-"""
-
-from unittest import mock
-
-from tools.environments.local import _msys_to_windows_path
-
-
-class TestInDirMsysResolution:
- def test_git_bash_tilde_expansion_translates_on_windows(self):
- # Assert the translation itself — abspath/expanduser are platform
- # functions, and this test also runs on Linux CI where posix abspath
- # would treat 'C:\\...' as relative and prepend the runner's cwd.
- with mock.patch("tools.environments.local._IS_WINDOWS", True):
- translated = _msys_to_windows_path("/c/Users/alice")
- assert translated == "C:" + chr(92) + "Users" + chr(92) + "alice"
- # ntpath (what the resolver uses on Windows) sees it as absolute.
- import ntpath
-
- assert ntpath.isabs(translated)
-
- def test_native_and_posix_forms_untouched(self):
- with mock.patch("tools.environments.local._IS_WINDOWS", True):
- assert _msys_to_windows_path("C:/Users/alice") == "C:/Users/alice"
- assert _msys_to_windows_path("~/projects") == "~/projects"
-
- def test_non_windows_never_translates(self):
- with mock.patch("tools.environments.local._IS_WINDOWS", False):
- assert _msys_to_windows_path("/c/Users/alice") == "/c/Users/alice"
-
- def test_main_call_site_uses_translation(self):
- """Guard: the --in resolution in hermes_cli.main must route through
- _msys_to_windows_path (a plain expanduser/abspath does not survive
- Git Bash). Source-level check keeps this honest without spawning
- the full CLI."""
- import inspect
-
- import hermes_cli.main as main_mod
-
- src = inspect.getsource(main_mod)
- idx = src.find('in_dir = getattr(args, "in_dir", None)')
- assert idx != -1, "--in resolution block moved; update this test"
- block = src[idx : idx + 800]
- assert "_msys_to_windows_path" in block, (
- "--in no longer translates MSYS paths; Git Bash `--in ~` will "
- "fail with '--in directory not found: /c/Users/...'"
- )
diff --git a/tests/hermes_cli/test_indicator_command.py b/tests/hermes_cli/test_indicator_command.py
index 68b2d3a9787..54189fcefb1 100644
--- a/tests/hermes_cli/test_indicator_command.py
+++ b/tests/hermes_cli/test_indicator_command.py
@@ -42,13 +42,6 @@ def _make_cli():
class TestIndicatorDispatch(unittest.TestCase):
"""The command must route to its handler — not fall through to "Unknown"."""
- def test_indicator_dispatches_to_handler(self):
- cli_obj = _make_cli()
- with patch.object(cli_obj, "_handle_indicator_command") as mock_handler:
- result = cli_obj.process_command("/indicator emoji")
-
- mock_handler.assert_called_once_with("/indicator emoji")
- self.assertTrue(result)
def test_indicator_is_not_unknown_command(self):
cli_obj = _make_cli()
@@ -126,18 +119,12 @@ class TestHandleIndicatorCommand(unittest.TestCase):
class TestIndicatorRegistry(unittest.TestCase):
- def test_indicator_in_registry(self):
- from hermes_cli.commands import COMMAND_REGISTRY
-
- names = [c.name for c in COMMAND_REGISTRY]
- self.assertIn("indicator", names)
def test_indicator_subcommands_match_handler(self):
from hermes_cli.commands import COMMAND_REGISTRY
from hermes_constants import INDICATOR_STYLES
indicator = next(c for c in COMMAND_REGISTRY if c.name == "indicator")
- self.assertEqual(indicator.category, "Configuration")
# The registered styles are what the handler accepts — single source of truth.
self.assertEqual(
set(indicator.subcommands), set(INDICATOR_STYLES)
diff --git a/tests/hermes_cli/test_init_command.py b/tests/hermes_cli/test_init_command.py
index 41c99005a36..83ea54eb9fc 100644
--- a/tests/hermes_cli/test_init_command.py
+++ b/tests/hermes_cli/test_init_command.py
@@ -7,7 +7,6 @@ it builds a guidance-laden prompt that the live agent runs as a normal turn
"""
from hermes_cli.init_command import (
- _QUALITY_BAR,
build_init_prompt,
build_init_prompt_for_cwd,
)
@@ -17,17 +16,6 @@ class TestBuildInitPrompt:
- def test_merge_not_overwrite_when_existing_file_passed(self):
- existing = "# My Project\n\nAlways run `make lint` before committing.\n"
- prompt = build_init_prompt("/tmp/proj", existing_file=existing)
- low = prompt.lower()
- # Update mode, with explicit merge-not-overwrite discipline.
- assert "UPDATE the existing AGENTS.md" in prompt
- assert "merge" in low
- assert "do not overwrite" in low or "not overwrite" in low
- assert "preserve" in low
- # And it carries the current content so the agent can merge.
- assert existing.strip() in prompt
def test_includes_extra_notes_verbatim(self):
@@ -46,7 +34,6 @@ class TestBuildInitPromptForCwd:
"# Existing\n\nRun `tox -e py311`.\n", encoding="utf-8"
)
prompt = build_init_prompt_for_cwd(cwd=str(tmp_path))
- assert "UPDATE the existing AGENTS.md" in prompt
assert "Run `tox -e py311`." in prompt
def test_passes_extra_through(self, tmp_path):
@@ -54,18 +41,4 @@ class TestBuildInitPromptForCwd:
assert "keep it short" in prompt
-class TestInitRegistryWiring:
- def test_init_is_registered_and_resolves(self):
- from hermes_cli.commands import resolve_command
-
- cmd = resolve_command("init")
- assert cmd is not None
- assert cmd.name == "init"
-
-
- def test_init_works_on_the_gateway(self):
- # /init is a both-surfaces command like /learn, not CLI-only.
- from hermes_cli.commands import GATEWAY_KNOWN_COMMANDS
-
- assert "init" in GATEWAY_KNOWN_COMMANDS
diff --git a/tests/hermes_cli/test_install_cua_driver.py b/tests/hermes_cli/test_install_cua_driver.py
index f53e8c14a5e..14ab5a8aa62 100644
--- a/tests/hermes_cli/test_install_cua_driver.py
+++ b/tests/hermes_cli/test_install_cua_driver.py
@@ -118,31 +118,6 @@ class TestInstallCuaDriverUpgrade:
# ``patch("platform.system", return_value="Darwin")`` bought nothing but a
# fake host. Dropped, and the names no longer claim macOS.
- def test_upgrade_on_unsupported_platform_is_silent_noop(self):
- """The one branch no CI runner can reach for real.
-
- ``platform.system`` is still faked here, deliberately and narrowly: we
- run Linux/macOS/Windows lanes, and every one of them is a *supported*
- platform, so the refusal path is unreachable on all three. The fake is
- sound because the function returns before touching any OS facility —
- no subprocess, no path handling, no import — so there is nothing
- underneath the branch for a real host to falsify.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config, "_print_warning") as warn, \
- patch("platform.system", return_value="FreeBSD"):
- assert tools_config.install_cua_driver(upgrade=True) is False
- warn.assert_not_called()
-
- def test_non_upgrade_on_unsupported_platform_warns(self):
- """Same narrow exception as above — see that test's docstring."""
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config, "_print_warning") as warn, \
- patch("platform.system", return_value="FreeBSD"):
- assert tools_config.install_cua_driver(upgrade=False) is False
- warn.assert_called()
def test_upgrade_with_binary_present_runs_installer(self):
from hermes_cli import tools_config_cua as tools_config
@@ -163,81 +138,6 @@ class TestInstallCuaDriverUpgrade:
kwargs = runner.call_args.kwargs
assert kwargs.get("verbose") is False
- def test_upgrade_without_binary_runs_installer(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/bin/curl" if n == "curl" else None), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=True) is True
- runner.assert_called_once()
-
- @pytest.mark.linux_only
- def test_quiet_refresh_prints_single_contextual_progress_line(self):
- """``linux_only``: reaches Popen through the POSIX download-then-exec
- branch, which this lane takes for real."""
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- with patch(
- "subprocess.run",
- return_value=MagicMock(returncode=0, stderr=""),
- ), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(
- tools_config.shutil,
- "which",
- return_value="/usr/local/bin/cua-driver",
- ), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_info") as info:
- assert tools_config._run_cua_driver_installer(
- label="Refreshing",
- verbose=False,
- ) is True
-
- info.assert_called_once_with(
- "→ Refreshing cua-driver (Computer Use)..."
- )
-
- @pytest.mark.linux_only
- def test_quiet_refresh_can_suppress_progress_line(self):
- """``linux_only``: same POSIX Popen path as the test above."""
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- with patch(
- "subprocess.run",
- return_value=MagicMock(returncode=0, stderr=""),
- ), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(
- tools_config.shutil,
- "which",
- return_value="/usr/local/bin/cua-driver",
- ), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_info") as info:
- assert tools_config._run_cua_driver_installer(
- label="Refreshing",
- verbose=False,
- show_progress=False,
- ) is True
-
- info.assert_not_called()
def test_quiet_refresh_closes_stdin_and_honors_custom_timeout(self):
"""A background refresh must neither wait on a hidden prompt nor
@@ -279,35 +179,6 @@ class TestInstallCuaDriverUpgrade:
assert popen.call_args.kwargs["stdin"] is subprocess.DEVNULL
fake_proc.communicate.assert_called_once_with(timeout=120)
- def test_upgrade_can_suppress_installer_progress(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(
- tools_config.shutil,
- "which",
- side_effect=lambda name: (
- f"/usr/local/bin/{name}"
- if name in {"cua-driver", "curl"}
- else None
- ),
- ), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch.object(
- tools_config,
- "_run_cua_driver_installer",
- return_value=True,
- ) as runner, \
- patch("subprocess.run"):
- assert tools_config.install_cua_driver(
- upgrade=True,
- show_installer_progress=False,
- ) is True
-
- assert runner.call_args.kwargs["show_progress"] is False
def test_upgrade_non_writable_install_target_skips_refresh(self):
from hermes_cli import tools_config_cua as tools_config
@@ -342,24 +213,6 @@ class TestInstallCuaDriverUpgrade:
for call in info.call_args_list
)
- @pytest.mark.macos_only
- def test_install_target_writability_is_probed_for_real_on_macos(self):
- """The ``_cua_install_target_writable`` seam the two tests above patch.
-
- ``macos_only``: ``/Applications`` is the only install target Hermes
- checks, and the probe short-circuits to True on every other platform —
- so this is the one host where the real filesystem answer means
- anything.
- """
- import os
-
- from hermes_cli import tools_config_cua as tools_config
-
- writable = tools_config._cua_install_target_writable()
- if os.path.isdir("/Applications"):
- assert writable is os.access("/Applications", os.W_OK)
- else:
- assert writable is True
def test_non_upgrade_with_binary_skips_install(self):
from hermes_cli import tools_config_cua as tools_config
@@ -538,26 +391,22 @@ class TestRequireConfirmedUpdate:
for call in info.call_args_list
)
- def test_indeterminate_check_points_at_force_path(self):
- ok, runner, info = self._install(None, require_confirmed=True)
- assert ok is True
- runner.assert_not_called()
- assert any(
- "computer-use install --upgrade" in call.args[0]
- for call in info.call_args_list
- )
def test_confirmed_update_runs_installer_bounded(self):
"""Every platform: a positively confirmed newer release runs the
installer in unattended-safe mode (background ceiling). On Windows
the actual command adds -NoAutoStart and the preflights guard the
launch (covered by their own test classes below)."""
+ from hermes_cli import tools_config_cua
+
state = {"current_version": "0.5.0", "latest_version": "0.6.0",
"update_available": True}
ok, runner, _ = self._install(state, require_confirmed=True)
assert ok is True
runner.assert_called_once()
- assert runner.call_args.kwargs["installer_timeout"] == 120
+ bounded = runner.call_args.kwargs["installer_timeout"]
+ assert bounded is not None
+ assert bounded < tools_config_cua._CUA_INSTALLER_TIMEOUT
@pytest.mark.windows_only
def test_windows_incompatible_driver_defers_interactive_repair(self):
@@ -679,140 +528,6 @@ class TestRequireConfirmedUpdate:
check.assert_not_called()
-class TestUpdateCheckTimeoutDefaults:
- """cua_driver_update_check: platform-sensitive default timeout.
-
- 8s is fine on POSIX but too tight for Windows first-spawn (Defender /
- SmartScreen scanning), and a false timeout is what used to trigger the
- full reinstall fall-through during `hermes update`.
- """
-
- def _captured_timeout(self):
- from unittest.mock import MagicMock
- from tools.computer_use import cua_backend_driver
-
- captured = {}
-
- def fake_run(cmd, **kw):
- captured["timeout"] = kw.get("timeout")
- m = MagicMock()
- m.stdout = '{"update_available": false, "current_version": "1.0"}'
- return m
-
- with patch("tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",
- return_value="/x/cua-driver"), \
- patch("tools.computer_use.cua_backend.subprocess.run",
- side_effect=fake_run):
- cua_backend_driver.cua_driver_update_check()
- return captured.get("timeout")
-
- @pytest.mark.windows_only
- def test_windows_default_is_generous(self):
- """``windows_only``: the 25s default exists because a real Windows
- first-spawn is delayed by Defender/SmartScreen scanning — a faked
- platform asserted the constant, never the host it is chosen for.
- """
- assert self._captured_timeout() == 25.0
-
- def test_posix_default_unchanged(self):
- # Unmarked: the POSIX default is what this (Linux) host already picks,
- # so no platform faking is involved.
- assert self._captured_timeout() == 8.0
-
- def test_explicit_timeout_wins(self):
- from unittest.mock import MagicMock
- from tools.computer_use import cua_backend_driver
-
- captured = {}
-
- def fake_run(cmd, **kw):
- captured["timeout"] = kw.get("timeout")
- m = MagicMock()
- m.stdout = "{}"
- return m
-
- with patch("tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",
- return_value="/x/cua-driver"), \
- patch("tools.computer_use.cua_backend.subprocess.run",
- side_effect=fake_run):
- cua_backend_driver.cua_driver_update_check(timeout=3.0)
- assert captured.get("timeout") == 3.0
-
-
-class TestArchProbeRemoval:
- """Regression tests for the deletion of `_check_cua_driver_asset_for_arch`.
-
- The old probe queried ``/releases/latest`` on trycua/cua and inspected
- asset names. That was wrong in two ways:
-
- 1. cua-driver-rs releases are marked **prerelease** on every cut, so
- ``/releases/latest`` returns the Python ``cua-agent`` / ``cua-computer``
- package instead — a release with zero binary assets. The probe then
- reported "no asset for $arch" on Linux x86_64, Windows, macOS Intel,
- Linux arm64 — every non-Apple-Silicon host.
- 2. Even with the right endpoint, it duplicated tag-resolution the upstream
- installer already does correctly via ``CUA_DRIVER_RS_BAKED_VERSION``
- (auto-baked by CD on every release).
-
- The fix: stop probing. Trust the upstream installer for fresh installs
- (it has the baked version + correct API fallback) and the
- ``cua-driver check-update --json`` MCP-binary native command for the
- upgrade path.
- """
-
- def test_probe_function_is_gone(self):
- from hermes_cli import tools_config_cua as tools_config
- assert not hasattr(tools_config, "_check_cua_driver_asset_for_arch")
- assert not hasattr(tools_config, "_latest_cua_driver_rs_release")
-
- def test_fresh_install_does_not_call_github_api(self):
- """Pre-install no longer probes the GitHub API — the upstream
- ``install.sh`` resolves the tag from its baked CUA_DRIVER_RS_BAKED_VERSION
- line. install.sh errors cleanly when the arch has no asset, so the
- probe was duplicate gatekeeping.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- # No platform fake: "does Python hit the GitHub API?" is host-agnostic,
- # and ``which`` is stubbed so the host's own fetch tool resolves.
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/bin/" + n
- if n in ("curl", "powershell") else None), \
- patch("urllib.request.urlopen") as urlopen, \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=False) is True
- runner.assert_called_once()
- urlopen.assert_not_called()
-
- def test_upgrade_with_binary_does_not_call_github_api_directly(self):
- """The upgrade path no longer hits GitHub from Python — it delegates
- to the upstream ``install.sh`` (which has the baked release tag and
- the proper API fallback). When cua-driver is already installed,
- ``cua_driver_update_check()`` (added in a separate change) further
- short-circuits the network re-install via the binary's native
- ``check-update --json`` verb.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/local/bin/" + n
- if n in ("cua-driver", "curl", "powershell") else None), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch("urllib.request.urlopen") as urlopen, \
- patch("subprocess.run"), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=True) is True
- runner.assert_called_once()
- # Probe deleted — no direct GitHub API call from Python.
- urlopen.assert_not_called()
-
-
@pytest.mark.skipif(
sys.platform == "win32",
reason="POSIX installer uses the .install.lock.d directory protocol",
@@ -879,23 +594,6 @@ class TestPosixStaleInstallLockClear:
tools_config._clear_stale_cua_install_lock() # must not raise
-class TestWindowsStaleInstallLockClearDispatch:
- @pytest.mark.windows_only
- def test_windows_branch_uses_file_lock_probe(self):
- """``windows_only``: which lock protocol applies IS the host fact under
- test — on Linux the faked platform asserted the dispatch and skipped
- the ``.install.lock.d`` directory that really exists here.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(
- tools_config, "_clear_stale_windows_cua_install_lock"
- ) as clear_windows:
- tools_config._clear_stale_cua_install_lock()
-
- clear_windows.assert_called_once_with()
-
-
# ``windows_only`` rather than ``skipif(sys.platform != "win32")``: the
# dedicated Windows CI job selects ``-m windows_only``, so a bare skipif left
# these real-CreateFileW tests running on no host at all.
@@ -1746,8 +1444,7 @@ class TestUnattendedRefreshPreflights:
bypass both preflights — a human is watching upstream's own recovery.
"""
- def _run(self, installer_timeout, lock_held=False, reachable=True,
- system="Linux"):
+ def _run(self, installer_timeout, lock_held=False, reachable=True):
from unittest.mock import MagicMock
from hermes_cli import tools_config_cua as tools_config
@@ -1756,8 +1453,7 @@ class TestUnattendedRefreshPreflights:
proc.communicate.return_value = ("ok", None)
proc.returncode = 0
- with patch("platform.system", return_value=system), \
- patch.object(tools_config, "_cua_install_lock_held",
+ with patch.object(tools_config, "_cua_install_lock_held",
return_value=lock_held) as lock_probe, \
patch.object(tools_config, "_cua_release_endpoint_reachable",
return_value=reachable) as net_probe, \
@@ -1812,20 +1508,17 @@ class TestUnattendedRefreshPreflights:
def test_windows_unattended_command_passes_noautostart(self):
"""The unattended Windows command must invoke install.ps1 with
-NoAutoStart — Register-CuaDriverAutostart is the only branch that
- self-elevates (UAC)."""
- ok, popen, _, _, _ = self._run(120, system="Windows")
- assert ok is True
- cmd = popen.call_args.args[0]
- joined = " ".join(cmd)
- assert "-NoAutoStart" in joined
- assert "scriptblock" in joined
+ self-elevates (UAC). Host-independent: the preflight takes the
+ platform as data."""
+ from hermes_cli import tools_config_cua as tools_config
- def test_windows_explicit_command_keeps_plain_oneliner(self):
- """Explicit installs keep upstream's documented `irm | iex` shape
- (autostart re-registration included — human present for UAC)."""
- ok, popen, _, _, _ = self._run(None, system="Windows")
- assert ok is True
- cmd = popen.call_args.args[0]
+ explicit_cmd, _hint, _script = tools_config._cua_installer_command(True)
+ with patch.object(tools_config, "_cua_install_lock_held", return_value=False), \
+ patch.object(tools_config, "_cua_release_endpoint_reachable",
+ return_value=True):
+ cmd = tools_config._unattended_installer_preflight(
+ explicit_cmd, is_windows=True
+ )
joined = " ".join(cmd)
- assert "-NoAutoStart" not in joined
- assert "| iex" in joined
+ assert "-NoAutoStart" in joined
+ assert "-NoAutoStart" not in " ".join(explicit_cmd)
diff --git a/tests/hermes_cli/test_interrupt_output_history_regression.py b/tests/hermes_cli/test_interrupt_output_history_regression.py
index 0f43783cd0e..f0847040bdf 100644
--- a/tests/hermes_cli/test_interrupt_output_history_regression.py
+++ b/tests/hermes_cli/test_interrupt_output_history_regression.py
@@ -61,15 +61,6 @@ class TestRecoverTerminalPreservesHistory:
"_recover_terminal_after_interrupt must NOT clear _OUTPUT_HISTORY"
)
- def test_recovery_still_calls_force_full_redraw(self, monkeypatch):
- """The recovery path still forces a redraw (original behavior preserved)."""
- cli = object.__new__(HermesCLI)
- cli._force_full_redraw = MagicMock()
-
- with patch("hermes_cli.curses_ui.flush_stdin"):
- cli._recover_terminal_after_interrupt()
-
- cli._force_full_redraw.assert_called_once()
def test_normal_scrollback_survives_interrupt_cycle(self, monkeypatch):
"""Multiple lines of scrollback survive a full interrupt → recovery cycle."""
@@ -154,133 +145,11 @@ class TestInterruptMarkerNotRecorded:
# ── _show_interrupt_marker flag logic ──────────────────────────────
-class TestShowInterruptMarkerLogic:
- """The _show_interrupt_marker flag must be set correctly.
-
- The flag is True only when: the turn was interrupted (result.interrupted),
- AND there is both a response AND a pending_message (interrupt_msg).
- """
-
- def test_marker_shown_when_interrupted_with_response_and_message(self):
- """Happy path: interrupted turn with response and pending_message."""
- result = {"interrupted": True}
- response = "Some partial response"
- pending_message = "interrupt message"
-
- _show_interrupt_marker = False
- _interrupted_this_turn = bool(result and result.get("interrupted"))
-
- if _interrupted_this_turn:
- pending_message = result.get("interrupt_message") or pending_message
- _show_interrupt_marker = bool(response and pending_message)
-
- assert _show_interrupt_marker is True
-
- def test_marker_suppressed_when_no_response(self):
- """No marker when there is no response text to interrupt."""
- result = {"interrupted": True}
- response = ""
- pending_message = "interrupt message"
-
- _show_interrupt_marker = False
- _interrupted_this_turn = bool(result and result.get("interrupted"))
-
- if _interrupted_this_turn:
- pending_message = result.get("interrupt_message") or pending_message
- _show_interrupt_marker = bool(response and pending_message)
-
- assert _show_interrupt_marker is False
-
- def test_marker_suppressed_when_no_pending_message(self):
- """No marker when there's no interrupt message text."""
- result = {"interrupted": True}
- response = "Some partial response"
- pending_message = None
-
- _show_interrupt_marker = False
- _interrupted_this_turn = bool(result and result.get("interrupted"))
-
- if _interrupted_this_turn:
- pending_message = result.get("interrupt_message") or pending_message
- _show_interrupt_marker = bool(response and pending_message)
-
- assert _show_interrupt_marker is False
-
- def test_marker_suppressed_when_not_interrupted(self):
- """No marker when the turn was not interrupted."""
- result = {"completed": True}
- response = "Full response text"
- pending_message = "interrupt message"
-
- _show_interrupt_marker = False
- _interrupted_this_turn = bool(result and result.get("interrupted"))
-
- if _interrupted_this_turn:
- pending_message = result.get("interrupt_message") or pending_message
- _show_interrupt_marker = bool(response and pending_message)
-
- assert _show_interrupt_marker is False
-
- def test_marker_shown_with_explicit_interrupt_message(self):
- """Marker shown when result provides interrupt_message."""
- result = {"interrupted": True, "interrupt_message": "User cancelled"}
- response = "Partial output"
- pending_message = "default interrupt msg"
-
- _show_interrupt_marker = False
- _interrupted_this_turn = bool(result and result.get("interrupted"))
-
- if _interrupted_this_turn:
- pending_message = result.get("interrupt_message") or pending_message
- _show_interrupt_marker = bool(response and pending_message)
-
- assert _show_interrupt_marker is True
- assert pending_message == "User cancelled"
# ── End-to-end: _show_interrupt_marker → _cprint flow ──────────────
-class TestInterruptMarkerPrintFlow:
- """End-to-end: the flag leads to a supressed _cprint of the marker."""
-
- def test_marker_printed_via_suspend_after_panel(self, monkeypatch):
- """When _show_interrupt_marker is True, the marker is cprinted.
-
- The marker text is printed inside _suspend_output_history so it
- bypasses _OUTPUT_HISTORY.
- """
- cli_mod._configure_output_history(True, 10)
- printed_lines = []
-
- monkeypatch.setattr(cli_mod, "_pt_print", lambda x: printed_lines.append(x))
- monkeypatch.setattr(cli_mod, "_PT_ANSI", lambda t: t)
-
- # Simulate the production flow
- _show_interrupt_marker = True
- if _show_interrupt_marker:
- with _suspend_output_history():
- cli_mod._cprint(
- "\n── [Interrupted — processing new message] ──"
- )
-
- # Marker was printed but NOT recorded in history
- assert printed_lines, "Marker must have been printed"
- assert "Interrupted" in printed_lines[0]
- assert list(cli_mod._OUTPUT_HISTORY) == []
-
- def test_no_marker_printed_when_flag_false(self, monkeypatch):
- """When _show_interrupt_marker is False, nothing is printed."""
- printed_lines = []
- monkeypatch.setattr(cli_mod, "_pt_print", lambda x: printed_lines.append(x))
- monkeypatch.setattr(cli_mod, "_PT_ANSI", lambda t: t)
-
- _show_interrupt_marker = False
- if _show_interrupt_marker:
- with _suspend_output_history():
- cli_mod._cprint("── [Interrupted] ──")
-
- assert printed_lines == []
# ── _replay does not replay the marker (E2E) ───────────────────────
diff --git a/tests/hermes_cli/test_inventory.py b/tests/hermes_cli/test_inventory.py
index 6726c55b3a5..ea89f2b111a 100644
--- a/tests/hermes_cli/test_inventory.py
+++ b/tests/hermes_cli/test_inventory.py
@@ -112,59 +112,8 @@ def _nous_row(model: str = "openai/gpt-5.5") -> dict:
-def test_cli_model_picker_forwards_force_refresh_to_probe_flags():
- """CLI /model picker must pass force_refresh to probe flags (#65652, #65650).
- Normal open (/model bare) skips non-current probes; /model --refresh probes
- all custom providers to freshen their model lists.
- """
- ctx = _empty_ctx()
-
- # Normal open — skip non-current probes
- force_refresh = False
- with patch(
- "hermes_cli.model_switch.list_authenticated_providers",
- return_value=[],
- ) as mock_list:
- build_models_payload(
- ctx,
- probe_custom_providers=force_refresh,
- probe_current_custom_provider=not force_refresh,
- )
- assert mock_list.call_args.kwargs["probe_custom_providers"] is False
- assert mock_list.call_args.kwargs["probe_current_custom_provider"] is True
- # Refresh open — probe everything
- force_refresh = True
- with patch(
- "hermes_cli.model_switch.list_authenticated_providers",
- return_value=[],
- ) as mock_list:
- build_models_payload(
- ctx,
- probe_custom_providers=force_refresh,
- probe_current_custom_provider=not force_refresh,
- )
- assert mock_list.call_args.kwargs["probe_custom_providers"] is True
- assert mock_list.call_args.kwargs["probe_current_custom_provider"] is False
-
-
-def test_list_authenticated_providers_force_fresh_is_keyword_only():
- """``force_fresh_nous_tier`` must be keyword-only on the public listing API.
-
- It was inserted between ``custom_providers`` and ``max_models``; making it
- keyword-only ensures no positional caller passing ``max_models`` as the 5th
- arg silently mis-binds it to the tier-refresh flag. Pin the contract so a
- future signature edit that drops the ``*`` separator is caught.
- """
- import inspect
-
- from hermes_cli.model_switch import list_authenticated_providers
-
- sig = inspect.signature(list_authenticated_providers)
- param = sig.parameters["force_fresh_nous_tier"]
- assert param.kind is inspect.Parameter.KEYWORD_ONLY
- assert param.default is False
@@ -378,7 +327,6 @@ def test_picker_hints_api_key_warning_format():
r for r in payload["providers"] if r["slug"] == "anthropic"
)
assert "ANTHROPIC_API_KEY" in anthropic["warning"]
- assert anthropic["warning"].startswith("paste ")
# ─── canonical_order ───────────────────────────────────────────────────
@@ -630,26 +578,6 @@ def test_build_models_payload_no_max_models_returns_full_list():
# ─── refresh flag (cache-bust) ─────────────────────────────────────────
-def test_build_models_payload_forwards_refresh_flag():
- """build_models_payload must forward refresh= to list_authenticated_providers.
-
- The desktop picker's "Refresh Models" control passes refresh=True; the
- flag has to reach list_authenticated_providers so the per-provider
- model-id cache gets busted. Default opens pass refresh=False.
- """
- captured: dict = {}
-
- def _capture(*args, **kwargs):
- captured["refresh"] = kwargs.get("refresh")
- return []
-
- with patch("hermes_cli.model_switch.list_authenticated_providers", side_effect=_capture):
- build_models_payload(_empty_ctx())
- assert captured["refresh"] is False
-
- with patch("hermes_cli.model_switch.list_authenticated_providers", side_effect=_capture):
- build_models_payload(_empty_ctx(), refresh=True)
- assert captured["refresh"] is True
def test_list_authenticated_providers_refresh_busts_cache():
@@ -662,26 +590,3 @@ def test_list_authenticated_providers_refresh_busts_cache():
assert clear.call_count == 0
model_switch.list_authenticated_providers(refresh=True)
assert clear.call_count == 1
-
-
-# ─── _apply_featured (one-flagship-per-lab shortlist) ──────────────────
-
-
-class _FakeInfo:
- def __init__(self, release_date: str) -> None:
- self.release_date = release_date
-
-
-def _apply_featured_with_dates(rows, dates: dict[str, str]):
- """Run _apply_featured with a deterministic models.dev stub."""
- from hermes_cli import inventory
-
- def _fake_get_model_info(provider, model):
- return _FakeInfo(dates[model]) if model in dates else None
-
- with patch("agent.models_dev.get_model_info", side_effect=_fake_get_model_info):
- inventory._apply_featured(rows)
-
-
-
-
diff --git a/tests/hermes_cli/test_iron_proxy_cli.py b/tests/hermes_cli/test_iron_proxy_cli.py
index 736f32827bd..775677d261f 100644
--- a/tests/hermes_cli/test_iron_proxy_cli.py
+++ b/tests/hermes_cli/test_iron_proxy_cli.py
@@ -11,8 +11,7 @@ from __future__ import annotations
import argparse
import os
-from pathlib import Path
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
import pytest
@@ -58,13 +57,6 @@ def _args(**overrides):
# ---------------------------------------------------------------------------
-def test_cmd_install_success_returns_0(hermes_home, monkeypatch):
- monkeypatch.setattr(ip, "install_iron_proxy", lambda **kw: hermes_home / "iron-proxy")
- monkeypatch.setattr(ip, "iron_proxy_version", lambda b: "v0.39.0-test")
- rc = proxy_cli.cmd_install(_args())
- assert rc == 0
-
-
def test_cmd_install_failure_returns_1(hermes_home, monkeypatch):
def boom(**kw):
raise RuntimeError("download failed")
@@ -78,10 +70,6 @@ def test_cmd_install_failure_returns_1(hermes_home, monkeypatch):
# ---------------------------------------------------------------------------
-
-
-
-
def test_cmd_setup_from_bitwarden_refuses_on_empty_vault(hermes_home, monkeypatch):
"""If BW returns {} (empty vault / scoped wrong / unreachable), fail
loud rather than silently writing credential_source: bitwarden."""
@@ -115,18 +103,6 @@ def test_cmd_setup_from_bitwarden_refuses_on_empty_vault(hermes_home, monkeypatc
assert rc == 1
-
-
-
-
-# ---------------------------------------------------------------------------
-# ---------------------------------------------------------------------------
-
-
-
-
-
-
def test_cmd_start_passes_bitwarden_refresh_flag_when_credential_source_is_bitwarden(
hermes_home, monkeypatch,
):
@@ -166,52 +142,11 @@ def test_cmd_start_passes_bitwarden_refresh_flag_when_credential_source_is_bitwa
assert captured.get("bitwarden_config") is not None
-
-
-
-
# ---------------------------------------------------------------------------
-# cmd_stop, cmd_status, cmd_disable, cmd_config
+# cmd_disable
# ---------------------------------------------------------------------------
-
-
-
-
-# ---------------------------------------------------------------------------
-# cmd_restart
-# ---------------------------------------------------------------------------
-
-
-
-
-
-
-def test_cmd_restart_propagates_start_failure(hermes_home, monkeypatch):
- monkeypatch.setattr(ip, "stop_proxy", lambda: True)
- monkeypatch.setattr(proxy_cli, "cmd_start", lambda args: 1)
- rc = proxy_cli.cmd_restart(_args())
- assert rc == 1
-
-
-# ---------------------------------------------------------------------------
-# _load_env_file_into_environ — setup discovers keys kept only in ~/.hermes/.env
-# ---------------------------------------------------------------------------
-
-
-
-
-
-
-def test_cmd_status_returns_0(hermes_home, monkeypatch):
- monkeypatch.setattr(ip, "get_status", lambda: ip.ProxyStatus())
- monkeypatch.setattr(ip, "load_mappings", lambda: [])
- monkeypatch.setattr(ip, "discover_uncovered_providers", lambda **kw: [])
- rc = proxy_cli.cmd_status(_args())
- assert rc == 0
-
-
def test_cmd_disable_uses_public_status_pid_not_private_read_pid(
hermes_home, monkeypatch,
):
@@ -256,39 +191,6 @@ def test_cmd_disable_uses_public_status_pid_not_private_read_pid(
assert cfg2["proxy"]["enabled"] is False
-def test_cmd_config_returns_0_when_present(hermes_home, monkeypatch):
- fake = ip.ProxyStatus()
- fake.config_path = hermes_home / "proxy.yaml"
- monkeypatch.setattr(ip, "get_status", lambda: fake)
- rc = proxy_cli.cmd_config(_args())
- assert rc == 0
-
-
-
-
-# ---------------------------------------------------------------------------
-# Argparse wiring — dest='egress_command' regression
-# ---------------------------------------------------------------------------
-
-
-def test_register_cli_uses_egress_command_dest():
- """The subparser dest must be 'egress_command' to stay disjoint from
- the inbound OAuth 'hermes proxy' subparser (dest='proxy_command').
- A future grep-and-refactor on proxy_command should not hit this
- subparser by accident."""
-
- parser = argparse.ArgumentParser(prog="hermes egress")
- proxy_cli.register_cli(parser)
- # Parse a no-op invocation and confirm the attribute name.
- args = parser.parse_args(["install"])
- assert hasattr(args, "egress_command")
- assert not hasattr(args, "proxy_command")
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# v4 round: credential_source=bitwarden with secrets.bitwarden disabled
# must NOT silently degrade to host-env secrets
@@ -316,8 +218,6 @@ def test_cmd_start_refuses_when_bitwarden_mode_but_disabled(hermes_home, monkeyp
assert rc == 1
-
-
def test_cmd_setup_audit_log_failure_is_warning_not_abort(hermes_home, monkeypatch):
"""On the pinned v0.39 the daemon never writes audit.log, so a
pre-create failure must not abort the wizard."""
diff --git a/tests/hermes_cli/test_jobs_json_utf8_bom.py b/tests/hermes_cli/test_jobs_json_utf8_bom.py
index 4efe45f6675..a3ec82c3e26 100644
--- a/tests/hermes_cli/test_jobs_json_utf8_bom.py
+++ b/tests/hermes_cli/test_jobs_json_utf8_bom.py
@@ -20,17 +20,6 @@ def test_dump_cron_summary_accepts_utf8_bom(tmp_path):
assert _cron_summary(tmp_path) == "1 active / 2 total"
-def test_dump_cron_summary_bomless_regression(tmp_path):
- from hermes_cli.dump import _cron_summary
-
- cron = tmp_path / "cron"
- cron.mkdir()
- (cron / "jobs.json").write_text(
- '{"jobs": [{"id": "j1", "enabled": true}]}',
- encoding="utf-8",
- )
-
- assert _cron_summary(tmp_path) == "1 active / 1 total"
def test_status_scheduled_jobs_accepts_utf8_bom(monkeypatch, capsys, tmp_path):
diff --git a/tests/hermes_cli/test_kanban_block_kinds.py b/tests/hermes_cli/test_kanban_block_kinds.py
index 923889b09b3..51ecafcfd9e 100644
--- a/tests/hermes_cli/test_kanban_block_kinds.py
+++ b/tests/hermes_cli/test_kanban_block_kinds.py
@@ -131,7 +131,7 @@ def test_dependency_block_with_terminal_parents_parks_then_escalates(
# `hermes kanban block <child> --kind dependency waiting on upstream`
args = argparse.Namespace(task_id=child, ids=None, reason=["waiting", "on", "upstream"], kind="dependency")
assert kanban_cli._cmd_block(args) == 0
- assert f"Blocked {child} as needs_input (no open parent to wait on): waiting on upstream" in capsys.readouterr().out
+ assert "needs_input" in capsys.readouterr().out
parked = kb.get_task(conn, child)
assert (parked.status, parked.block_kind, parked.block_recurrences) == ("blocked", "needs_input", 1)
events = kb.list_events(conn, child)
diff --git a/tests/hermes_cli/test_kanban_boards.py b/tests/hermes_cli/test_kanban_boards.py
index 92215d5cb96..38a9c71d8a3 100644
--- a/tests/hermes_cli/test_kanban_boards.py
+++ b/tests/hermes_cli/test_kanban_boards.py
@@ -177,12 +177,6 @@ class TestBoardCRUD:
assert "task_events" in tables
assert "tasks" in tables
- def test_rename_updates_metadata(self, fresh_home):
- kb.create_board("slug-immutable")
- kb.write_board_metadata("slug-immutable", name="New Display Name")
- assert kb.read_board_metadata("slug-immutable")["name"] == "New Display Name"
- # Slug must not change.
- assert kb.board_exists("slug-immutable")
# ---------------------------------------------------------------------------
@@ -310,14 +304,6 @@ def _cli(args: list[str], env_extra: dict | None = None) -> subprocess.Completed
class TestCLI:
- def test_boards_list_default_only(self, tmp_path):
- env = {"HERMES_HOME": str(tmp_path)}
- res = _cli(["boards", "list", "--json"], env_extra=env)
- assert res.returncode == 0, res.stderr
- data = json.loads(res.stdout)
- slugs = [b["slug"] for b in data]
- assert slugs == ["default"]
- assert data[0]["is_current"] is True
def test_per_board_task_isolation_via_cli(self, tmp_path):
diff --git a/tests/hermes_cli/test_kanban_cli.py b/tests/hermes_cli/test_kanban_cli.py
index d7e191c0506..be8aa5ad4fd 100644
--- a/tests/hermes_cli/test_kanban_cli.py
+++ b/tests/hermes_cli/test_kanban_cli.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import argparse
import json
-import os
import threading
from pathlib import Path
@@ -81,8 +80,8 @@ def test_kanban_show_text_renders_graph_with_open_connection(kanban_home):
output = kc.run_slash(f"show {child_id}")
- assert f"Task {child_id}: child task" in output
- assert f"parents: {parent_id}" in output
+ assert "child task" in output
+ assert parent_id in output
assert "Cannot operate on a closed database" not in output
@@ -90,11 +89,10 @@ def test_kanban_edit_updates_documented_task_fields(kanban_home):
with kbc.connect_closing() as conn:
task_id = kb.create_task(conn, title="old title", body="old body", priority=2)
- output = kc.run_slash(
+ kc.run_slash(
f"edit {task_id} --title 'new title' --body 'new body' --priority 70"
)
- assert f"Edited {task_id}" in output
with kbc.connect_closing() as conn:
task = kb.get_task(conn, task_id)
events = kb.list_events(conn, task_id)
@@ -197,7 +195,6 @@ def test_run_slash_reclaim_running_task(kanban_home):
import re
import time
import secrets
- from hermes_cli import kanban_db as kb
from hermes_cli import kanban_db_connect as kbc
out1 = kc.run_slash("create 'stuck worker task' --assignee broken-model")
diff --git a/tests/hermes_cli/test_kanban_cli_exit_status.py b/tests/hermes_cli/test_kanban_cli_exit_status.py
index 79be890e91a..70d732aeb6c 100644
--- a/tests/hermes_cli/test_kanban_cli_exit_status.py
+++ b/tests/hermes_cli/test_kanban_cli_exit_status.py
@@ -57,4 +57,4 @@ def test_delegated_child_kanban_cli_refusal_returns_nonzero_exit_status(tmp_path
)
assert refused.returncode == 1
- assert "delegate_task child contexts cannot mutate Kanban tasks via the CLI" in refused.stderr
+ assert "delegate_task" in refused.stderr
diff --git a/tests/hermes_cli/test_kanban_core_functionality.py b/tests/hermes_cli/test_kanban_core_functionality.py
index 4d314a7f728..c51dd8ea336 100644
--- a/tests/hermes_cli/test_kanban_core_functionality.py
+++ b/tests/hermes_cli/test_kanban_core_functionality.py
@@ -10,14 +10,9 @@ parity across every registered verb.
from __future__ import annotations
-import argparse
-import json
import os
-import subprocess
-import threading
import time
from pathlib import Path
-from types import SimpleNamespace
import pytest
@@ -26,7 +21,6 @@ from hermes_cli import kanban_db_connect as kbc
from hermes_cli import kanban_db_notify as kbn
from hermes_cli import kanban_db_dispatch as kbd
from hermes_cli import kanban_db_workspace as kbw
-from hermes_cli.kanban import run_slash
# ---------------------------------------------------------------------------
@@ -444,23 +438,6 @@ def test_stale_run_cannot_block_or_heartbeat_new_attempt(kanban_home, monkeypatc
-def test_relative_age_renders_coarse_buckets():
- """Freshness helper turns epoch seconds into coarse human ages, and
- degrades safely on missing / future timestamps."""
- now = 1_000_000
- assert kb._relative_age(now, now) == "just now"
- assert kb._relative_age(now - 30, now) == "just now"
- assert kb._relative_age(now - 5 * 60, now) == "5m ago"
- assert kb._relative_age(now - 18 * 3600, now) == "18h ago"
- assert kb._relative_age(now - 2 * 86400, now) == "2d ago"
- # Clock skew across machines/profiles must not claim "in the future".
- assert kb._relative_age(now + 500, now) == "just now"
- # Missing / unparseable timestamps render empty so callers can append
- # unconditionally.
- assert kb._relative_age(None, now) == ""
- # Defensive: an unparseable value (e.g. a stray string) renders empty
- # rather than raising.
- assert kb._relative_age("garbage", now) == "" # type: ignore[arg-type]
def test_migration_backfills_inflight_run_for_legacy_db(kanban_home):
@@ -653,8 +630,7 @@ def test_migration_backfill_idempotent_under_re_run(tmp_path, monkeypatch):
# Battle-test findings (May 2026: stress/ suite exposed zombie + id collision)
# -------------------------------------------------------------------------
[email protected]("linux" not in __import__("sys").platform,
- reason="zombie detection is Linux-specific")
def test_pid_alive_detects_zombie(kanban_home):
"""_pid_alive must return False for a zombie process.
@@ -951,72 +927,14 @@ def test_legacy_migration_no_legacy_columns_at_all(tmp_path):
# Gateway-embedded dispatcher: config, CLI warnings, daemon deprecation stub
# ---------------------------------------------------------------------------
-def test_config_default_dispatch_in_gateway_is_true():
- """Default config must enable gateway-embedded dispatch out of the box.
- Flipping this default to false is a user-visible behaviour change and
- should require a conscious migration."""
- from hermes_cli.config import DEFAULT_CONFIG
- kanban = DEFAULT_CONFIG.get("kanban", {})
- assert kanban.get("dispatch_in_gateway") is True, (
- "kanban.dispatch_in_gateway default should be True; got "
- f"{kanban.get('dispatch_in_gateway')!r}"
- )
- interval = kanban.get("dispatch_interval_seconds")
- assert isinstance(interval, (int, float)) and interval >= 1, (
- f"dispatch_interval_seconds must be a positive number, got {interval!r}"
- )
-def _make_create_ns(**overrides):
- """Build a Namespace suitable for kb_cli._cmd_create()."""
- ns = argparse.Namespace(
- title="x", body=None, assignee="worker",
- created_by="user", workspace="scratch", tenant=None,
- priority=0, parent=None, triage=False,
- idempotency_key=None, max_runtime=None, skills=None,
- json=False,
- )
- for k, v in overrides.items():
- setattr(ns, k, v)
- return ns
-
-
-def test_cli_daemon_help_marks_deprecated():
- """The argparse help string on `daemon` mentions deprecation so users
- scanning `--help` see the migration before running the stub."""
- import argparse as _ap
- from hermes_cli import kanban as kb_cli
- root = _ap.ArgumentParser()
- subs = root.add_subparsers()
- kb_cli.build_parser(subs)
- # Walk the subparser tree to find the daemon action.
- daemon_help = None
- for action in root._actions:
- if isinstance(action, _ap._SubParsersAction):
- for name, parser in action.choices.items():
- if name == "kanban":
- for sub_action in parser._actions:
- if isinstance(sub_action, _ap._SubParsersAction):
- for sname, _ in sub_action.choices.items():
- if sname == "daemon":
- daemon_help = sub_action._choices_actions
- break
- # _choices_actions is a list of _ChoicesPseudoAction-like objects with .help
- found_deprecation = False
- if daemon_help:
- for act in daemon_help:
- if getattr(act, "dest", "") == "daemon":
- if "DEPRECATED" in (act.help or ""):
- found_deprecation = True
- break
- assert found_deprecation, (
- "daemon subparser help should be marked DEPRECATED so users see "
- "the migration guidance in `hermes kanban --help` output"
- )
+
+
# ---------------------------------------------------------------------------
@@ -1038,7 +956,6 @@ def test_gateway_dispatcher_disables_corrupt_board_without_traceback(
import hermes_cli.config as _cfg_mod
import hermes_cli.kanban_db as _kb
from hermes_cli import kanban_db_connect as _kbc
- from hermes_cli import kanban_db_dispatch as _kbd
runner = object.__new__(GatewayRunner)
runner._running = True
@@ -1112,13 +1029,6 @@ def test_gateway_dispatcher_disables_corrupt_board_without_traceback(
assert sum("not a valid SQLite database" in msg for msg in messages) == 1
assert not any("tick failed on board" in msg for msg in messages)
assert not any(record.exc_info for record in caplog.records)
- # First tick connect (dispatch) + two probes per `_has_ready_work` call
- # (ready then review, both via _kbc.connect). The second dispatch tick
- # skips the dispatch connect because the corrupt board fingerprint is
- # disabled, but the ready/review probes still each connect. PR f55d94a1e
- # added the review-column probe alongside the existing ready-column
- # probe, bumping this from 3 → 5.
- assert calls["connect"] == 5
# ---------------------------------------------------------------------------
@@ -1337,7 +1247,6 @@ def test_protocol_violation_budget_not_consumed_by_other_failures(kanban_home):
retries, and below-budget violations must leave the unified counter
untouched (so the two budgets stay independent).
"""
- import hermes_cli.kanban_db as _kb
from hermes_cli import kanban_db_dispatch as _kbd
conn = kbc.connect()
try:
diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.py
index b0f834b281b..c13b0bcbdb2 100644
--- a/tests/hermes_cli/test_kanban_db.py
+++ b/tests/hermes_cli/test_kanban_db.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import concurrent.futures
import json
import os
import sqlite3
@@ -10,12 +9,10 @@ import subprocess
import sys
import time
import types
-import unittest.mock
from pathlib import Path
import pytest
-import hermes_state
import hermes_state_wal
from hermes_cli import kanban_db as kb
from hermes_cli import kanban_db_connect as kbc
@@ -1495,54 +1492,6 @@ def test_add_column_if_missing_is_idempotent_on_race(kanban_home):
conn.close()
-def test_migrate_add_optional_columns_tolerates_concurrent_migration(kanban_home):
- """Full _migrate_add_optional_columns must not raise when columns already
- exist (issue #21708 race window — two connections migrate concurrently)."""
- import sqlite3
-
- # Schema already in fully-migrated state (all optional columns present).
- conn = sqlite3.connect(":memory:")
- conn.row_factory = sqlite3.Row
- conn.execute(
- """
- CREATE TABLE tasks (
- id INTEGER PRIMARY KEY,
- title TEXT NOT NULL,
- status TEXT NOT NULL DEFAULT '',
- tenant TEXT,
- result TEXT,
- idempotency_key TEXT,
- branch_name TEXT,
- consecutive_failures INTEGER NOT NULL DEFAULT 0,
- worker_pid INTEGER,
- last_failure_error TEXT,
- max_runtime_seconds INTEGER,
- last_heartbeat_at INTEGER,
- current_run_id INTEGER,
- workflow_template_id TEXT,
- current_step_key TEXT,
- skills TEXT,
- max_retries INTEGER,
- session_id TEXT
- )
- """
- )
- conn.execute(
- """
- CREATE TABLE task_events (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- task_id TEXT NOT NULL DEFAULT '',
- run_id INTEGER,
- kind TEXT NOT NULL DEFAULT '',
- payload TEXT,
- created_at INTEGER NOT NULL DEFAULT 0
- )
- """
- )
-
- # Running migration on an already-migrated schema must not raise.
- kbc._migrate_add_optional_columns(conn)
- conn.close()
def test_connect_heals_reduced_tasks_schema_seeded_by_external_harness(kanban_home):
@@ -1619,23 +1568,6 @@ def test_resolve_hermes_argv_prefers_module_form_over_path_shim(monkeypatch):
assert kbd._resolve_hermes_argv() == ["/opt/hermes/bin/hermes"]
-def test_resolve_hermes_argv_falls_back_to_module_form_when_no_path_shim(monkeypatch):
- """When the shim is not on PATH, fall back to `python -m hermes_cli.main`.
-
- Pins the correct module name (NOT `hermes` — there is no top-level
- `hermes` package). Regression for #23198: the original PR shipped
- `python -m hermes` which fails with `No module named hermes` on every
- invocation.
- """
- import shutil
- import sys
- import hermes_cli.kanban_db as kb
- from hermes_cli import kanban_db_dispatch as kbd
-
- monkeypatch.delenv("HERMES_BIN", raising=False)
- monkeypatch.setattr(shutil, "which", lambda name: None)
- argv = kbd._resolve_hermes_argv()
- assert argv == [sys.executable, "-m", "hermes_cli.main"]
def test_resolve_hermes_argv_module_actually_runs():
@@ -1648,7 +1580,6 @@ def test_resolve_hermes_argv_module_actually_runs():
Run it as a real subprocess to catch that regression.
"""
import subprocess
- import hermes_cli.kanban_db as kb
from hermes_cli import kanban_db_dispatch as kbd
import shutil
import unittest.mock as mock
@@ -1662,7 +1593,6 @@ def test_resolve_hermes_argv_module_actually_runs():
f"`{' '.join(argv)} --version` failed (rc={r.returncode}); "
f"stderr={r.stderr[:200]!r}"
)
- assert "Hermes Agent" in r.stdout, f"unexpected output: {r.stdout[:200]!r}"
# ---------------------------------------------------------------------------
@@ -1680,27 +1610,6 @@ def test_resolve_hermes_argv_module_actually_runs():
# ---------------------------------------------------------------------------
-def _make_task(**overrides) -> "kb.Task":
- """Minimal Task with all required fields filled in. Override anything."""
- defaults = dict(
- id="t_age",
- title="x",
- body=None,
- assignee=None,
- status="ready",
- priority=0,
- created_by=None,
- created_at=0,
- started_at=None,
- completed_at=None,
- workspace_kind="scratch",
- workspace_path=None,
- claim_lock=None,
- claim_expires=None,
- tenant=None,
- )
- defaults.update(overrides)
- return kb.Task(**defaults)
@@ -1872,72 +1781,6 @@ def test_locked_healthy_db_does_not_classify_as_corrupt(tmp_path, monkeypatch):
# First-use tip for scratch workspaces
# ---------------------------------------------------------------------------
-def test_maybe_emit_scratch_tip_fires_once_per_install(kanban_home, caplog):
- """First scratch workspace materialization warns + emits an event.
-
- Subsequent scratch workspaces on the SAME install stay silent — the
- sentinel file under kanban_home() flips after the first emit.
- """
- import logging
-
- with kbc.connect() as conn:
- t1 = kb.create_task(conn, title="first scratch")
- t2 = kb.create_task(conn, title="second scratch")
-
- # Sentinel must not exist yet on a fresh install.
- assert not kbw._scratch_tip_shown()
-
- with caplog.at_level(logging.WARNING, logger="hermes_cli.kanban_db"):
- with kbc.connect() as conn:
- kbw._maybe_emit_scratch_tip(conn, t1, "scratch")
-
- # Sentinel is now set.
- assert kbw._scratch_tip_shown()
- assert kbw._scratch_tip_sentinel_path().exists()
-
- # Warning was logged exactly once.
- tip_records = [
- r for r in caplog.records
- if "scratch workspaces are ephemeral" in r.getMessage()
- ]
- assert len(tip_records) == 1, (
- f"Expected exactly one tip warning, got {len(tip_records)}: "
- f"{[r.getMessage() for r in tip_records]!r}"
- )
-
- # An event row was appended on the first task.
- with kbc.connect() as conn:
- events = conn.execute(
- "SELECT kind FROM task_events WHERE task_id = ? ORDER BY id",
- (t1,),
- ).fetchall()
- kinds = [e["kind"] for e in events]
- assert "tip_scratch_workspace" in kinds, (
- f"Expected tip_scratch_workspace event on first scratch task; "
- f"got {kinds!r}"
- )
-
- # Second scratch materialization on the same install stays silent.
- caplog.clear()
- with caplog.at_level(logging.WARNING, logger="hermes_cli.kanban_db"):
- with kbc.connect() as conn:
- kbw._maybe_emit_scratch_tip(conn, t2, "scratch")
- tip_records2 = [
- r for r in caplog.records
- if "scratch workspaces are ephemeral" in r.getMessage()
- ]
- assert tip_records2 == [], (
- f"Tip should not re-fire after sentinel is set; got "
- f"{[r.getMessage() for r in tip_records2]!r}"
- )
- with kbc.connect() as conn:
- events2 = conn.execute(
- "SELECT kind FROM task_events WHERE task_id = ? ORDER BY id",
- (t2,),
- ).fetchall()
- assert "tip_scratch_workspace" not in [e["kind"] for e in events2], (
- "Tip event should not be appended for subsequent scratch tasks."
- )
@@ -2079,20 +1922,6 @@ def test_write_txn_check_reads_correct_header_fields(tmp_path):
-def test_bare_connect_does_not_close_on_context_exit(tmp_path):
- """Document the leak that connect_closing exists to prevent.
-
- sqlite3.Connection's __exit__ commits/rollbacks but doesn't close.
- This is the upstream behaviour we cannot change; the regression
- guard is to make sure connect_closing() does the right thing.
- """
- db_path = tmp_path / "kanban.db"
- kb._INITIALIZED_PATHS.discard(str(db_path.resolve()))
- with kbc.connect(db_path=db_path) as conn:
- pass
- # Still usable after with-block exit (the leak).
- conn.execute("SELECT 1").fetchone()
- conn.close() # explicit close to avoid leaking THIS test
def test_archive_running_task_terminates_worker(kanban_home, monkeypatch):
diff --git a/tests/hermes_cli/test_kanban_db_init.py b/tests/hermes_cli/test_kanban_db_init.py
index 89849940112..c89b7da6ede 100644
--- a/tests/hermes_cli/test_kanban_db_init.py
+++ b/tests/hermes_cli/test_kanban_db_init.py
@@ -2,12 +2,10 @@ from __future__ import annotations
import contextlib
import sqlite3
-import threading
from pathlib import Path
from hermes_cli import kanban_db as kb
from hermes_cli import kanban_db_connect as kbc
-from hermes_cli import kanban_db_notify as kbn
def _make_legacy_db(path: Path) -> None:
@@ -125,18 +123,6 @@ def test_migration_is_idempotent(tmp_path, monkeypatch):
assert len(conn.execute("SELECT * FROM task_events").fetchall()) == 2
-def test_unseen_events_for_sub_survives_migrated_db(tmp_path, monkeypatch):
- """The crash that motivated #35096 — ``int(None)`` on a NULL cursor — is
- gone after migration; the notifier query returns an integer cursor."""
- db_path = _setup_home(tmp_path, monkeypatch)
- _make_legacy_db(db_path)
-
- with kbc.connect(db_path) as conn:
- cursor, events = kbn.unseen_events_for_sub(
- conn, task_id="task-1", platform="telegram", chat_id="123"
- )
- assert isinstance(cursor, int)
- assert isinstance(events, list)
def _default_board_db(tmp_path, monkeypatch) -> Path:
diff --git a/tests/hermes_cli/test_kanban_db_repair.py b/tests/hermes_cli/test_kanban_db_repair.py
index 9a515f63760..d659d83587a 100644
--- a/tests/hermes_cli/test_kanban_db_repair.py
+++ b/tests/hermes_cli/test_kanban_db_repair.py
@@ -93,10 +93,8 @@ def _integrity_messages(db_path: Path) -> list[str]:
# Narrow auto-repair in the connect-time guard
# ---------------------------------------------------------------------------
-def test_connect_auto_repairs_index_only_corruption(tmp_path, caplog):
+def test_connect_auto_repairs_index_only_corruption(tmp_path):
"""Index-only integrity errors are REINDEXed and connect proceeds."""
- import logging
-
db_path = tmp_path / "kanban.db"
_build_board_db(db_path)
_corrupt_index(db_path, "idx_tasks_status")
@@ -106,8 +104,7 @@ def test_connect_auto_repairs_index_only_corruption(tmp_path, caplog):
assert any(m.startswith("wrong # of entries in index") for m in messages)
assert kbc._repairable_index_names(messages) == ["idx_tasks_status"]
- with caplog.at_level(logging.WARNING, logger="hermes_cli.kanban_db"):
- conn = kbc.connect(db_path=db_path)
+ conn = kbc.connect(db_path=db_path)
try:
# DB is clean again and data survived.
row = conn.execute("PRAGMA integrity_check").fetchone()
@@ -116,7 +113,6 @@ def test_connect_auto_repairs_index_only_corruption(tmp_path, caplog):
assert "task-0" in titles and "task-11" in titles
finally:
conn.close()
- assert "auto-repaired via REINDEX" in caplog.text
# The corrupt bytes were quarantined BEFORE the repair mutated the file.
backups = list(tmp_path.glob("kanban.db.corrupt.*.bak"))
diff --git a/tests/hermes_cli/test_kanban_decompose.py b/tests/hermes_cli/test_kanban_decompose.py
index 11205a00d80..b56e9f1f44a 100644
--- a/tests/hermes_cli/test_kanban_decompose.py
+++ b/tests/hermes_cli/test_kanban_decompose.py
@@ -254,6 +254,5 @@ def test_decompose_returns_false_when_task_not_triage(kanban_home):
for p in patches:
p.stop()
assert outcome.ok is False
- assert "not in triage" in outcome.reason
diff --git a/tests/hermes_cli/test_kanban_decompose_db.py b/tests/hermes_cli/test_kanban_decompose_db.py
index d7eec08821d..e82aed36402 100644
--- a/tests/hermes_cli/test_kanban_decompose_db.py
+++ b/tests/hermes_cli/test_kanban_decompose_db.py
@@ -86,7 +86,7 @@ def test_decompose_records_audit_comment_and_event(kanban_home):
comments = kb.list_comments(conn, tid)
events = kb.list_events(conn, tid)
- assert any("Decomposed into" in (c.body or "") for c in comments)
+ assert comments
assert any(ev.kind == "decomposed" for ev in events)
diff --git a/tests/hermes_cli/test_kanban_default_assignee.py b/tests/hermes_cli/test_kanban_default_assignee.py
index a56324c026e..4d8801a3478 100644
--- a/tests/hermes_cli/test_kanban_default_assignee.py
+++ b/tests/hermes_cli/test_kanban_default_assignee.py
@@ -7,27 +7,20 @@ the task is skipped (existing behavior preserved).
from __future__ import annotations
import json
-import os
-import sys
-import tempfile
+from pathlib import Path
import pytest
@pytest.fixture()
-def isolated_kanban_home(monkeypatch):
- """Spin up a fresh HERMES_HOME with a clean kanban DB."""
- test_home = tempfile.mkdtemp(prefix="kanban_default_assignee_test_")
- monkeypatch.setenv("HERMES_HOME", test_home)
- # Force-reimport so the fresh HERMES_HOME is picked up.
- for mod in list(sys.modules.keys()):
- if mod.startswith("hermes_cli") or mod.startswith("hermes_state") or mod == "hermes_constants":
- del sys.modules[mod]
+def isolated_kanban_home(tmp_path, monkeypatch):
+ """Fresh HERMES_HOME with a clean kanban DB."""
+ test_home = tmp_path / ".hermes"
+ test_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(test_home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
from hermes_cli import kanban_db
yield kanban_db, test_home
- # Cleanup is best-effort; tempfile dir survives but pytest isolation
- # gives each test its own monkeypatched HERMES_HOME so no cross-test
- # contamination.
def _fake_spawn(*args, **kwargs):
diff --git a/tests/hermes_cli/test_kanban_diagnostics.py b/tests/hermes_cli/test_kanban_diagnostics.py
index ca1c4dede66..1eff2081681 100644
--- a/tests/hermes_cli/test_kanban_diagnostics.py
+++ b/tests/hermes_cli/test_kanban_diagnostics.py
@@ -115,23 +115,6 @@ def test_stuck_in_blocked_fires_past_threshold():
-def test_repeated_crashes_truncates_huge_tracebacks():
- """Full Python tracebacks can be tens of KB. The title stays one
- line (≤160 chars); the detail caps at 500 chars + ellipsis so the
- card doesn't explode visually."""
- huge = "Traceback (most recent call last):\n" + (" File\n" * 500)
- task = _task(status="ready")
- runs = [
- _run(outcome="crashed", run_id=1, error=huge),
- _run(outcome="crashed", run_id=2, error=huge),
- ]
- diags = kd.compute_task_diagnostics(task, [], runs)
- d = diags[0]
- # Title only the first line, capped.
- assert "\n" not in d.title
- assert len(d.title) < 250
- # Detail contains the snippet with ellipsis.
- assert d.detail.endswith("…") or len(d.detail) < 700
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_kanban_dispatch_tick_hook.py b/tests/hermes_cli/test_kanban_dispatch_tick_hook.py
index d02e101ea27..f8340c5cba2 100644
--- a/tests/hermes_cli/test_kanban_dispatch_tick_hook.py
+++ b/tests/hermes_cli/test_kanban_dispatch_tick_hook.py
@@ -19,7 +19,7 @@ import pytest
from hermes_cli import kanban_db as kb
from hermes_cli import kanban_db_connect as kbc
from hermes_cli import kanban_db_dispatch as kbd
-from hermes_cli.plugins import VALID_HOOKS, get_plugin_manager
+from hermes_cli.plugins import get_plugin_manager
@pytest.fixture
@@ -110,21 +110,3 @@ def test_misbehaving_subscriber_does_not_break_dispatcher(kanban_home):
mgr._hooks = saved
-def test_no_subscriber_short_circuits_tick_hook(kanban_home, monkeypatch):
- """With nothing registered, the tick observer is never invoked."""
- from hermes_cli import lifecycle
-
- invoked: list[str] = []
- real_invoke = lifecycle.invoke_hook
-
- def _spy(hook_name, **kw):
- invoked.append(hook_name)
- return real_invoke(hook_name, **kw)
-
- monkeypatch.setattr(lifecycle, "invoke_hook", _spy)
- conn = kbc.connect()
- try:
- kbd.dispatch_once(conn, spawn_fn=lambda *a, **k: 1)
- finally:
- conn.close()
- assert "on_kanban_dispatch_tick" not in invoked
diff --git a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
index e6088ea2ecb..5bc28c5e0cc 100644
--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
@@ -201,18 +201,19 @@ def test_real_user_systemd_scope_preserves_worker_context(
receipt = workspace / "worker-receipt.json"
script = (
"import json, os, pathlib, sys, time; "
- "pathlib.Path(sys.argv[1]).write_text(json.dumps({"
+ "p = pathlib.Path(sys.argv[1]); t = p.with_suffix('.tmp'); "
+ "t.write_text(json.dumps({"
"'pid': os.getpid(), 'cwd': os.getcwd(), "
"'task': os.environ.get('HERMES_KANBAN_TASK'), "
"'run': os.environ.get('HERMES_KANBAN_RUN_ID'), "
- "'cgroup': pathlib.Path('/proc/self/cgroup').read_text()})); time.sleep(0.5)"
+ "'cgroup': pathlib.Path('/proc/self/cgroup').read_text()})); os.replace(t, p); time.sleep(0.5)"
)
monkeypatch.setattr(kbd, "_resolve_hermes_argv", lambda: [sys.executable, "-c", script, str(receipt)])
monkeypatch.setenv("INVOCATION_ID", "managed-gateway-test")
monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
pid = kbd._default_spawn(task, str(workspace))
- deadline = time.monotonic() + 5
+ deadline = time.monotonic() + 15
while not receipt.exists() and time.monotonic() < deadline:
time.sleep(0.05)
diff --git a/tests/hermes_cli/test_kanban_gc_retention.py b/tests/hermes_cli/test_kanban_gc_retention.py
index e18edc6dc25..1e0886e93a1 100644
--- a/tests/hermes_cli/test_kanban_gc_retention.py
+++ b/tests/hermes_cli/test_kanban_gc_retention.py
@@ -121,12 +121,3 @@ def test_slash_kanban_gc_retention_bounds(board, days, expected):
assert log.exists()
-def test_gc_parser_rejects_negative_retention_days():
- """``hermes kanban gc --event-retention-days -1`` is a usage error before
- ``_cmd_gc`` runs; ``0`` still parses (the CLI treats it as 'disabled')."""
- from hermes_cli.kanban_parser import _nonnegative_int
- assert _nonnegative_int("0") == 0
- with pytest.raises(argparse.ArgumentTypeError, match=">= 0"):
- _nonnegative_int("-1")
- with pytest.raises(argparse.ArgumentTypeError, match="integer"):
- _nonnegative_int("thirty")
diff --git a/tests/hermes_cli/test_kanban_goal_mode.py b/tests/hermes_cli/test_kanban_goal_mode.py
index a77e3c7c33e..850243da952 100644
--- a/tests/hermes_cli/test_kanban_goal_mode.py
+++ b/tests/hermes_cli/test_kanban_goal_mode.py
@@ -208,20 +208,16 @@ class TestCLIJudgeGate:
assert rc == 0
assert complete_calls == ["t1"]
- def test_judge_blocked_verdict_rejects_completion(self, monkeypatch, capsys):
+ def test_judge_blocked_verdict_rejects_completion(self, monkeypatch):
"""#100954: an unachievable goal must not complete silently.
The judge's ``blocked`` verdict is a refusal, not a completion —
- ``complete_task`` must never run and stderr must steer the user
- toward re-scoping / recording the block.
+ ``complete_task`` must never run.
"""
rc, complete_calls = self._run(
monkeypatch,
verdict="blocked",
reason="the target repository does not exist",
)
- err = capsys.readouterr().err
assert rc != 0, "blocked verdict must reject the completion"
assert complete_calls == [], "an unachievable goal must never reach complete_task"
- assert "unachievable" in err.lower()
- assert "kanban block" in err.lower()
diff --git a/tests/hermes_cli/test_kanban_goal_mode_worker_log.py b/tests/hermes_cli/test_kanban_goal_mode_worker_log.py
index 11559574ee1..7772225c152 100644
--- a/tests/hermes_cli/test_kanban_goal_mode_worker_log.py
+++ b/tests/hermes_cli/test_kanban_goal_mode_worker_log.py
@@ -8,10 +8,7 @@ The loop now also runs on the ``-q`` path, driving follow-up turns through ``cli
from __future__ import annotations
-from types import SimpleNamespace
-import cli
-from hermes_cli import goals
from hermes_cli import kanban_db_dispatch as dispatch
from hermes_cli.kanban_db import Task
@@ -38,54 +35,3 @@ def test_goal_mode_worker_takes_the_same_stdout_rich_path_as_a_one_shot_worker(m
assert "-Q" not in goal
-def test_non_quiet_one_shot_runs_the_goal_loop_through_cli_chat(monkeypatch):
- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_goal1")
- monkeypatch.setenv("HERMES_KANBAN_GOAL_MODE", "1")
- monkeypatch.setattr(cli, "_should_seed_interactive", lambda *a, **k: False)
- monkeypatch.setattr(cli, "_collect_query_images", lambda q, i: (q, []))
- monkeypatch.setattr(cli, "_collect_kanban_task_images", lambda imgs: [])
- monkeypatch.setattr(cli, "_finalize_single_query", lambda c: None)
-
- class _Conn:
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- monkeypatch.setattr("hermes_cli.kanban_db_connect.connect_closing", lambda: _Conn())
- monkeypatch.setattr("hermes_cli.kanban_db.get_task", lambda conn, tid: _task(goal_mode=True))
-
- def _fake_loop(*, run_turn, first_response, log, **_kw):
- # One continuation turn: it must go through cli.chat (tool feed on stdout), and the
- # verdict line must reach stdout too, not only agent.log.
- assert first_response == "first answer"
- assert run_turn("keep going") == "second answer"
- log("kanban goal loop: turn 1/20 verdict=continue reason=x")
- return {"turns": 1}
-
- monkeypatch.setattr(goals, "run_kanban_goal_loop", _fake_loop)
-
- chats: list[str] = []
-
- def _chat(message, images=None):
- chats.append(message)
- return "first answer" if len(chats) == 1 else "second answer"
-
- stub = SimpleNamespace(
- _single_query_mode=False,
- _claim_active_session=lambda *a, **k: True,
- console=SimpleNamespace(print=lambda *a, **k: None),
- _show_security_advisories=lambda: None,
- chat=_chat,
- _print_exit_summary=lambda **k: None,
- _last_turn_result={"final_response": "second answer", "completed": True},
- )
- printed: list[str] = []
- monkeypatch.setattr("builtins.print", lambda *a, **k: printed.append(" ".join(str(x) for x in a)))
- try:
- cli._run_single_query_mode(stub, "work kanban task t_goal1", None, False, True)
- except SystemExit as exc:
- assert exc.code == 0
- assert chats == ["work kanban task t_goal1", "keep going"]
- assert any("verdict=continue" in line for line in printed)
diff --git a/tests/hermes_cli/test_kanban_host_cap.py b/tests/hermes_cli/test_kanban_host_cap.py
index db08fef241a..b311a2d6591 100644
--- a/tests/hermes_cli/test_kanban_host_cap.py
+++ b/tests/hermes_cli/test_kanban_host_cap.py
@@ -85,27 +85,6 @@ def test_run_daemon_resolves_and_passes_max_in_progress(
assert captured.get("max_in_progress") == 3
-def test_run_daemon_explicit_config_wins(kanban_home, monkeypatch):
- captured: dict = {}
- stop = threading.Event()
-
- def fake_dispatch_once(conn, **kwargs):
- captured.update(kwargs)
- return kb.DispatchResult()
-
- monkeypatch.setattr(kbd, "dispatch_once", fake_dispatch_once)
- monkeypatch.setattr(kbd, "configured_max_in_progress", lambda: 7)
- monkeypatch.setattr(
- kbd, "derive_default_max_in_progress",
- lambda sample=None: pytest.fail("derived default must not be consulted"),
- )
-
- def on_tick(res):
- stop.set()
-
- kbd.run_daemon(interval=0.01, stop_event=stop, on_tick=on_tick)
-
- assert captured.get("max_in_progress") == 7
def test_configured_max_in_progress_parsing(monkeypatch):
diff --git a/tests/hermes_cli/test_kanban_memory_guard.py b/tests/hermes_cli/test_kanban_memory_guard.py
index 7ced3ec927e..9387a02fe87 100644
--- a/tests/hermes_cli/test_kanban_memory_guard.py
+++ b/tests/hermes_cli/test_kanban_memory_guard.py
@@ -52,11 +52,6 @@ def test_derived_cap_small_vm_floors_at_two():
assert kbd.derive_default_max_in_progress({"mem_total_kib": GIB // 4}) == 2
-def test_derived_cap_scales_with_memory_and_ceilings():
- assert kbd.derive_default_max_in_progress({"mem_total_kib": 2 * GIB}) == 4
- assert kbd.derive_default_max_in_progress({"mem_total_kib": 4 * GIB}) == 8
- # Big iron clamps at the ceiling — explicit config is the escape hatch.
- assert kbd.derive_default_max_in_progress({"mem_total_kib": 64 * GIB}) == 8
def test_derived_cap_fails_open_without_memtotal():
@@ -93,18 +88,8 @@ def test_resolve_max_in_progress_unset_and_unknown_memory_is_uncapped(monkeypatc
# ---------------------------------------------------------------------------
-def test_pressure_level_unknown_on_empty_sample(monkeypatch):
- monkeypatch.setattr(kbd, "_system_memory_sample", lambda: {})
- assert kbd._memory_pressure_level() == "unknown"
-def test_pressure_level_classifies_via_gateway_thresholds():
- ok = {"mem_available_kib": GIB // 2, "mem_total_kib": 1 * GIB}
- critical = {"mem_available_kib": 32 * 1024, "mem_total_kib": 1 * GIB}
- elevated = {"mem_available_kib": 100 * 1024, "mem_total_kib": 1 * GIB}
- assert kbd._memory_pressure_level(ok) == "ok"
- assert kbd._memory_pressure_level(critical) == "critical"
- assert kbd._memory_pressure_level(elevated) == "elevated"
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_kanban_notify.py b/tests/hermes_cli/test_kanban_notify.py
index fca3ff72df1..eb278ca6d96 100644
--- a/tests/hermes_cli/test_kanban_notify.py
+++ b/tests/hermes_cli/test_kanban_notify.py
@@ -29,15 +29,6 @@ def kanban_home(tmp_path, monkeypatch):
return home
-def _assert_inherited_notify_sub(subs: list[dict]) -> None:
- assert len(subs) == 1
- assert subs[0]["platform"] == "telegram"
- assert subs[0]["chat_id"] == "chat1"
- assert subs[0]["thread_id"] == "topic1"
- assert subs[0]["user_id"] == "user1"
- assert subs[0]["notifier_profile"] == "default"
-
-
def test_notify_sub_delivery_mode_persists_and_last_write_wins(kanban_home):
"""delivery_mode persists; an explicit re-subscribe is last-write-wins, a
``None`` re-subscribe leaves the existing mode untouched, an unknown value
@@ -113,37 +104,6 @@ def test_notify_subscribe_cli_records_discord_multiplex_anchors(kanban_home):
}
-def test_child_task_inherits_parent_delivery_mode(kanban_home):
- """Graph children inherit the parent's ACK edge AND its delivery_mode."""
- import hermes_cli.kanban_db as kb
- from hermes_cli import kanban_db_connect as kbc
- from hermes_cli import kanban_db_notify as kbn
-
- conn = kbc.connect()
- try:
- parent = kb.create_task(conn, title="root", assignee=None)
- kbn.add_notify_sub(
- conn, task_id=parent, platform="telegram", chat_id="chat1",
- thread_id="42", user_id="u1", user_id_alt="alt-u1", notifier_profile="default",
- delivery_mode="notify+wake",
- )
- child = kb.create_task(
- conn, title="review child", assignee="ccreviewer", parents=[parent],
- )
- subs = kbn.list_notify_subs(conn, child)
- finally:
- conn.close()
-
- assert len(subs) == 1
- assert subs[0]["platform"] == "telegram"
- assert subs[0]["chat_id"] == "chat1"
- assert subs[0]["thread_id"] == "42"
- assert subs[0]["user_id"] == "u1"
- assert subs[0]["user_id_alt"] == "alt-u1"
- assert subs[0]["notifier_profile"] == "default"
- assert subs[0]["delivery_mode"] == "notify+wake"
-
-
def test_notify_sub_chat_type_persists_and_last_write_wins(kanban_home):
"""chat_type persists, defaults to 'dm', an explicit re-subscribe is
last-write-wins, and a None re-subscribe leaves it untouched. The
@@ -233,36 +193,6 @@ def test_notify_sub_user_id_alt_persists_and_backfills_legacy_rows(kanban_home):
assert subs[0]["user_id_alt"] == "union-id"
-def test_child_task_inherits_parent_chat_type(kanban_home):
- """Graph children inherit the parent's chat_type alongside its ACK edge and
- delivery_mode, so a woken child notification keys to the same session as
- the parent's originating channel."""
- import hermes_cli.kanban_db as kb
- from hermes_cli import kanban_db_connect as kbc
- from hermes_cli import kanban_db_notify as kbn
-
- conn = kbc.connect()
- try:
- parent = kb.create_task(conn, title="root", assignee=None)
- kbn.add_notify_sub(
- conn, task_id=parent, platform="telegram", chat_id="chat1",
- user_id="u1", user_id_alt="alt-u1", chat_type="group",
- delivery_mode="notify+wake",
- )
- child = kb.create_task(
- conn, title="impl child", assignee="coder", parents=[parent],
- )
- subs = kbn.list_notify_subs(conn, child)
- finally:
- conn.close()
-
- assert len(subs) == 1
- assert subs[0]["chat_type"] == "group"
- assert subs[0]["delivery_mode"] == "notify+wake"
- assert subs[0]["user_id"] == "u1"
- assert subs[0]["user_id_alt"] == "alt-u1"
-
-
@pytest.mark.asyncio
async def test_notifier_notify_plus_wake_sends_and_wakes(kanban_home):
"""notify+wake delivers the passive message AND wakes the agent; a plain
@@ -613,9 +543,6 @@ async def test_notifier_unsubs_after_abnormal_events(kind, kanban_home):
fake_adapter.send.assert_called_once()
sent = fake_adapter.send.call_args[0][1]
assert tid in sent
- # Plain-language outcome per event kind (no internal event names).
- expected = {"crashed": "stopped unexpectedly", "gave_up": "blocked", "timed_out": "time limit"}[kind]
- assert expected in sent
# ...but the subscription survives so a respawn-then-same-event cycle
# reaches the user too. The cursor (last_event_id) advanced inside
@@ -636,34 +563,6 @@ async def test_notifier_unsubs_after_abnormal_events(kind, kanban_home):
)
-
-
-
-
-
-
-
-# ---------------------------------------------------------------------------
-# Regression: gateway watchers must not double-init the kanban DB.
-#
-# Both the notifier watcher (`_kanban_notifier_watcher`) and the dispatcher
-# tick (`_tick_once_for_board`) used to call `_kb.connect(board=slug)`
-# immediately followed by `_kb.init_db(board=slug)`. Since `connect()`
-# already runs the schema + idempotent migration on first open per process,
-# the explicit `init_db()` was redundant — and worse, `init_db()`
-# deliberately busts the per-process cache and re-runs the migration on a
-# *second* connection, which races the first. On legacy DBs this surfaced
-# as `duplicate column name: <col>` (now tolerated by
-# `_add_column_if_missing`) and intermittent `database is locked` errors
-# (issue #21378).
-#
-# The fix removes the `init_db()` calls in both watchers; this regression
-# test pins that behaviour so we don't reintroduce them.
-# ---------------------------------------------------------------------------
-
-
-
-
@pytest.mark.asyncio
async def test_notifier_wakes_origin_for_review_and_keeps_subscription(kanban_home):
from gateway.config import Platform
@@ -716,7 +615,6 @@ async def test_notifier_wakes_origin_for_review_and_keeps_subscription(kanban_ho
timeout=10.0,
)
- assert any("ready for review" in message for message in delivered)
assert any("Implementation and tests ready" in message for message in delivered)
with kbc.connect() as conn:
assert kbn.list_notify_subs(conn), "review is non-final; subscription must survive"
@@ -1314,22 +1212,3 @@ def test_gc_purges_blocked_task_that_never_done(kanban_home):
conn.close()
-def test_gc_archived_rows_already_removed_by_unsub(kanban_home):
- import hermes_cli.kanban_db as kb
- from hermes_cli import kanban_db_connect as kbc
- from hermes_cli import kanban_db_notify as kbn
-
- conn = kbc.connect()
- try:
- tid = _make_done_task_with_sub(kb, conn, title="archived", chat_id="c-arch")
- assert kb.archive_task(conn, tid)
- # The notifier removes the sub at archive time; the GC targets only
- # ``done`` tasks, so an archived task contributes nothing to purge.
- kbn.remove_notify_sub(
- conn, task_id=tid, platform="telegram", chat_id="c-arch",
- )
- _backdate_task(kb, conn, tid, days=365)
- assert kbn.purge_stale_done_notify_subs(conn, max_age_days=30) == 0
- assert kbn.list_notify_subs(conn, tid) == []
- finally:
- conn.close()
diff --git a/tests/hermes_cli/test_kanban_promote.py b/tests/hermes_cli/test_kanban_promote.py
index 55398b90f3d..3e88fd98592 100644
--- a/tests/hermes_cli/test_kanban_promote.py
+++ b/tests/hermes_cli/test_kanban_promote.py
@@ -9,7 +9,6 @@ Direct-SQL setup is used to construct that state deterministically.
from __future__ import annotations
import argparse
-import json
from pathlib import Path
import pytest
@@ -69,17 +68,11 @@ def test_promote_refuses_undone_parent_and_names_the_real_remedy(conn):
child, (parent,) = _stuck_todo(conn, parents_done=False)
ok, err = kb.promote_task(conn, child, actor="tester", reason="recovery")
assert not ok
- assert parent in err and "--force" not in err and f"unlink <parent_id> {child}" in err
+ assert err and parent in err
assert kb.get_task(conn, child).status == "todo"
assert kb.claim_task(conn, child) is None # still gated; nothing pretended
-def test_cli_promote_has_no_force_flag(kanban_home):
- from hermes_cli import kanban_parser
- parser = argparse.ArgumentParser(prog="hermes", add_help=False)
- kanban_parser.build_parser(parser.add_subparsers(dest="command"))
- with pytest.raises(SystemExit):
- parser.parse_args(["kanban", "promote", "t_x", "--force"])
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_kanban_review_lifecycle.py b/tests/hermes_cli/test_kanban_review_lifecycle.py
index a183984a592..18f764b9c61 100644
--- a/tests/hermes_cli/test_kanban_review_lifecycle.py
+++ b/tests/hermes_cli/test_kanban_review_lifecycle.py
@@ -631,43 +631,6 @@ def test_dispatch_json_exposes_suppression_reasons(
assert payload["memory_pressure"] == "elevated"
-def test_dispatch_text_and_daemon_stuck_warning_name_guard_reason(
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
-) -> None:
- """The plain `hermes kanban dispatch` output and the standalone daemon's
- "dispatcher stuck" warning both say WHY a ready card was held (#111910):
- a guarded card must not look like an idle tick with `Spawned: 0`."""
- res = kbd.DispatchResult(respawn_guarded=[("t_held", "active_pr")], memory_pressure="elevated")
- monkeypatch.setattr(kanban_ops.kbd, "dispatch_once", lambda *a, **k: res)
-
- class _Conn:
- def __enter__(self):
- return None
-
- def __exit__(self, *exc):
- return False
-
- monkeypatch.setattr(kanban_ops.kbc, "connect_closing", lambda: _Conn())
- assert kanban_ops._cmd_dispatch(
- SimpleNamespace(dry_run=True, max=None, failure_limit=kbd.DEFAULT_FAILURE_LIMIT, json=False)
- ) == 0
- out = capsys.readouterr().out
- assert "Guarded (active_pr): t_held" in out
- assert "Memory pressure elevated" in out
-
- def _fake_daemon(*, interval, max_spawn, failure_limit, on_tick):
- for _ in range(6): # HEALTH_WINDOW consecutive bad ticks
- on_tick(res)
-
- monkeypatch.setattr(kanban_ops.kbd, "run_daemon", _fake_daemon)
- monkeypatch.setattr(kanban_ops.kbd, "has_spawnable_ready", lambda conn: True)
- monkeypatch.setattr(kanban_ops.kb, "init_db", lambda *a, **k: None)
- assert kanban_ops._cmd_daemon(
- SimpleNamespace(force=True, interval=5, max=None, failure_limit=2, verbose=False, pidfile=None)
- ) in (0, None)
- err = capsys.readouterr().err
- assert "dispatcher stuck" in err
- assert "Last tick held back: active_pr=1, memory_pressure=elevated." in err
def test_review_dispatch_preserves_task_skills_and_adds_reviewer_skill(
diff --git a/tests/hermes_cli/test_kanban_review_surfaces.py b/tests/hermes_cli/test_kanban_review_surfaces.py
index 84e213256f7..dffffa8e1f1 100644
--- a/tests/hermes_cli/test_kanban_review_surfaces.py
+++ b/tests/hermes_cli/test_kanban_review_surfaces.py
@@ -115,11 +115,6 @@ def test_review_tools_are_gated_and_visible_to_kanban_workers(
assert "kanban_request_changes" in resolve_toolset("kanban")
-def test_review_changes_are_exposed_in_acp() -> None:
- pytest.importorskip("acp", reason="ACP adapter requires the optional acp extra")
- from acp_adapter.tools import _POLISHED_TOOLS
-
- assert "kanban_request_changes" in _POLISHED_TOOLS
def test_review_cli_round_trip_preserves_handoff(
@@ -234,27 +229,6 @@ def test_domain_and_cli_review_handoffs_redact_before_persistence(
assert secret not in json.dumps(event.payload)
-def test_worker_guidance_distinguishes_same_card_and_downstream_review() -> None:
- from agent.prompt_builder import KANBAN_GUIDANCE
- from hermes_cli.config_defaults import DEFAULT_CONFIG
-
- assert "lists child IDs" in KANBAN_GUIDANCE
- assert "inspect those cards" in KANBAN_GUIDANCE
- assert "pre-created review, QA, or release child" in KANBAN_GUIDANCE
- assert "call `kanban_complete`" in KANBAN_GUIDANCE
- assert "Never sticky-block that parent for `review-required`" in KANBAN_GUIDANCE
- assert "`kanban_request_changes`" in KANBAN_GUIDANCE
- assert "metadata=..." in KANBAN_GUIDANCE
- kanban_defaults = DEFAULT_CONFIG["kanban"]
- assert isinstance(kanban_defaults, dict)
- assert kanban_defaults["review_dispatch"] is True
-
- repo_root = Path(__file__).resolve().parents[2]
- review_skill = repo_root / "skills" / "devops" / "sdlc-review" / "SKILL.md"
- skill_text = review_skill.read_text(encoding="utf-8")
- assert "kanban_request_changes" in skill_text
- assert "approve" in skill_text.lower()
- assert "escalate" in skill_text.lower()
def test_cli_reopen_review_is_transition_first_and_redacts_reason(
diff --git a/tests/hermes_cli/test_kanban_task_updated_hook.py b/tests/hermes_cli/test_kanban_task_updated_hook.py
index 4080bd9ea79..8877eca0654 100644
--- a/tests/hermes_cli/test_kanban_task_updated_hook.py
+++ b/tests/hermes_cli/test_kanban_task_updated_hook.py
@@ -15,7 +15,7 @@ import pytest
from hermes_cli import kanban_db as kb
from hermes_cli import kanban_db_connect as kbc
-from hermes_cli.plugins import VALID_HOOKS, get_plugin_manager
+from hermes_cli.plugins import get_plugin_manager
@pytest.fixture
@@ -98,21 +98,3 @@ def test_raising_callback_does_not_break_assign(kanban_home):
mgr._hooks = saved
-def test_no_subscriber_short_circuits_task_updated(kanban_home, monkeypatch):
- from hermes_cli import lifecycle
-
- invoked: list[str] = []
- real_invoke = lifecycle.invoke_hook
-
- def _spy(hook_name, **kw):
- invoked.append(hook_name)
- return real_invoke(hook_name, **kw)
-
- monkeypatch.setattr(lifecycle, "invoke_hook", _spy)
- conn = kbc.connect()
- try:
- tid = kb.create_task(conn, title="t", assignee="alice")
- assert kb.assign_task(conn, tid, "bob") is True
- finally:
- conn.close()
- assert "on_kanban_task_updated" not in invoked
diff --git a/tests/hermes_cli/test_kanban_worker_exit_decode.py b/tests/hermes_cli/test_kanban_worker_exit_decode.py
index 8d4e11cc617..baf3a3b2ad2 100644
--- a/tests/hermes_cli/test_kanban_worker_exit_decode.py
+++ b/tests/hermes_cli/test_kanban_worker_exit_decode.py
@@ -24,34 +24,6 @@ def _spawn_exit(code: int) -> subprocess.Popen:
return proc
-def test_windows_reaper_classifies_parked_popen_exit(monkeypatch):
- """With the Windows flag on, the reaper learns exit codes from the parked
- ``Popen`` handles (no ``waitpid``) and the decode needs no ``os.WIF*``:
- the rate-limit sentinel is ``rate_limited``, a crash ``nonzero_exit``,
- and a still-running worker is left alone."""
- monkeypatch.setattr(kb, "_IS_WINDOWS", True)
- for name in ("WIFEXITED", "WEXITSTATUS", "WIFSIGNALED", "WTERMSIG"):
- monkeypatch.delattr(os, name, raising=False)
- monkeypatch.setattr(kbd, "_live_worker_procs", {})
- monkeypatch.setattr(kbd, "_recent_worker_exits", {})
-
- limited = _spawn_exit(kb.KANBAN_RATE_LIMIT_EXIT_CODE)
- crashed = _spawn_exit(3)
- alive = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) # noqa: S603
- try:
- for proc in (limited, crashed, alive):
- kbd._live_worker_procs[proc.pid] = proc
-
- reaped = kbd.reap_worker_zombies()
-
- assert sorted(reaped) == sorted([limited.pid, crashed.pid])
- assert kbd._classify_worker_exit(limited.pid) == ("rate_limited", kb.KANBAN_RATE_LIMIT_EXIT_CODE)
- assert kbd._classify_worker_exit(crashed.pid) == ("nonzero_exit", 3)
- assert kbd._classify_worker_exit(alive.pid) == ("unknown", None)
- assert set(kbd._live_worker_procs) == {alive.pid}
- finally:
- alive.kill()
- alive.wait()
@pytest.mark.windows_only
diff --git a/tests/hermes_cli/test_kanban_worker_lifecycle_hooks.py b/tests/hermes_cli/test_kanban_worker_lifecycle_hooks.py
index 6bb8d6cc668..1955922ec6e 100644
--- a/tests/hermes_cli/test_kanban_worker_lifecycle_hooks.py
+++ b/tests/hermes_cli/test_kanban_worker_lifecycle_hooks.py
@@ -21,7 +21,7 @@ import pytest
from hermes_cli import kanban_db as kb
from hermes_cli import kanban_db_connect as kbc
from hermes_cli import kanban_db_dispatch as kbd
-from hermes_cli.plugins import VALID_HOOKS, get_plugin_manager
+from hermes_cli.plugins import get_plugin_manager
WORKER_HOOKS = (
"on_kanban_worker_spawned",
@@ -187,26 +187,3 @@ def test_raising_callbacks_never_break_worker_lifecycle(
mgr._hooks = saved
-def test_no_subscriber_short_circuits_worker_hooks(
- kanban_home, all_assignees_spawnable, monkeypatch,
-):
- """With nothing registered, the new observers are never invoked at all."""
- from hermes_cli import lifecycle
-
- invoked: list[str] = []
- real_invoke = lifecycle.invoke_hook
-
- def _spy(hook_name, **kw):
- invoked.append(hook_name)
- return real_invoke(hook_name, **kw)
-
- monkeypatch.setattr(lifecycle, "invoke_hook", _spy)
- conn = kbc.connect()
- try:
- kb.create_task(conn, title="t", assignee="alice")
- kbd.dispatch_once(conn, spawn_fn=lambda *a, **k: 222)
- finally:
- conn.close()
- assert "on_kanban_worker_spawned" not in invoked
- # The shipped claimed hook has no short-circuit and still fires.
- assert "kanban_task_claimed" in invoked
diff --git a/tests/hermes_cli/test_launchd_refresh_reporting.py b/tests/hermes_cli/test_launchd_refresh_reporting.py
index 92a864008b2..b9184655336 100644
--- a/tests/hermes_cli/test_launchd_refresh_reporting.py
+++ b/tests/hermes_cli/test_launchd_refresh_reporting.py
@@ -30,17 +30,3 @@ def test_refresh_reports_registration_outcome(tmp_path, monkeypatch, capsys):
assert "Updated" in capsys.readouterr().out
-def test_install_repair_warns_instead_of_claiming_success(tmp_path, monkeypatch, capsys):
- plist_path = tmp_path / "com.hermes.plist"
- plist_path.write_text("<old/>", encoding="utf-8")
- monkeypatch.setattr(gw, "get_launchd_plist_path", lambda: plist_path)
- monkeypatch.setattr(gw, "launchd_plist_is_current", lambda: False)
- monkeypatch.setattr(gw, "refresh_launchd_plist_if_needed", lambda: False)
- monkeypatch.setattr("hermes_constants.display_hermes_home", lambda: "~/.hermes-work")
-
- gw.launchd_install(force=False)
-
- out = capsys.readouterr().out
- assert "Service definition updated" not in out
- assert "could not be reloaded" in out
- assert "~/.hermes-work/logs/launchd-reload.log" in out
diff --git a/tests/hermes_cli/test_lazy_command_exports.py b/tests/hermes_cli/test_lazy_command_exports.py
index 2214ee14294..d2c9f9608af 100644
--- a/tests/hermes_cli/test_lazy_command_exports.py
+++ b/tests/hermes_cli/test_lazy_command_exports.py
@@ -53,23 +53,7 @@ def test_frozen_updater_surface_resolves_to_real_objects():
assert got is getattr(mod, name) or (
getattr(got, "__module__", None) == module and getattr(got, "__name__", None) == name
), name
- assert "_kill_stale_dashboard_processes" in hermes_cli.main._FROZEN_UPDATER_SURFACE["hermes_cli.dashboard_procs"]
- assert "_stash_local_changes_if_needed" in hermes_cli.main._FROZEN_UPDATER_SURFACE["hermes_cli.update_cmd"]
-def test_frozen_surface_covers_every_update_cmd_main_read():
- """Every ``_m().<name>`` in the frozen update_cmd*.py files resolves on hermes_cli.main."""
- import re
- from pathlib import Path
- pkg = Path(hermes_cli.main.__file__).parent
- names = set()
- for path in pkg.glob("update*.py"):
- names.update(re.findall(r"_m\(\)\.(\w+)", path.read_text(encoding="utf-8")))
- missing = [n for n in sorted(names) if not hasattr(hermes_cli.main, n)]
- assert not missing, missing
-
-def test_removed_reexports_are_gone():
- for name in ("_scan_dashboard_processes", "_warn_stale_dashboard_processes", "_self", "_PROVIDER_MODELS"):
- assert not hasattr(hermes_cli.main, name), name
diff --git a/tests/hermes_cli/test_lazy_refresh_venv_repair.py b/tests/hermes_cli/test_lazy_refresh_venv_repair.py
index 98857115161..49480f95842 100644
--- a/tests/hermes_cli/test_lazy_refresh_venv_repair.py
+++ b/tests/hermes_cli/test_lazy_refresh_venv_repair.py
@@ -3,14 +3,11 @@
from __future__ import annotations
import textwrap
-from pathlib import Path
-from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
import hermes_cli.main as m
import hermes_cli.main_install_repair as hermes_cli_main_install_repair
from hermes_cli import main_install_repair
-from hermes_cli import update_cmd
import pytest
@@ -89,7 +86,7 @@ def test_repair_runs_force_reinstall_with_pyproject_pins(
assert detect_calls["count"] == 1
-def test_refresh_repairs_venv_after_lazy_failure(tmp_path, monkeypatch, capsys):
+def test_refresh_repairs_venv_after_lazy_failure(tmp_path, monkeypatch):
import tools.lazy_deps as lazy_deps_mod
monkeypatch.setattr(lazy_deps_mod, "active_features", lambda: ["platform.matrix"])
@@ -109,13 +106,9 @@ def test_refresh_repairs_venv_after_lazy_failure(tmp_path, monkeypatch, capsys):
monkeypatch.setattr(main_install_repair, "_repair_broken_lazy_refresh_imports", fake_repair)
ok = m._refresh_active_lazy_features(["uv", "pip"], env={"VIRTUAL_ENV": str(tmp_path)})
- out = capsys.readouterr().out
assert ok is True
assert repair_calls == [["PyYAML"]]
- assert "Venv repair succeeded" in out
- assert "import probes" in out
- assert "Backends keep their previously-installed version" not in out
def test_refresh_uses_pre_rebuild_snapshot_when_provided(monkeypatch):
@@ -140,16 +133,6 @@ def test_refresh_uses_pre_rebuild_snapshot_when_provided(monkeypatch):
assert restored == [["platform.telegram"]]
-def test_capture_active_tool_dependencies_uses_tools_status_probes(monkeypatch):
- from hermes_cli import tools_config_post_setup
-
- monkeypatch.setattr(
- tools_config_post_setup,
- "_module_installed",
- lambda module: module in {"langfuse", "ddgs"},
- )
-
- assert m._capture_active_tool_dependencies() == ["ddgs", "langfuse"]
def test_restore_active_tool_dependencies_uses_static_allowlist(monkeypatch):
@@ -175,96 +158,6 @@ def test_restore_active_tool_dependencies_uses_static_allowlist(monkeypatch):
assert calls == [(["uv", "pip", "install", "langfuse", "--quiet"], env)]
-def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(
- tmp_path, monkeypatch
-):
- """The updater must carry pre-rebuild state into its repair refresh."""
- from hermes_cli import managed_uv, update_cmd
-
- (tmp_path / ".git").mkdir()
- snapshot = ["platform.telegram"]
- tool_snapshot = ["langfuse"]
- refresh_calls = []
- restore_calls = []
-
- class RestoreReached(Exception):
- pass
-
- def fake_run(cmd, **kwargs):
- if "rev-parse" in cmd:
- return SimpleNamespace(returncode=0, stdout="main\n", stderr="")
- if "rev-list" in cmd:
- return SimpleNamespace(returncode=0, stdout="0\n", stderr="")
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- def fake_refresh(prefix, *, env=None, features=None):
- refresh_calls.append((prefix, env, features))
- return True
-
- def fake_restore(dependencies, prefix, *, env=None):
- restore_calls.append((dependencies, prefix, env))
- raise RestoreReached
-
- monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(m, "_capture_active_lazy_features", lambda: snapshot.copy())
- monkeypatch.setattr(
- m, "_capture_active_tool_dependencies", lambda: tool_snapshot.copy()
- )
- monkeypatch.setattr(m, "_is_windows", lambda: False)
- monkeypatch.setattr(hermes_cli_main_install_repair, "_is_windows", lambda: False)
- monkeypatch.setattr(m, "_run_pre_update_backup", lambda args: None)
- monkeypatch.setattr(m, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(m, "_resume_windows_gateways_after_update", lambda state: None)
- monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *args: None)
- monkeypatch.setattr(m, "_get_origin_url", lambda *args: "https://github.com/NousResearch/hermes-agent.git")
- monkeypatch.setattr(m, "_resolve_update_branch", lambda args: "main")
- monkeypatch.setattr(m, "_stash_local_changes_if_needed", lambda *args: None)
- monkeypatch.setattr(update_cmd, "_invalidate_update_cache", lambda: None)
- monkeypatch.setattr(
- update_cmd, "_venv_core_imports_healthy", lambda: (False, "broken")
- )
- monkeypatch.setattr(update_cmd, "_write_update_incomplete_marker", lambda: None)
- monkeypatch.setattr(
- m, "_install_python_dependencies_with_optional_fallback", lambda *a, **k: None
- )
- monkeypatch.setattr(m, "_refresh_active_lazy_features", fake_refresh)
- monkeypatch.setattr(m, "_restore_active_tool_dependencies", fake_restore)
- monkeypatch.setattr(m.subprocess, "run", fake_run)
- monkeypatch.setattr(managed_uv, "update_managed_uv", lambda **kwargs: None)
- monkeypatch.setattr(managed_uv, "ensure_uv", lambda **kwargs: "uv")
-
- args = SimpleNamespace(
- yes=True,
- force=False,
- force_venv=False,
- no_backup=True,
- backup=False,
- branch=None,
- )
- with pytest.raises(RestoreReached):
- update_cmd._cmd_update_impl(args, gateway_mode=False)
-
- # The repair env is now built via managed_python_env (#83914): third-party
- # UV vars are stripped, managed pins set, then VIRTUAL_ENV re-pointed at
- # the install's venv. Assert the CONTRACT, not the raw environ copy.
- from hermes_cli.managed_uv import managed_python_env
-
- expected_env = managed_python_env()
- expected_env["VIRTUAL_ENV"] = str(tmp_path / "venv")
- assert refresh_calls == [
- (
- ["uv", "pip"],
- expected_env,
- snapshot,
- )
- ]
- assert restore_calls == [
- (
- tool_snapshot,
- ["uv", "pip"],
- expected_env,
- )
- ]
diff --git a/tests/hermes_cli/test_lazy_secrets_dispatch.py b/tests/hermes_cli/test_lazy_secrets_dispatch.py
index 32e925001d7..383acd156a9 100644
--- a/tests/hermes_cli/test_lazy_secrets_dispatch.py
+++ b/tests/hermes_cli/test_lazy_secrets_dispatch.py
@@ -17,7 +17,6 @@ import sys
from pathlib import Path
import pytest
-from hermes_cli import update_cmd
def _run_hermes(args: list[str], timeout: int = 30) -> subprocess.CompletedProcess[str]:
@@ -109,15 +108,6 @@ class TestSecretsDispatchE2E:
)
assert "ImportError" not in result.stderr
- def test_onepassword_setup_help(self) -> None:
- """`hermes secrets onepassword setup --help` must exit 0."""
- result = _run_hermes(["secrets", "onepassword", "setup", "--help"])
- assert result.returncode in (0, 2), (
- f"onepassword setup --help failed:\n"
- f"stdout: {result.stdout}\n"
- f"stderr: {result.stderr}"
- )
- assert "ImportError" not in result.stderr
class TestUpdatePathE2E:
@@ -141,15 +131,6 @@ class TestUpdatePathE2E:
assert "ImportError" not in result.stderr
assert "cannot import name" not in result.stderr
- @pytest.mark.live_system_guard_bypass
- def test_update_no_self_lock(self) -> None:
- """Update path must not self-lock (cryptography._rust absent)."""
- result = _run_hermes(["update", "--check"])
- # The check itself may return non-zero (e.g. no updates), but
- # must not contain the self-lock defer message
- assert "deferred" not in result.stderr.lower()
- assert "self-lock" not in result.stderr.lower()
- assert "_rust.pyd" not in result.stderr.lower()
@pytest.mark.live_system_guard_bypass
def test_main_update_check_crypto_absent_in_sys_modules(self) -> None: