Skip to content

The agent that grows with you

test: purge low-value tests, lane py10 (412 removed)

teknium1d09dacf66aab
diff --git a/tests/hermes_cli/test_anon_desktop_signin.py b/tests/hermes_cli/test_anon_desktop_signin.py
index f1849a7fcea..45d366a8c41 100644
--- a/tests/hermes_cli/test_anon_desktop_signin.py
+++ b/tests/hermes_cli/test_anon_desktop_signin.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import time
-import httpx
import pytest
from fastapi.testclient import TestClient
@@ -97,11 +96,13 @@ def test_a_sign_in_cancelled_while_waiting_never_persists_the_account(portal, fr
return {"status": "completed", "user_id": "nas_user:9", "account_email": EMAIL}
monkeypatch.setattr(anon_auth, "wait_for_promotion", _wait_until_released)
+ threads_before = set(threading.enumerate())
start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()
assert client.delete(f"/api/providers/oauth/sessions/{start['session_id']}", headers=HEADERS).json()["ok"] is True
release.set()
- for _ in range(100):
- time.sleep(0.05)
+ # Let the poller finish whatever it does with the "completed" result before asserting.
+ for t in set(threading.enumerate()) - threads_before:
+ t.join(timeout=5)
assert portal.token_grants == 0
state = _load_auth_store()["providers"]["nous"]
assert state["anon_token"] == guest["anon_token"] and anon_auth.is_guest_state(state)
diff --git a/tests/hermes_cli/test_anon_failure_modes.py b/tests/hermes_cli/test_anon_failure_modes.py
index 7afdc4a70e3..0b61c672290 100644
--- a/tests/hermes_cli/test_anon_failure_modes.py
+++ b/tests/hermes_cli/test_anon_failure_modes.py
@@ -74,7 +74,7 @@ class TestNasRefusalCodes:
nas.token_response = httpx.Response(428, json={"error": "pow_required", "pow": {"bits": 31}})
err = _exchange_error(nas)
assert err.code == anon_auth.ANON_POW_REQUIRED and err.retryable is False
- assert str(err).startswith("The Nous server asked for a proof of work, but that isn't implemented")
+ assert "proof of work" in str(err)
# The credential from ``create`` is kept, so a later NAS without PoW exchanges it instead
# of minting again.
assert anon_auth.is_guest_state(_load_auth_store()["providers"]["nous"])
@@ -170,7 +170,8 @@ class TestMintCooldown:
failure = anon_auth._mint_failure_for_profile()
waits.append(failure.retry_after)
monkeypatch.setattr(anon_auth.time, "monotonic", lambda f=failure: f.not_before + 1)
- assert waits == [15.0, 60.0, 300.0, 300.0]
+ ladder = list(anon_auth._MINT_RETRY_LADDER)
+ assert waits == (ladder + [ladder[-1]] * 4)[:4]
def test_the_users_own_retry_bypasses_the_cooldown_once(self, nas):
nas.raise_transport = httpx.ConnectTimeout("no route")
@@ -223,7 +224,7 @@ class TestBootstrapRecord:
free_tier_bootstrap._bootstrap_then_retry()
record = free_tier_bootstrap.current_record()
assert record.has_identity is True and record.free_tier is True
- assert slept == [15, 60]
+ assert slept == [int(w) for w in anon_auth._MINT_RETRY_LADDER[:2]]
assert nas.creates() == 3
def test_the_background_loop_never_retries_a_terminal_code(self, nas, monkeypatch):
@@ -308,7 +309,7 @@ class TestSignInFailures:
def test_an_unnamed_local_failure_keeps_the_generic_copy_and_its_terminal_detail(self):
state = anon_sign_in._failed_from_exception(RuntimeError("bad CA bundle"))
assert state.reason == "" and state.copy == anon_sign_in.UPGRADE_NOT_COMPLETED
- assert state.copy_terminal == "Sign-in failed: bad CA bundle"
+ assert "bad CA bundle" in state.copy_terminal
def test_account_busy_is_retryable(self):
state = anon_sign_in.Failed(reason="account_busy")
@@ -333,15 +334,6 @@ def test_extra_welcome_hosts_make_a_local_stand_in_the_welcome_host(monkeypatch)
# --- The spoken wait -----------------------------------------------------------------------------
[email protected]("seconds,expected", [
- (0, "a few seconds"), (5, "a few seconds"), (30, "about a minute"), (89, "about a minute"),
- (300, "about 5 minutes"), (3599, "about 60 minutes"), (3600, "about an hour"), (7200, "about 2 hours"),
- ("nope", "a few seconds"),
-])
-def test_friendly_wait_never_prints_raw_seconds(seconds, expected):
- assert anon_auth.friendly_wait(seconds) == expected
-
-
def test_retry_after_is_the_whole_wait_not_the_wait_plus_float_dust(monkeypatch):
"""``(now + 60) - now`` is 60.000000000000455 for this ``now``; the payload must still say 60."""
now = 4080.78551427515
diff --git a/tests/hermes_cli/test_anon_sign_in_flow.py b/tests/hermes_cli/test_anon_sign_in_flow.py
index 5cc28a62115..98810a20253 100644
--- a/tests/hermes_cli/test_anon_sign_in_flow.py
+++ b/tests/hermes_cli/test_anon_sign_in_flow.py
@@ -10,12 +10,10 @@ from __future__ import annotations
import threading
import time
-import httpx
import pytest
from hermes_cli import anon_auth
from hermes_cli.auth import _auth_file_path
-from hermes_cli.auth_constants import AuthError
from tests.hermes_cli.test_anon_upgrade import ( # noqa: F401 (fixtures used by name)
EMAIL, FREE_PICK, PORTAL, WELCOME, _shared_store, _write_model_config, free_account, portal)
@@ -63,7 +61,7 @@ def test_declined_yields_declined_and_persists_nothing(portal, tmp_path):
_seed_free_tier()
before = _auth_file_path().read_bytes()
shared_before = _shared_store(tmp_path)
- portal.status_sequence = [{"status": "pending"}, _voided("user_declined")]
+ portal.status_sequence = [_voided("user_declined")]
terminal = [s for s in _drain() if s.terminal]
@@ -181,7 +179,7 @@ def test_a_transport_error_yields_failed_without_leaking_the_detail_into_chat_co
lowered = state.copy.lower()
for banned in ("http://", "https://", "/anonymous/", "anonymous"):
assert banned not in lowered
- assert state.copy_terminal == f"Sign-in failed: {detail}"
+ assert detail in state.copy_terminal
assert portal.token_grants == 0
assert _auth_file_path().read_bytes() == before
@@ -390,26 +388,6 @@ def test_a_persist_guard_that_refuses_persists_nothing_and_never_settles(
assert _auth_file_path().read_bytes() == before
-def test_settle_runs_exactly_once_per_completion(portal, free_account, monkeypatch):
- _seed_free_tier()
- settles, persists = [], []
- real_settle = anon_auth.settle_after_upgrade
- from hermes_cli import auth_nous
- real_persist = auth_nous.persist_nous_credentials
- monkeypatch.setattr(
- anon_auth, "settle_after_upgrade",
- lambda state: (settles.append(state), real_settle(state))[1])
- monkeypatch.setattr(
- auth_nous, "persist_nous_credentials",
- lambda state, **kw: (persists.append(state), real_persist(state, **kw))[1])
-
- states = list(anon_auth.run_sign_in())
-
- assert states[-1].kind == "completed"
- assert len(settles) == 1
- assert len(persists) == 1
-
-
def test_persistence_happens_only_after_the_promotion_and_the_token_grant(portal, free_account):
_seed_free_tier()
before = _auth_file_path().read_bytes()
@@ -424,33 +402,6 @@ def test_persistence_happens_only_after_the_promotion_and_the_token_grant(portal
assert "/api/oauth/token" in paths
-def test_the_budget_shrinks_across_the_two_waits(portal, free_account, monkeypatch):
- """One absolute deadline: what the promotion wait spends, the token poll no longer has."""
- _seed_free_tier()
- captured = {}
- from hermes_cli import auth_device_flow
- real_request, real_poll = auth_device_flow._request_device_code, auth_device_flow._poll_for_token
-
- def _short_lived_code(client, portal_base_url, client_id, scope):
- return {**real_request(client, portal_base_url, client_id, scope), "expires_in": 10}
- monkeypatch.setattr(auth_device_flow, "_request_device_code", _short_lived_code)
-
- def _wait(client, portal_base_url, claim_code, *, expires_in, interval, cancelled=None):
- time.sleep(3.0)
- return {"status": "completed", "account_email": EMAIL}
- monkeypatch.setattr(anon_auth, "wait_for_promotion", _wait)
-
- def _poll(**kwargs):
- captured.update(kwargs)
- return real_poll(**kwargs)
- monkeypatch.setattr(auth_device_flow, "_poll_for_token", _poll)
-
- states = list(anon_auth.run_sign_in())
-
- assert states[-1].kind == "completed"
- assert 1 <= captured["expires_in"] <= 7
-
-
def test_the_scope_is_entered_for_the_preconditions_and_the_persist_but_never_around_a_wait(
portal, free_account, monkeypatch):
import contextlib
@@ -491,14 +442,3 @@ def test_the_scope_is_entered_for_the_preconditions_and_the_persist_but_never_ar
assert not any(first[1] <= at <= second[1] for at in yields)
-def test_wait_for_promotion_without_a_cancel_hook_is_unchanged(portal):
- import httpx
- _seed_free_tier()
- portal.status_sequence = [{"status": "completed", "account_email": EMAIL}]
- portal.calls.clear()
- with httpx.Client(transport=httpx.MockTransport(portal.handler), base_url=PORTAL) as client:
- outcome = anon_auth.wait_for_promotion(
- client, PORTAL, "clm_1", expires_in=30, interval=0)
-
- assert outcome == {"status": "completed", "account_email": EMAIL}
- assert [p for _, p in portal.calls] == ["/api/anonymous/promotion-status"]
diff --git a/tests/hermes_cli/test_anon_surfaces.py b/tests/hermes_cli/test_anon_surfaces.py
index 9272b7662f4..b19b15e2fb6 100644
--- a/tests/hermes_cli/test_anon_surfaces.py
+++ b/tests/hermes_cli/test_anon_surfaces.py
@@ -12,19 +12,16 @@ import base64
import dataclasses
import json
import re
-import threading
import time
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
import pytest
-from unittest.mock import AsyncMock, call
from hermes_cli import (
anon_auth,
auth_commands,
- model_setup_flows,
nous_account,
nous_auth_keepalive,
portal_cli,
@@ -155,32 +152,6 @@ def test_keepalive_does_not_start_for_free_tier(isolated_store, monkeypatch):
monkeypatch.setattr(nous_auth_keepalive, "_keepalive_thread", None)
-def test_every_in_chat_free_tier_string_names_the_slash_command(monkeypatch):
- from gateway.run_notifications import GatewayNotificationsMixin
-
- monkeypatch.setattr("hermes_cli.auth.resolve_provider", lambda _requested: "nous")
- monkeypatch.setattr(anon_auth, "guest_carries_inference", lambda: True)
- startup = GatewayNotificationsMixin._free_tier_startup_line(object())
- command_copy = (
- anon_auth.FREE_TIER_AVAILABLE_NOTICE,
- anon_auth.FREE_TIER_STATUS_LINE,
- anon_auth.UPGRADE_UNAVAILABLE_CHAT,
- anon_auth.FREE_TIER_RATE_LIMIT_CHAT,
- nous_account.FREE_TIER_NEEDS_ACCOUNT_CHAT,
- startup,
- )
- refusal_copy = (
- anon_auth.LOGIN_DM_ONLY,
- anon_auth.LOGIN_BUSY_ELSEWHERE,
- anon_auth.LOGIN_NOT_ALLOWED,
- )
- assert all("/login" in text for text in command_copy)
- for text in (*command_copy, *refusal_copy):
- # The ruled refusal uses Hermes as the grammatical subject; only that exact product-name
- # phrase is exempt from the broad top-level-command gate.
- assert "hermes " not in text.replace("this Hermes can", "this product can").lower()
-
-
def test_no_chat_copy_of_any_sign_in_state_leaks_a_terminal_verb_or_a_forbidden_word():
placeholders = {
"link": "https://example.test/sign-in",
@@ -205,17 +176,6 @@ def test_no_chat_copy_of_any_sign_in_state_leaks_a_terminal_verb_or_a_forbidden_
assert terminal_or_url.search(copy) is None, state_type.__name__
-def test_terminal_only_strings_keep_the_terminal_verb(monkeypatch, capsys):
- assert "hermes " in nous_account.FREE_TIER_NEEDS_ACCOUNT
- assert "hermes " in anon_auth.UPGRADE_UNAVAILABLE
- assert "hermes " in anon_auth.FREE_TIER_NOT_SIGNED_IN
-
- monkeypatch.setattr("hermes_cli.auth.get_provider_auth_state", lambda _provider: {"access_token": "token"})
- monkeypatch.setattr("hermes_cli.model_switch_providers._free_tier_nous_row", lambda _provider: None)
- model_setup_flows._model_flow_nous({})
- assert "hermes " in capsys.readouterr().out
-
-
def test_the_paid_tool_notice_switches_wording_inside_a_chat():
info = nous_account.NousPortalAccountInfo(
logged_in=True, source="token", fresh=True, account_tier="anonymous"
@@ -228,42 +188,6 @@ def test_the_paid_tool_notice_switches_wording_inside_a_chat():
) == nous_account.FREE_TIER_NEEDS_ACCOUNT
-async def test_the_wait_line_is_only_composed_on_the_state(monkeypatch):
- from gateway.slash_commands_login import GatewayLoginCommandsMixin
-
- state = anon_auth.Code(
- link="https://example.test/sign-in", code="code-1", expires_in=900, interval=1
- )
- assert state.copy == anon_auth.UPGRADE_DO_NOT_SHARE
- assert state.copy_with_wait == (
- f"{anon_auth.UPGRADE_DO_NOT_SHARE} {anon_auth.format_wait_line(state.expires_in)}"
- )
-
- monkeypatch.setattr(
- "hermes_cli.auth_device_flow._print_device_code_instructions", lambda *_args, **_kwargs: None
- )
- cli_copy = []
- anon_auth.render_sign_in_cli_code(state, printer=cli_copy.append)
- runner = SimpleNamespace(_push_login=AsyncMock())
- attempt = object()
- await GatewayLoginCommandsMixin._render_login_state(runner, attempt, state)
-
- assert cli_copy == [f" {state.copy_with_wait}"]
- assert runner._push_login.await_args_list == [
- call(attempt, state.link),
- call(attempt, state.code),
- call(attempt, state.copy_with_wait),
- ]
-
- # The wait line is composed once, on the state. A renderer that called
- # format_wait_line itself would emit the same text and pass the assertions
- # above, so the renderers are checked by source instead.
- repo = Path(anon_auth.__file__).resolve().parents[1]
- for rel in ("gateway/slash_commands_login.py", "hermes_cli/cli_commands_mixin.py"):
- assert "format_wait_line" not in (repo / rel).read_text(encoding="utf-8"), rel
-
-
def test_cli_chat_status_names_the_free_tier(isolated_store):
from hermes_cli.cli_session_mixin import CLISessionMixin
diff --git a/tests/hermes_cli/test_anon_upgrade.py b/tests/hermes_cli/test_anon_upgrade.py
index fde6147e884..b6ffe141eb6 100644
--- a/tests/hermes_cli/test_anon_upgrade.py
+++ b/tests/hermes_cli/test_anon_upgrade.py
@@ -145,7 +145,7 @@ class TestUpgrade:
anon_auth.ensure_portal_identity(explicit=True)
before = _auth_file_path().read_bytes()
shared_before = _shared_store(tmp_path)
- portal.status_sequence = [{"status": "pending"}, {"status": "voided", "reason": "user_declined"}]
+ portal.status_sequence = [{"status": "voided", "reason": "user_declined"}]
code = anon_auth.upgrade_guest(_args())
out = capsys.readouterr().out
assert code == 1
diff --git a/tests/hermes_cli/test_anthropic_model_flow_stale_oauth.py b/tests/hermes_cli/test_anthropic_model_flow_stale_oauth.py
index a0121c55b0f..3294c90d541 100644
--- a/tests/hermes_cli/test_anthropic_model_flow_stale_oauth.py
+++ b/tests/hermes_cli/test_anthropic_model_flow_stale_oauth.py
@@ -64,82 +64,4 @@ class TestStaleOAuthTokenDetection:
f"Expected auth method menu but got: {output!r}"
)
- def test_valid_api_key_skips_stale_check(self, tmp_path, monkeypatch, capsys):
- """
- A non-OAuth ANTHROPIC_API_KEY (regular pay-per-token key) must NOT be
- flagged as stale even when cc_creds are invalid. Regular API keys don't
- expire the same way OAuth tokens do.
- """
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
-
- # Regular API key — NOT an OAuth token
- save_env_value("ANTHROPIC_API_KEY", "sk-ant-api03-RegularPayPerTokenKey")
- save_env_value("ANTHROPIC_TOKEN", "")
-
- monkeypatch.setattr(
- "agent.anthropic_credentials.read_claude_code_credentials",
- lambda: None, # No CC creds
- )
- monkeypatch.setattr(
- "agent.anthropic_credentials.is_claude_code_token_valid",
- lambda creds: False,
- )
- monkeypatch.setattr(
- "agent.anthropic_credentials._is_oauth_token",
- lambda key: key.startswith("sk-ant-") and "oat" in key,
- )
-
- # Simulate user picks "1" (use existing)
- monkeypatch.setattr("builtins.input", lambda _: "1")
-
- from hermes_cli.model_setup_flows import _model_flow_anthropic
- cfg = {}
-
- _model_flow_anthropic(cfg)
-
- output = capsys.readouterr().out
- # Should show "Use existing credentials" menu, NOT auth method choice
- assert "Use existing" in output or "credentials" in output.lower()
-
-
-class TestStaleOAuthGuardLogic:
- """Unit-level test of the stale-OAuth detection guard logic."""
-
- def test_stale_oauth_flag_logic_no_cc_creds(self):
- """
- When existing_key is OAuth and cc_available is False,
- existing_is_stale_oauth should be True → has_creds = False.
- """
- existing_key = "sk-ant-oat-expiredtoken123"
- _is_oauth_token = lambda k: k.startswith("sk-ant-")
- cc_available = False
-
- existing_is_stale_oauth = (
- bool(existing_key) and
- _is_oauth_token(existing_key) and
- not cc_available
- )
- has_creds = (bool(existing_key) and not existing_is_stale_oauth) or cc_available
-
- assert existing_is_stale_oauth is True
- assert has_creds is False
-
- def test_stale_oauth_flag_logic_with_valid_cc_creds(self):
- """
- When existing_key is OAuth but cc_available is True (valid creds exist),
- has_creds should be True — the cc_creds will be used instead.
- """
- existing_key = "sk-ant-oat-sometoken"
- _is_oauth_token = lambda k: k.startswith("sk-ant-")
- cc_available = True
-
- existing_is_stale_oauth = (
- bool(existing_key) and
- _is_oauth_token(existing_key) and
- not cc_available
- )
- has_creds = (bool(existing_key) and not existing_is_stale_oauth) or cc_available
-
- assert existing_is_stale_oauth is False
- assert has_creds is True
diff --git a/tests/hermes_cli/test_anthropic_picker_curated.py b/tests/hermes_cli/test_anthropic_picker_curated.py
index 198aa90371a..01627231e6e 100644
--- a/tests/hermes_cli/test_anthropic_picker_curated.py
+++ b/tests/hermes_cli/test_anthropic_picker_curated.py
@@ -16,43 +16,6 @@ from unittest.mock import patch
from hermes_cli import models as M
-def test_anthropic_native_list_keeps_aggregator_flagships():
- """Native Anthropic must list the same current flagships OpenRouter/Nous already ship.
-
- Aggregator catalogs get the new aliases first; the native curated list is what
- `/model` falls back to when live `/v1/models` lags or 401s. Newest-first order
- is the contract that keeps Fable 5.1 / Opus 5 from hiding behind older 4.x ids.
- """
- or_ids = {mid for mid, _ in M.OPENROUTER_MODELS}
- native = M._PROVIDER_MODELS["anthropic"]
- for slug in ("claude-fable-5.1", "claude-opus-5"):
- assert f"anthropic/{slug}" in or_ids
- assert slug in native
- assert native.index("claude-fable-5.1") < native.index("claude-fable-5")
- assert native.index("claude-opus-5") < native.index("claude-opus-4-8")
-
-
-def test_anthropic_curated_alias_survives_when_live_omits_it():
- """A curated alias missing from /v1/models still surfaces (first)."""
- curated = M._PROVIDER_MODELS["anthropic"]
- assert "claude-fable-5.1" in curated # sanity: newest Fable alias is curated
- assert "claude-fable-5" in curated # sanity: the alias is curated
- assert "claude-opus-5" in curated # sanity: native flagship matches aggregators
- assert "claude-sonnet-5" in curated # newest Sonnet alias is curated
-
- # Live catalog the API would actually return — no fable-5.1 / opus-5.
- live = ["claude-opus-4-8", "claude-sonnet-4-6", "claude-haiku-4-5-20251001"]
- with patch.object(M, "_fetch_anthropic_models", return_value=live):
- result = M.provider_model_ids("anthropic")
-
- assert "claude-fable-5.1" in result
- assert "claude-fable-5" in result
- assert "claude-opus-5" in result
- assert "claude-sonnet-5" in result
- # Curated order is preserved at the front.
- assert result[:len(curated)] == list(curated)
-
-
def test_anthropic_merge_dedupes_overlap_and_appends_live_only():
"""Models in both lists appear once; live-only models are appended."""
live = [
@@ -68,8 +31,8 @@ def test_anthropic_merge_dedupes_overlap_and_appends_live_only():
# Live-only entry is preserved (discovery still works for unknown models).
assert "claude-future-9-99" in result
# Curated entries lead, live-only trails.
- assert result.index("claude-fable-5.1") < result.index("claude-future-9-99")
- assert result.index("claude-opus-5") < result.index("claude-future-9-99")
+ curated = list(M._PROVIDER_MODELS["anthropic"])
+ assert result[:len(curated)] == curated and result[-1] == "claude-future-9-99"
def test_anthropic_falls_back_to_curated_when_live_unavailable():
@@ -78,6 +41,3 @@ def test_anthropic_falls_back_to_curated_when_live_unavailable():
result = M.provider_model_ids("anthropic")
assert result == list(M._PROVIDER_MODELS["anthropic"])
- assert "claude-fable-5.1" in result
- assert "claude-opus-5" in result
- assert "claude-fable-5" in result
diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.py
index 70043cd8f6a..740af4ac6ad 100644
--- a/tests/hermes_cli/test_api_key_providers.py
+++ b/tests/hermes_cli/test_api_key_providers.py
@@ -1,7 +1,6 @@
"""Tests for API-key provider support (z.ai/GLM, Kimi, MiniMax, AI Gateway)."""
import json
-import os
import pytest
@@ -10,13 +9,9 @@ from hermes_cli.auth import (
resolve_provider,
get_api_key_provider_status,
resolve_api_key_provider_credentials,
- get_external_process_provider_status,
- resolve_external_process_provider_credentials,
- get_auth_status,
AuthError,
KIMI_CODE_BASE_URL,
STEPFUN_STEP_PLAN_INTL_BASE_URL,
- STEPFUN_STEP_PLAN_CN_BASE_URL,
_resolve_kimi_base_url,
)
from hermes_cli.copilot_auth import _try_gh_cli_token
@@ -26,103 +21,6 @@ from hermes_cli.copilot_auth import _try_gh_cli_token
# Provider Registry tests
# =============================================================================
-class TestProviderRegistry:
- """Test that new providers are correctly registered."""
-
- @pytest.mark.parametrize("provider_id,name,auth_type", [
- ("copilot-acp", "GitHub Copilot ACP", "external_process"),
- ("copilot", "GitHub Copilot", "api_key"),
- ("huggingface", "Hugging Face", "api_key"),
- ("zai", "Z.AI / GLM", "api_key"),
- ("xai", "xAI", "api_key"),
- ("nvidia", "NVIDIA NIM", "api_key"),
- ("kimi-coding", "Kimi / Moonshot", "api_key"),
- ("stepfun", "StepFun Step Plan", "api_key"),
- ("minimax", "MiniMax", "api_key"),
- ("minimax-cn", "MiniMax (China)", "api_key"),
- ("ai-gateway", "Vercel AI Gateway", "api_key"),
- ("kilocode", "Kilo Code", "api_key"),
- ("gmi", "GMI Cloud", "api_key"),
- ])
- def test_provider_registered(self, provider_id, name, auth_type):
- assert provider_id in PROVIDER_REGISTRY
- pconfig = PROVIDER_REGISTRY[provider_id]
- assert pconfig.name == name
- assert pconfig.auth_type == auth_type
- assert pconfig.inference_base_url # must have a default base URL
-
-
-
-
- def test_copilot_env_vars(self):
- pconfig = PROVIDER_REGISTRY["copilot"]
- assert pconfig.api_key_env_vars == ("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN")
- assert pconfig.base_url_env_var == "COPILOT_API_BASE_URL"
-
- def test_kimi_env_vars(self):
- pconfig = PROVIDER_REGISTRY["kimi-coding"]
- # KIMI_API_KEY is the primary env var; KIMI_CODING_API_KEY is a
- # secondary fallback for Kimi Code sk-kimi- keys so users don't
- # have to overload the same variable.
- assert "KIMI_API_KEY" in pconfig.api_key_env_vars
- assert "KIMI_CODING_API_KEY" in pconfig.api_key_env_vars
- assert pconfig.base_url_env_var == "KIMI_BASE_URL"
-
- def test_minimax_env_vars(self):
- pconfig = PROVIDER_REGISTRY["minimax"]
- assert pconfig.api_key_env_vars == ("MINIMAX_API_KEY",)
- assert pconfig.base_url_env_var == "MINIMAX_BASE_URL"
-
- def test_stepfun_env_vars(self):
- pconfig = PROVIDER_REGISTRY["stepfun"]
- assert pconfig.api_key_env_vars == ("STEPFUN_API_KEY",)
- assert pconfig.base_url_env_var == "STEPFUN_BASE_URL"
-
- def test_minimax_cn_env_vars(self):
- pconfig = PROVIDER_REGISTRY["minimax-cn"]
- assert pconfig.api_key_env_vars == ("MINIMAX_CN_API_KEY",)
- assert pconfig.base_url_env_var == "MINIMAX_CN_BASE_URL"
-
- def test_ai_gateway_env_vars(self):
- pconfig = PROVIDER_REGISTRY["ai-gateway"]
- assert pconfig.api_key_env_vars == ("AI_GATEWAY_API_KEY",)
- assert pconfig.base_url_env_var == "AI_GATEWAY_BASE_URL"
-
- def test_kilocode_env_vars(self):
- pconfig = PROVIDER_REGISTRY["kilocode"]
- assert pconfig.api_key_env_vars == ("KILOCODE_API_KEY",)
- assert pconfig.base_url_env_var == "KILOCODE_BASE_URL"
-
- def test_gmi_env_vars(self):
- pconfig = PROVIDER_REGISTRY["gmi"]
- assert pconfig.api_key_env_vars == ("GMI_API_KEY",)
- assert pconfig.base_url_env_var == "GMI_BASE_URL"
-
- def test_huggingface_env_vars(self):
- pconfig = PROVIDER_REGISTRY["huggingface"]
- assert pconfig.api_key_env_vars == ("HF_TOKEN",)
- assert pconfig.base_url_env_var == "HF_BASE_URL"
-
- def test_base_urls(self):
- assert PROVIDER_REGISTRY["copilot"].inference_base_url == "https://api.githubcopilot.com"
- assert PROVIDER_REGISTRY["copilot-acp"].inference_base_url == "acp://copilot"
- assert PROVIDER_REGISTRY["zai"].inference_base_url == "https://api.z.ai/api/paas/v4"
- assert PROVIDER_REGISTRY["kimi-coding"].inference_base_url == "https://api.moonshot.ai/v1"
- assert PROVIDER_REGISTRY["stepfun"].inference_base_url == STEPFUN_STEP_PLAN_INTL_BASE_URL
- assert PROVIDER_REGISTRY["minimax"].inference_base_url == "https://api.minimax.io/anthropic"
- assert PROVIDER_REGISTRY["minimax-cn"].inference_base_url == "https://api.minimaxi.com/anthropic"
- assert PROVIDER_REGISTRY["ai-gateway"].inference_base_url == "https://ai-gateway.vercel.sh/v1"
- assert PROVIDER_REGISTRY["kilocode"].inference_base_url == "https://api.kilo.ai/api/gateway"
- assert PROVIDER_REGISTRY["gmi"].inference_base_url == "https://api.gmi-serving.com/v1"
- assert PROVIDER_REGISTRY["huggingface"].inference_base_url == "https://router.huggingface.co/v1"
-
- def test_oauth_providers_unchanged(self):
- """Ensure we didn't break the existing OAuth providers."""
- assert "nous" in PROVIDER_REGISTRY
- assert PROVIDER_REGISTRY["nous"].auth_type == "oauth_device_code"
- assert "openai-codex" in PROVIDER_REGISTRY
- assert PROVIDER_REGISTRY["openai-codex"].auth_type == "oauth_external"
-
# =============================================================================
# Provider Resolution tests
@@ -162,20 +60,6 @@ def _clear_provider_env(monkeypatch):
class TestResolveProvider:
"""Test resolve_provider() with new providers."""
- def test_explicit_zai(self):
- assert resolve_provider("zai") == "zai"
-
-
-
-
-
- def test_explicit_ai_gateway(self):
- assert resolve_provider("ai-gateway") == "ai-gateway"
-
- def test_explicit_gmi(self):
- assert resolve_provider("gmi") == "gmi"
-
-
def test_alias_zhipu(self):
assert resolve_provider("zhipu") == "zai"
@@ -192,26 +76,14 @@ class TestResolveProvider:
def test_alias_minimax_underscore(self):
assert resolve_provider("minimax_cn") == "minimax-cn"
- def test_alias_aigateway(self):
- assert resolve_provider("aigateway") == "ai-gateway"
def test_alias_vercel(self):
assert resolve_provider("vercel") == "ai-gateway"
- def test_alias_gmi_cloud(self):
- assert resolve_provider("gmi-cloud") == "gmi"
-
- def test_explicit_kilocode(self):
- assert resolve_provider("kilocode") == "kilocode"
def test_alias_kilo(self):
assert resolve_provider("kilo") == "kilocode"
- def test_alias_kilo_code(self):
- assert resolve_provider("kilo-code") == "kilocode"
-
- def test_alias_kilo_gateway(self):
- assert resolve_provider("kilo-gateway") == "kilocode"
def test_alias_case_insensitive(self):
assert resolve_provider("GLM") == "zai"
@@ -239,24 +111,15 @@ class TestResolveProvider:
def test_alias_github_copilot(self):
assert resolve_provider("github-copilot") == "copilot"
- def test_alias_github_models(self):
- assert resolve_provider("github-models") == "copilot"
def test_alias_github_copilot_acp(self):
assert resolve_provider("github-copilot-acp") == "copilot-acp"
assert resolve_provider("copilot-acp-agent") == "copilot-acp"
- def test_explicit_huggingface(self):
- assert resolve_provider("huggingface") == "huggingface"
def test_alias_hf(self):
assert resolve_provider("hf") == "huggingface"
- def test_alias_hugging_face(self):
- assert resolve_provider("hugging-face") == "huggingface"
-
- def test_alias_huggingface_hub(self):
- assert resolve_provider("huggingface-hub") == "huggingface"
def test_unknown_provider_raises(self):
with pytest.raises(AuthError):
@@ -266,45 +129,16 @@ class TestResolveProvider:
monkeypatch.setenv("GLM_API_KEY", "test-glm-key")
assert resolve_provider("auto") == "zai"
- def test_auto_detects_zai_key(self, monkeypatch):
- monkeypatch.setenv("ZAI_API_KEY", "test-zai-key")
- assert resolve_provider("auto") == "zai"
-
- def test_auto_detects_z_ai_key(self, monkeypatch):
- monkeypatch.setenv("Z_AI_API_KEY", "test-z-ai-key")
- assert resolve_provider("auto") == "zai"
def test_auto_detects_kimi_key(self, monkeypatch):
monkeypatch.setenv("KIMI_API_KEY", "test-kimi-key")
assert resolve_provider("auto") == "kimi-coding"
- def test_auto_detects_stepfun_key(self, monkeypatch):
- monkeypatch.setenv("STEPFUN_API_KEY", "test-stepfun-key")
- assert resolve_provider("auto") == "stepfun"
-
- def test_auto_detects_minimax_key(self, monkeypatch):
- monkeypatch.setenv("MINIMAX_API_KEY", "test-mm-key")
- assert resolve_provider("auto") == "minimax"
def test_auto_detects_minimax_cn_key(self, monkeypatch):
monkeypatch.setenv("MINIMAX_CN_API_KEY", "test-mm-cn-key")
assert resolve_provider("auto") == "minimax-cn"
- def test_auto_detects_ai_gateway_key(self, monkeypatch):
- monkeypatch.setenv("AI_GATEWAY_API_KEY", "test-gw-key")
- assert resolve_provider("auto") == "ai-gateway"
-
- def test_auto_detects_gmi_key(self, monkeypatch):
- monkeypatch.setenv("GMI_API_KEY", "test-gmi-key")
- assert resolve_provider("auto") == "gmi"
-
- def test_auto_detects_kilocode_key(self, monkeypatch):
- monkeypatch.setenv("KILOCODE_API_KEY", "test-kilo-key")
- assert resolve_provider("auto") == "kilocode"
-
- def test_auto_detects_hf_token(self, monkeypatch):
- monkeypatch.setenv("HF_TOKEN", "hf_test_token")
- assert resolve_provider("auto") == "huggingface"
def test_openrouter_takes_priority_over_glm(self, monkeypatch):
"""OpenRouter API key should win over GLM in auto-detection."""
@@ -355,9 +189,6 @@ class TestApiKeyProviderStatus:
class TestResolveApiKeyProviderCredentials:
-
-
-
def test_try_gh_cli_token_uses_homebrew_path_when_not_on_path(self, monkeypatch, tmp_path):
from hermes_cli.copilot_auth import _invalidate_gh_cli_token_cache
from hermes_platform.resolver import known_dirs
@@ -388,7 +219,6 @@ class TestResolveApiKeyProviderCredentials:
assert calls == [[str(gh), "auth", "token"]]
-
def test_resolve_stepfun_with_key(self, monkeypatch):
monkeypatch.setenv("STEPFUN_API_KEY", "stepfun-secret-key")
creds = resolve_api_key_provider_credentials("stepfun")
@@ -397,26 +227,6 @@ class TestResolveApiKeyProviderCredentials:
assert creds["base_url"] == STEPFUN_STEP_PLAN_INTL_BASE_URL
-
-
- def test_resolve_ai_gateway_with_key(self, monkeypatch):
- monkeypatch.setenv("AI_GATEWAY_API_KEY", "gw-secret-key")
- creds = resolve_api_key_provider_credentials("ai-gateway")
- assert creds["provider"] == "ai-gateway"
- assert creds["api_key"] == "gw-secret-key"
- assert creds["base_url"] == "https://ai-gateway.vercel.sh/v1"
-
- def test_resolve_kilocode_with_key(self, monkeypatch):
- monkeypatch.setenv("KILOCODE_API_KEY", "kilo-secret-key")
- creds = resolve_api_key_provider_credentials("kilocode")
- assert creds["provider"] == "kilocode"
- assert creds["api_key"] == "kilo-secret-key"
- assert creds["base_url"] == "https://api.kilo.ai/api/gateway"
-
-
-
-
-
# =============================================================================
# Runtime Provider Resolution tests
# =============================================================================
@@ -433,7 +243,6 @@ class TestRuntimeProviderResolution:
assert "z.ai" in result["base_url"] or "api.z.ai" in result["base_url"]
-
def test_runtime_minimax(self, monkeypatch):
monkeypatch.setenv("MINIMAX_API_KEY", "mm-key")
from hermes_cli.runtime_provider import resolve_runtime_provider
@@ -441,32 +250,6 @@ class TestRuntimeProviderResolution:
assert result["provider"] == "minimax"
assert result["api_key"] == "mm-key"
- def test_runtime_ai_gateway(self, monkeypatch):
- monkeypatch.setenv("AI_GATEWAY_API_KEY", "gw-key")
- from hermes_cli.runtime_provider import resolve_runtime_provider
- result = resolve_runtime_provider(requested="ai-gateway")
- assert result["provider"] == "ai-gateway"
- assert result["api_mode"] == "chat_completions"
- assert result["api_key"] == "gw-key"
- assert "ai-gateway.vercel.sh" in result["base_url"]
-
- def test_runtime_kilocode(self, monkeypatch):
- monkeypatch.setenv("KILOCODE_API_KEY", "kilo-key")
- from hermes_cli.runtime_provider import resolve_runtime_provider
- result = resolve_runtime_provider(requested="kilocode")
- assert result["provider"] == "kilocode"
- assert result["api_mode"] == "chat_completions"
- assert result["api_key"] == "kilo-key"
- assert "kilo.ai" in result["base_url"]
-
- def test_runtime_gmi(self, monkeypatch):
- monkeypatch.setenv("GMI_API_KEY", "gmi-key")
- from hermes_cli.runtime_provider import resolve_runtime_provider
- result = resolve_runtime_provider(requested="gmi")
- assert result["provider"] == "gmi"
- assert result["api_mode"] == "chat_completions"
- assert result["api_key"] == "gmi-key"
- assert result["base_url"] == "https://api.gmi-serving.com/v1"
def test_runtime_auto_detects_api_key_provider(self, monkeypatch):
monkeypatch.setenv("KIMI_API_KEY", "auto-kimi-key")
@@ -530,12 +313,9 @@ class TestRuntimeProviderResolution:
class TestHasAnyProviderConfigured:
-
-
def test_claude_code_creds_ignored_on_fresh_install(self, monkeypatch, tmp_path):
"""Claude Code credentials should NOT skip the wizard when Hermes is unconfigured."""
from hermes_cli import config as config_module
- from hermes_cli.auth import PROVIDER_REGISTRY
hermes_home = tmp_path / ".hermes"
hermes_home.mkdir()
monkeypatch.setattr(config_module, "get_env_path", lambda: hermes_home / ".env")
@@ -586,7 +366,6 @@ class TestHasAnyProviderConfigured:
@staticmethod
def _clear_provider_env(monkeypatch):
"""Clear every provider env var so early checks can't short-circuit."""
- from hermes_cli.auth import PROVIDER_REGISTRY
_all_vars = {"OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY",
"ANTHROPIC_TOKEN", "OPENAI_BASE_URL"}
for pconfig in PROVIDER_REGISTRY.values():
@@ -878,10 +657,6 @@ class TestKimiMoonshotModelListIsolation:
leaked = set(moonshot_models) & coding_plan_only
assert not leaked, f"Moonshot list contains Coding Plan-only models: {leaked}"
- def test_moonshot_list_non_empty(self):
- from hermes_cli.models import _PROVIDER_MODELS
- assert len(_PROVIDER_MODELS["moonshot"]) >= 1
-
# =============================================================================
# Hugging Face provider model list tests
@@ -891,12 +666,6 @@ class TestHuggingFaceModels:
"""Verify Hugging Face model lists are consistent across all locations."""
- def test_model_lists_match(self):
- """Model lists in main.py and models.py should be identical."""
- from hermes_cli.models import _PROVIDER_MODELS as main_models
- from hermes_cli.models import _PROVIDER_MODELS as models_models
- assert main_models["huggingface"] == models_models["huggingface"]
-
def test_model_metadata_has_context_lengths(self):
"""Every HF model should have a context length entry."""
from hermes_cli.models import _PROVIDER_MODELS
@@ -916,18 +685,6 @@ class TestHuggingFaceModels:
class TestNovitaProvider:
"""Tests for NovitaAI — an OpenAI-compatible multi-model aggregator."""
- def test_novita_profile_loads(self):
- from providers import get_provider_profile
- profile = get_provider_profile("novita")
- assert profile is not None
- assert profile.name == "novita"
- assert profile.display_name == "NovitaAI"
- assert profile.base_url == "https://api.novita.ai/openai/v1"
- assert "NOVITA_API_KEY" in profile.env_vars
-
-
-
-
def test_novita_pricing_cache(self, monkeypatch):
"""_fetch_novita_pricing should cache results in _pricing_cache."""
@@ -989,12 +746,6 @@ class TestNovitaProvider:
class TestMinimaxOAuthProvider:
"""Tests for the minimax-oauth OAuth provider."""
- def test_minimax_oauth_in_provider_registry(self):
- assert "minimax-oauth" in PROVIDER_REGISTRY
- pconfig = PROVIDER_REGISTRY["minimax-oauth"]
- assert pconfig.auth_type == "oauth_minimax"
- assert pconfig.id == "minimax-oauth"
-
def test_minimax_oauth_aux_model_registered(self):
# Aux model for the minimax-oauth provider now lives on the
@@ -1035,7 +786,6 @@ def _deepinfra_cache_isolation(monkeypatch):
a later test's fetch within the failure TTL.
"""
import hermes_cli.models as _models_mod
- from hermes_cli import models_pricing
monkeypatch.setattr(_models_mod, "_deepinfra_catalog_cache", {})
monkeypatch.setattr(_models_mod, "_deepinfra_catalog_neg_cache", {})
yield
@@ -1062,7 +812,6 @@ class TestFetchDeepInfraModels:
]}).encode()
import hermes_cli.models as models
- from hermes_cli import models_pricing
monkeypatch.setattr(
models, "_urlopen_model_catalog_request", lambda *a, **kw: _Resp()
)
@@ -1077,10 +826,8 @@ class TestFetchDeepInfraModels:
assert not any("stable-diffusion" in m.lower() for m in result)
-
def test_catalog_uses_credential_safe_opener(self, monkeypatch):
import hermes_cli.models as models
- from hermes_cli import models_pricing
seen = {}
@@ -1106,8 +853,6 @@ class TestFetchDeepInfraModels:
assert seen == {"authorization": "Bearer test-key", "timeout": 5.0}
-
-
def _make_urlopen_returning(payload):
"""Helper: build a urlopen() shim returning a fixed JSON payload."""
import json as _json
@@ -1153,7 +898,6 @@ class TestDeepInfraTagFiltering:
]}
from hermes_cli.models import _fetch_deepinfra_models_by_tag
import hermes_cli.models as _m
- from hermes_cli import models_pricing
for surface in ("chat", "image-gen", "tts", "stt", "embed"):
monkeypatch.setattr(
@@ -1206,7 +950,6 @@ class TestDeepInfraPricingFetcher:
{"id": "vendor/model-image", "metadata": {"tags": ["image-gen"], "pricing": {"per_image_unit": 0.05}}},
]}
import hermes_cli.models as models
- from hermes_cli import models_pricing
monkeypatch.setattr(
models,
"_urlopen_model_catalog_request",
@@ -1230,7 +973,7 @@ class TestDeepInfraProviderProfile:
def test_profile_registered_with_alias_and_aux(self):
from providers import get_provider_profile
from agent.auxiliary_client import _get_aux_model_for_provider
- from hermes_cli.auth import PROVIDER_REGISTRY, resolve_provider
+ from hermes_cli.auth import resolve_provider
from hermes_cli.config import OPTIONAL_ENV_VARS
from hermes_cli.models import CANONICAL_PROVIDERS
@@ -1254,7 +997,6 @@ class TestDeepInfraProviderProfile:
assert isinstance(profile.fallback_models, tuple)
-
class TestRuntimeAlibabaRegionalAndTokenPlan:
"""#73265: the catalog-advertised Alibaba China/Token Plan variants must
resolve on the shared execution path (resolve_runtime_provider), not just
diff --git a/tests/hermes_cli/test_approvals_command.py b/tests/hermes_cli/test_approvals_command.py
index 470869b6164..bdb1aab563d 100644
--- a/tests/hermes_cli/test_approvals_command.py
+++ b/tests/hermes_cli/test_approvals_command.py
@@ -1,11 +1,6 @@
"""Cross-surface contract for the persistent /approvals mode command."""
-from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
-import yaml
-
-from cli import HermesCLI
from hermes_cli.commands import GATEWAY_KNOWN_COMMANDS, SUBCOMMANDS, gateway_help_lines, resolve_command
from hermes_cli.commands_completion import SlashCommandCompleter
from hermes_cli.commands_platforms import telegram_bot_commands
@@ -25,8 +20,6 @@ def _completions(text: str) -> set[str]:
def test_approvals_registry_drives_help_menu_and_autocomplete():
command = resolve_command("approvals")
assert command is not None
- assert command.category == "Configuration"
- assert command.args_hint == "[manual|smart|off]"
assert SUBCOMMANDS["/approvals"] == ["manual", "smart", "off"]
assert "approvals" in GATEWAY_KNOWN_COMMANDS
assert any("/approvals" in line for line in gateway_help_lines())
@@ -34,21 +27,6 @@ def test_approvals_registry_drives_help_menu_and_autocomplete():
assert _completions("/approvals ") == {"manual", "smart", "off"}
-def _isolate_config(monkeypatch, home):
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.setenv("HERMES_MANAGED_DIR", str(home / "missing-managed"))
- from hermes_cli import managed_scope
- from hermes_cli.config import _LOAD_CONFIG_CACHE, _RAW_CONFIG_CACHE
-
- _LOAD_CONFIG_CACHE.clear()
- _RAW_CONFIG_CACHE.clear()
- managed_scope.invalidate_managed_cache()
-
-
-
-
-
-
def test_shared_command_refuses_managed_mode_override(tmp_path, monkeypatch):
from hermes_cli import managed_scope
from hermes_cli.approval_mode import run_approval_mode_command
@@ -71,7 +49,3 @@ def test_shared_command_refuses_managed_mode_override(tmp_path, monkeypatch):
assert not (home / "config.yaml").exists()
-
-
-
-
diff --git a/tests/hermes_cli/test_approvals_suggest.py b/tests/hermes_cli/test_approvals_suggest.py
index 13c6a909b21..a59a61e96b7 100644
--- a/tests/hermes_cli/test_approvals_suggest.py
+++ b/tests/hermes_cli/test_approvals_suggest.py
@@ -23,9 +23,7 @@ from hermes_cli.approvals_suggest import (
apply_proposals,
build_proposals,
derive_glob,
- is_unsafe_class,
normalize_command,
- parse_apply_indices,
scan_approval_history,
suggest_command,
)
@@ -143,7 +141,6 @@ class TestScan:
assert len(scan_approval_history(path, days=0)) == 2
-
# ---------------------------------------------------------------------------
# Normalize / glob derivation
# ---------------------------------------------------------------------------
@@ -194,10 +191,6 @@ class TestRankingAndSafety:
assert len(build_proposals(records, min_count=1)) == 1
-
-
-
-
# ---------------------------------------------------------------------------
# Credential masking in rendered proposals
# ---------------------------------------------------------------------------
@@ -293,7 +286,6 @@ class TestApply:
assert "git push *" in out and "docker restart *" in out
-
class TestJsonOutput:
def test_json_proposal_output(self, db_path, isolated_allowlist, capsys):
path, con = db_path
@@ -346,5 +338,3 @@ class TestParserWiring:
args = parser.parse_args(["approvals", "suggest"])
assert args.apply_indices is None
assert args.json is False
- assert args.days == 90
- assert args.min_count == 2
diff --git a/tests/hermes_cli/test_approvals_test.py b/tests/hermes_cli/test_approvals_test.py
index c67d967b126..ac4b0c13fdb 100644
--- a/tests/hermes_cli/test_approvals_test.py
+++ b/tests/hermes_cli/test_approvals_test.py
@@ -18,7 +18,6 @@ import pytest
import tools.approval as A
import tools.approval_prompt as approval_prompt
from tools import approval_context
-from tools import approval_detection, approval_floors
from hermes_cli import approvals_test as at
@@ -127,33 +126,6 @@ class TestNormalizationParity:
assert rc == 0
assert "git status" in out
- def test_composes_real_runtime_detectors(self, isolated_approvals, capsys,
- monkeypatch):
- """Prove the tester calls the real evaluators, not a reimplementation."""
- calls = {}
-
- def _spy(name, real):
- def wrapper(c):
- calls[name] = c
- return real(c)
- return wrapper
-
- monkeypatch.setattr(approval_detection, "detect_hardline_command",
- _spy("hardline", approval_detection.detect_hardline_command))
- monkeypatch.setattr(approval_detection, "detect_dangerous_command",
- _spy("dangerous", approval_detection.detect_dangerous_command))
- monkeypatch.setattr(approval_floors, "_match_user_deny_rule",
- _spy("deny", approval_floors._match_user_deny_rule))
- monkeypatch.setattr(approval_detection, "_command_detection_variants",
- _spy("variants", approval_detection._command_detection_variants))
- cmd = "rm -rf ~/project/build"
- at.approvals_test_command(_args(cmd.split()))
- capsys.readouterr()
- assert calls.get("hardline") == cmd
- assert calls.get("dangerous") == cmd
- assert calls.get("deny") == cmd
- assert calls.get("variants") == cmd
-
class TestReadOnly:
def test_nothing_executed(self, isolated_approvals, capsys, tmp_path):
@@ -179,7 +151,7 @@ class TestOutputAndWiring:
assert rc == 3
assert payload["verdict"] == "hardline-deny"
assert payload["exit_code"] == 3
- assert payload["rule"] == "system shutdown/reboot"
+ assert payload["rule"]
assert payload["command"] == "sudo re" + "boot"
assert isinstance(payload["normalized_variants"], list)
diff --git a/tests/hermes_cli/test_arcee_provider.py b/tests/hermes_cli/test_arcee_provider.py
index 5b58fc38a64..c933c356aad 100644
--- a/tests/hermes_cli/test_arcee_provider.py
+++ b/tests/hermes_cli/test_arcee_provider.py
@@ -27,15 +27,6 @@ _OTHER_PROVIDER_KEYS = (
# =============================================================================
-class TestArceeProviderRegistry:
- def test_registered(self):
- assert "arcee" in PROVIDER_REGISTRY
-
-
- def test_inference_base_url(self):
- assert PROVIDER_REGISTRY["arcee"].inference_base_url == "https://api.arcee.ai/api/v1"
-
-
# =============================================================================
# Aliases
# =============================================================================
@@ -79,7 +70,7 @@ class TestArceeCredentials:
monkeypatch.delenv("ARCEE_BASE_URL", raising=False)
creds = resolve_api_key_provider_credentials("arcee")
assert creds["api_key"] == "arc-direct-key"
- assert creds["base_url"] == "https://api.arcee.ai/api/v1"
+ assert creds["base_url"] == PROVIDER_REGISTRY["arcee"].inference_base_url
# =============================================================================
@@ -87,30 +78,12 @@ class TestArceeCredentials:
# =============================================================================
-class TestArceeModelCatalog:
- def test_static_model_list(self):
- """Arcee has a static _PROVIDER_MODELS catalog entry. Specific model
- names change with releases and don't belong in tests.
- """
- from hermes_cli.models import _PROVIDER_MODELS
- assert "arcee" in _PROVIDER_MODELS
- assert len(_PROVIDER_MODELS["arcee"]) >= 1
-
- def test_canonical_provider_entry(self):
- from hermes_cli.models import CANONICAL_PROVIDERS
- slugs = [p.slug for p in CANONICAL_PROVIDERS]
- assert "arcee" in slugs
-
-
# =============================================================================
# Model normalization
# =============================================================================
class TestArceeNormalization:
- def test_in_matching_prefix_strip_set(self):
- from hermes_cli.model_normalize import _MATCHING_PREFIX_STRIP_PROVIDERS
- assert "arcee" in _MATCHING_PREFIX_STRIP_PROVIDERS
def test_bare_name_unchanged(self):
@@ -125,11 +98,6 @@ class TestArceeNormalization:
class TestArceeURLMapping:
- def test_provider_prefixes(self):
- from agent.model_metadata import _PROVIDER_PREFIXES
- assert "arcee" in _PROVIDER_PREFIXES
- assert "arcee-ai" in _PROVIDER_PREFIXES
- assert "arceeai" in _PROVIDER_PREFIXES
def test_trajectory_compressor_detects_arcee(self):
import trajectory_compressor as tc
@@ -143,16 +111,6 @@ class TestArceeURLMapping:
# =============================================================================
-class TestArceeProvidersModule:
- def test_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
- assert "arcee" in HERMES_OVERLAYS
- overlay = HERMES_OVERLAYS["arcee"]
- assert overlay.transport == "openai_chat"
- assert overlay.base_url_env_var == "ARCEE_BASE_URL"
- assert not overlay.is_aggregator
-
-
# =============================================================================
# Auxiliary client — main-model-first design
# =============================================================================
diff --git a/tests/hermes_cli/test_argparse_flag_propagation.py b/tests/hermes_cli/test_argparse_flag_propagation.py
index cf7dad4ef16..2c01ac95092 100644
--- a/tests/hermes_cli/test_argparse_flag_propagation.py
+++ b/tests/hermes_cli/test_argparse_flag_propagation.py
@@ -12,50 +12,11 @@ so the subparser only sets the attribute when the user explicitly provides it.
"""
import argparse
-import os
import sys
import pytest
-def _build_parser():
- """Build the hermes argument parser from the real code.
-
- We import the real main() and extract the parser it builds.
- Since main() is a large function that does much more than parse args,
- we replicate just the parser structure here to avoid side effects.
- """
- parser = argparse.ArgumentParser(prog="hermes")
- parser.add_argument("--resume", "-r", metavar="SESSION", default=None)
- parser.add_argument(
- "--continue", "-c", dest="continue_last", nargs="?",
- const=True, default=None, metavar="SESSION_NAME",
- )
- parser.add_argument("--worktree", "-w", action="store_true", default=False)
- parser.add_argument("--skills", "-s", action="append", default=None)
- parser.add_argument("--yolo", action="store_true", default=False)
- parser.add_argument("--pass-session-id", action="store_true", default=False)
-
- subparsers = parser.add_subparsers(dest="command")
- chat = subparsers.add_parser("chat")
- # These MUST use argparse.SUPPRESS to avoid overwriting parent values
- chat.add_argument("--yolo", action="store_true",
- default=argparse.SUPPRESS)
- chat.add_argument("--worktree", "-w", action="store_true",
- default=argparse.SUPPRESS)
- chat.add_argument("--skills", "-s", action="append",
- default=argparse.SUPPRESS)
- chat.add_argument("--pass-session-id", action="store_true",
- default=argparse.SUPPRESS)
- chat.add_argument("--resume", "-r", metavar="SESSION_ID",
- default=argparse.SUPPRESS)
- chat.add_argument(
- "--continue", "-c", dest="continue_last", nargs="?",
- const=True, default=argparse.SUPPRESS, metavar="SESSION_NAME",
- )
- return parser
-
-
class TestChatVerboseArg:
"""Verify chat --verbose preserves config fallback when absent."""
@@ -102,30 +63,6 @@ class TestChatVerboseArg:
assert "verbose" not in captured
-class TestYoloEnvVar:
- """Verify --yolo sets HERMES_YOLO_MODE regardless of flag position.
-
- This tests the actual cmd_chat logic pattern (getattr → os.environ).
- """
-
- @pytest.fixture(autouse=True)
- def _clean_env(self):
- os.environ.pop("HERMES_YOLO_MODE", None)
- yield
- os.environ.pop("HERMES_YOLO_MODE", None)
-
- def _simulate_cmd_chat_yolo_check(self, args):
- """Replicate the exact check from cmd_chat in main.py."""
- if getattr(args, "yolo", False):
- os.environ["HERMES_YOLO_MODE"] = "1"
-
- def test_yolo_before_chat_sets_env(self):
- parser = _build_parser()
- args = parser.parse_args(["--yolo", "chat"])
- self._simulate_cmd_chat_yolo_check(args)
- assert os.environ.get("HERMES_YOLO_MODE") == "1"
-
-
class TestAcceptHooksOnAgentSubparsers:
"""Verify --accept-hooks is accepted at every agent-subcommand
position (before the subcommand, between group/subcommand, and
@@ -223,8 +160,6 @@ class TestChatSubparserInheritedValueFlags:
return parser
-
-
def test_all_three_flags_before_chat(self, real_parser):
"""Issue #28780 reporter's case generalized: passing every inherited
value flag before `chat` must preserve all of them simultaneously."""
diff --git a/tests/hermes_cli/test_atomic_json_write.py b/tests/hermes_cli/test_atomic_json_write.py
index 2ed2dddb7aa..8346f336498 100644
--- a/tests/hermes_cli/test_atomic_json_write.py
+++ b/tests/hermes_cli/test_atomic_json_write.py
@@ -1,8 +1,6 @@
"""Tests for utils.atomic_json_write — crash-safe JSON file writes."""
import json
-import os
-from pathlib import Path
from unittest.mock import patch
import pytest
@@ -14,11 +12,6 @@ class TestAtomicJsonWrite:
"""Core atomic write behavior."""
-
-
-
-
-
def test_cleans_up_temp_file_on_baseexception(self, tmp_path):
class SimulatedAbort(BaseException):
pass
@@ -36,29 +29,6 @@ class TestAtomicJsonWrite:
assert json.loads(target.read_text(encoding="utf-8")) == original
-
-
- def test_mode_does_not_crash_without_fchmod(self, tmp_path):
- """Regression: os.fchmod is Unix-only and absent on Windows. Passing a
- mode must not raise AttributeError when fchmod is unavailable.
-
- Simulates the Windows os module by removing fchmod from the namespace.
- Previously this crashed in `hermes memory setup` while saving the
- Hindsight config with mode=0o600 (GitHub: Windows setup traceback).
- """
- import utils
-
- target = tmp_path / "secret.json"
- no_fchmod = {k: getattr(os, k) for k in dir(os) if k != "fchmod"}
- fake_os = type("FakeOs", (), no_fchmod)
- assert not hasattr(fake_os, "fchmod")
-
- with patch.object(utils, "os", fake_os):
- atomic_json_write(target, {"api_key": "secret"}, mode=0o600)
-
- assert json.loads(target.read_text(encoding="utf-8")) == {"api_key": "secret"}
-
-
def test_concurrent_writes_dont_corrupt(self, tmp_path):
"""Multiple rapid writes should each produce valid JSON."""
import threading
diff --git a/tests/hermes_cli/test_audio_playback_guard.py b/tests/hermes_cli/test_audio_playback_guard.py
index 4250be844ac..524c3f65a4d 100644
--- a/tests/hermes_cli/test_audio_playback_guard.py
+++ b/tests/hermes_cli/test_audio_playback_guard.py
@@ -32,7 +32,6 @@ import os
import sys
import types
-import pytest
from tui_gateway import server
@@ -108,19 +107,3 @@ def test_voice_env_does_not_leak_into_the_next_test():
assert server._voice_mode_enabled() is False
-def test_guard_can_be_opted_out_of_explicitly():
- """The stub is a guard, not a lobotomy — the real function is reachable."""
- import hermes_cli.voice as voice
-
- assert voice.speak_text.__name__ == "_blocked_speak_text"
-
-
[email protected]_audio_playback
-def test_bypass_marker_restores_the_real_speak_text():
- """``@pytest.mark.real_audio_playback`` hands back the real primitive.
-
- Asserts identity only — it does not call it, which would speak aloud.
- """
- import hermes_cli.voice as voice
-
- assert voice.speak_text.__name__ == "speak_text"
diff --git a/tests/hermes_cli/test_auth_codex_bounded_body.py b/tests/hermes_cli/test_auth_codex_bounded_body.py
index 2c35d481b58..0aca376d38f 100644
--- a/tests/hermes_cli/test_auth_codex_bounded_body.py
+++ b/tests/hermes_cli/test_auth_codex_bounded_body.py
@@ -51,7 +51,6 @@ def test_oversized_200_auth_body_is_rejected_before_being_buffered(monkeypatch):
with pytest.raises(AuthError) as excinfo:
auth_codex.refresh_codex_oauth_pure("old-at", "old-rt")
assert excinfo.value.code == "codex_auth_response_too_large"
- assert "exceeded 1024 KiB" in str(excinfo.value)
# Stopped within one chunk of the cap, not the full 3 MiB.
assert auth_codex._CODEX_AUTH_BODY_MAX_BYTES < pulled[0] <= auth_codex._CODEX_AUTH_BODY_MAX_BYTES + 65536
diff --git a/tests/hermes_cli/test_auth_codex_browser_login.py b/tests/hermes_cli/test_auth_codex_browser_login.py
index e9c9e9d71d8..7124189df95 100644
--- a/tests/hermes_cli/test_auth_codex_browser_login.py
+++ b/tests/hermes_cli/test_auth_codex_browser_login.py
@@ -114,7 +114,7 @@ def test_browser_flag_runs_loopback_pkce_and_stores_loopback_source(tmp_path, mo
assert token["redirect_uri"] == authorize["redirect_uri"] and token["client_id"] == authorize["client_id"]
-def test_default_is_device_code_and_busy_callback_port_falls_back(tmp_path, monkeypatch, capsys):
+def test_default_is_device_code_and_busy_callback_port_falls_back(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
(tmp_path / "hermes").mkdir()
(tmp_path / "hermes" / "auth.json").write_text(json.dumps({"version": 1, "providers": {}}))
@@ -145,7 +145,5 @@ def test_default_is_device_code_and_busy_callback_port_falls_back(tmp_path, monk
monkeypatch.setattr(browser_mod, "CODEX_BROWSER_CALLBACK_PORT", occupant.getsockname()[1])
auth_add_command(_args(browser=True, label="second"))
assert device_logins == [1, 1] and bind_attempts == [1]
- out = capsys.readouterr().out
- assert "already in use" in out and "falling back to the device-code login" in out
sources = [e["source"] for e in json.loads((tmp_path / "hermes" / "auth.json").read_text())["credential_pool"]["openai-codex"]]
assert sources == ["manual:device_code", "manual:device_code"]
diff --git a/tests/hermes_cli/test_auth_codex_provider.py b/tests/hermes_cli/test_auth_codex_provider.py
index 27cc91f1754..12ad0af0f32 100644
--- a/tests/hermes_cli/test_auth_codex_provider.py
+++ b/tests/hermes_cli/test_auth_codex_provider.py
@@ -1,8 +1,6 @@
"""Tests for Codex auth — tokens stored in Hermes auth store (~/.hermes/auth.json)."""
import json
-import time
-import base64
from pathlib import Path
from types import SimpleNamespace
@@ -11,14 +9,10 @@ import pytest
from hermes_cli.auth import (
AuthError,
DEFAULT_CODEX_BASE_URL,
- PROVIDER_REGISTRY,
_read_codex_tokens,
_save_codex_tokens,
- _import_codex_cli_tokens,
- _login_openai_codex,
refresh_codex_oauth_pure,
resolve_codex_runtime_credentials,
- resolve_provider,
)
@@ -44,16 +38,6 @@ def _setup_hermes_auth(hermes_home: Path, *, access_token: str = "access", refre
return auth_file
-def _jwt_with_exp(exp_epoch: int) -> str:
- payload = {"exp": exp_epoch}
- encoded = base64.urlsafe_b64encode(json.dumps(payload).encode("utf-8")).rstrip(b"=").decode("utf-8")
- return f"h.{encoded}.s"
-
-
-
-
-
-
def test_resolve_codex_runtime_credentials_missing_access_token(tmp_path, monkeypatch):
hermes_home = tmp_path / "hermes"
_setup_hermes_auth(hermes_home, access_token="")
@@ -104,8 +88,6 @@ def test_resolve_codex_runtime_credentials_falls_back_to_pool_when_singleton_emp
assert resolved["base_url"] # default codex backend URL
-
-
def test_save_codex_tokens_syncs_credential_pool(tmp_path, monkeypatch):
"""Re-auth must update the credential_pool device_code entry, not just providers.
@@ -278,105 +260,6 @@ def test_save_codex_tokens_syncs_manual_device_code_entries(tmp_path, monkeypatc
assert "refresh_token" not in api_key or api_key.get("refresh_token") is None
-def test_save_codex_tokens_does_not_overwrite_independent_manual_entries(tmp_path, monkeypatch):
- """Re-auth must NOT overwrite ``manual:device_code`` entries that hold
- independent token material (different OpenAI/ChatGPT accounts).
-
- Regression for #39236: ``hermes auth add openai-codex`` for accounts B and C
- routes through ``_save_codex_tokens`` because the singleton path is the
- only Codex OAuth save flow. The #33538 fix refreshed every
- ``manual:device_code`` entry on every re-auth, which works fine for the
- one-account/legacy-workaround case but silently overwrote distinct
- independent accounts with the latest-authenticated tokens (labels
- preserved, token material clobbered, status/quota readings then lie).
-
- The safe invariant: an entry is a singleton-alias only when its current
- access_token matches the *previous* singleton access_token. Manual
- entries whose tokens never matched the singleton are independent accounts
- and must be left alone.
- """
- hermes_home = tmp_path / "hermes"
- hermes_home.mkdir(parents=True, exist_ok=True)
- (hermes_home / "auth.json").write_text(json.dumps({
- "version": 1,
- "providers": {
- "openai-codex": {
- # Old singleton tokens — represent "account A" which the user
- # logged in with via setup originally.
- "tokens": {"access_token": "acctA-at", "refresh_token": "acctA-rt"},
- "last_refresh": "2026-01-01T00:00:00Z",
- "auth_mode": "chatgpt",
- "label": "account-A",
- },
- },
- "credential_pool": {
- "openai-codex": [
- # The seeded singleton mirror of account A.
- {
- "id": "seeded",
- "label": "account-A",
- "source": "device_code",
- "auth_type": "oauth",
- "access_token": "acctA-at",
- "refresh_token": "acctA-rt",
- },
- # Two INDEPENDENT manual entries added later via
- # ``hermes auth add openai-codex`` (account B and account C).
- # Each has its OWN distinct token material, unrelated to the
- # singleton.
- {
- "id": "acctB",
- "label": "account-B",
- "source": "manual:device_code",
- "auth_type": "oauth",
- "access_token": "acctB-at",
- "refresh_token": "acctB-rt",
- },
- {
- "id": "acctC",
- "label": "account-C",
- "source": "manual:device_code",
- "auth_type": "oauth",
- "access_token": "acctC-at",
- "refresh_token": "acctC-rt",
- },
- ],
- },
- }))
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- # User re-authenticates account A — fresh device-code login produces new
- # tokens. The legitimate update is the seeded singleton mirror; the
- # independent acctB/acctC entries must be untouched.
- _save_codex_tokens(
- {"access_token": "acctA-new-at", "refresh_token": "acctA-new-rt"},
- last_refresh="2026-06-05T00:00:00Z",
- )
-
- auth = json.loads((hermes_home / "auth.json").read_text())
- pool = auth["credential_pool"]["openai-codex"]
-
- # Singleton-seeded entry: refreshed (legitimate sync).
- seeded = next(e for e in pool if e["source"] == "device_code")
- assert seeded["access_token"] == "acctA-new-at"
- assert seeded["refresh_token"] == "acctA-new-rt"
- assert seeded["last_refresh"] == "2026-06-05T00:00:00Z"
-
- # acctB: INDEPENDENT entry — must NOT be overwritten.
- acctB = next(e for e in pool if e["id"] == "acctB")
- assert acctB["access_token"] == "acctB-at", (
- "acctB was clobbered by acctA re-auth (#39236 regression)"
- )
- assert acctB["refresh_token"] == "acctB-rt"
-
- # acctC: INDEPENDENT entry — must NOT be overwritten.
- acctC = next(e for e in pool if e["id"] == "acctC")
- assert acctC["access_token"] == "acctC-at", (
- "acctC was clobbered by acctA re-auth (#39236 regression)"
- )
- assert acctC["refresh_token"] == "acctC-rt"
-
-
def test_save_codex_tokens_clears_error_markers_only_on_refreshed_entries(tmp_path, monkeypatch):
"""Error markers must be cleared only on entries that were actually
refreshed by this re-auth. Independent ``manual:device_code`` entries
@@ -442,8 +325,6 @@ def test_save_codex_tokens_clears_error_markers_only_on_refreshed_entries(tmp_pa
assert acctB["last_error_reason"] == "quota_exhausted"
-
-
def test_codex_tokens_not_written_to_shared_file(tmp_path, monkeypatch):
"""Verify _save_codex_tokens writes only to Hermes auth store, not ~/.codex/."""
hermes_home = tmp_path / "hermes"
@@ -510,8 +391,6 @@ def _patch_httpx(monkeypatch, response):
monkeypatch.setattr("hermes_cli.auth.httpx.Client", _factory)
-
-
def test_refresh_429_classified_as_quota_not_auth_failure(monkeypatch):
"""429 from the token endpoint is a usage-quota cap, not an auth failure.
@@ -539,7 +418,6 @@ def test_refresh_429_classified_as_quota_not_auth_failure(monkeypatch):
assert err.code == CODEX_RATE_LIMITED_CODE
assert err.relogin_required is False
assert is_rate_limited_auth_error(err) is True
- assert "retry after 120s" in str(err)
# User-facing copy must not tell the operator to re-authenticate.
rendered = format_auth_error(err)
assert "re-authenticate" not in rendered
@@ -559,58 +437,6 @@ def test_refresh_429_without_retry_after_header(monkeypatch):
err = exc_info.value
assert err.code == CODEX_RATE_LIMITED_CODE
assert err.relogin_required is False
- assert "quota exhausted" in str(err).lower()
-
-
-def test_is_rate_limited_auth_error_distinguishes_credential_errors():
- """Missing/expired credentials must NOT be treated as rate-limit errors."""
- from hermes_cli.auth import CODEX_RATE_LIMITED_CODE, is_rate_limited_auth_error
-
- rate_limited = AuthError(
- "quota", provider="openai-codex", code=CODEX_RATE_LIMITED_CODE, relogin_required=False
- )
- missing_creds = AuthError(
- "No Codex credentials stored.",
- provider="openai-codex",
- code="codex_auth_missing",
- relogin_required=True,
- )
- assert is_rate_limited_auth_error(rate_limited) is True
- assert is_rate_limited_auth_error(missing_creds) is False
- assert is_rate_limited_auth_error(ValueError("nope")) is False
-
-
-
-
-class _FakeResp:
- def __init__(self, status_code, json_data=None, headers=None):
- self.status_code = status_code
- self._json = json_data or {}
- self.headers = headers or {}
-
- def json(self):
- return self._json
-
-
-def _patch_httpx_post(monkeypatch, responses):
- """Patch hermes_cli.auth.httpx.Client so .post() returns queued responses."""
- seq = iter(responses)
-
- class _FakeClient:
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- def post(self, *args, **kwargs):
- return next(seq)
-
- monkeypatch.setattr("hermes_cli.auth.httpx.Client", lambda *a, **k: _FakeClient())
-
-
-
-
def test_pool_only_force_refresh_rotates_the_pool_entry(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_auth_commands.py b/tests/hermes_cli/test_auth_commands.py
index df411db9ff9..1c21d27d278 100644
--- a/tests/hermes_cli/test_auth_commands.py
+++ b/tests/hermes_cli/test_auth_commands.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import base64
import json
import time
-from datetime import datetime, timezone
from unittest.mock import patch
import pytest
@@ -116,29 +115,6 @@ def test_auth_add_api_key_persists_manual_entry(tmp_path, monkeypatch):
assert entry["access_token"] == "sk-or-manual"
-def test_auth_add_configured_provider_uses_canonical_pool_key(tmp_path, monkeypatch):
- """A keyed providers row must keep its runtime slug in the auth pool."""
- hermes_home = tmp_path / "hermes"
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- monkeypatch.delenv("GROQ_API_KEY", raising=False)
- _write_auth_store(tmp_path, {"version": 1, "providers": {}})
- _write_groq_provider_config(tmp_path)
-
- from hermes_cli.auth_commands import auth_add_command
-
- class _Args:
- provider = "groq"
- auth_type = "api-key"
- api_key = "gsk-test"
- label = "primary"
-
- auth_add_command(_Args())
-
- payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
- assert "groq" in payload["credential_pool"]
- assert "custom:groq" not in payload["credential_pool"]
-
-
def test_auth_add_migrates_legacy_prefixed_key_for_configured_provider(
tmp_path, monkeypatch
):
@@ -218,7 +194,7 @@ def test_auth_add_migrates_display_name_derived_legacy_pool_key(
api_key = "gsk-new"
label = "new"
- with patch("hermes_cli.models.clear_provider_models_cache") as clear_cache:
+ with patch("hermes_cli.models.clear_provider_models_cache"):
auth_add_command(_Args())
payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
@@ -227,7 +203,6 @@ def test_auth_add_migrates_display_name_derived_legacy_pool_key(
entry["access_token"]
for entry in payload["credential_pool"]["groq-cloud"]
} == {"gsk-legacy", "gsk-new"}
- clear_cache.assert_called_once_with("custom:groq")
def test_auth_add_non_registry_configured_provider_preserves_endpoint(
@@ -291,66 +266,7 @@ def test_auth_list_includes_non_registry_configured_provider(
auth_list_command(type("Args", (), {"provider": None})())
- assert "private-groq (1 credentials):" in capsys.readouterr().out
-
-
-def test_auth_list_shows_entry_id_and_priority(tmp_path, monkeypatch, capsys):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- _write_auth_store(
- tmp_path,
- {
- "version": 1,
- "providers": {},
- "credential_pool": {
- "openrouter": [
- {
- "id": "ab12cd",
- "label": "primary",
- "auth_type": "api_key",
- "priority": 0,
- "source": "manual",
- "access_token": "secret-1",
- },
- {
- "id": "ef56gh",
- "label": "backup",
- "auth_type": "api_key",
- "priority": 1,
- "source": "manual",
- "access_token": "secret-2",
- },
- ]
- },
- },
- )
-
- from hermes_cli.auth_commands import auth_list_command
-
- auth_list_command(type("Args", (), {"provider": "openrouter"})())
-
- out = capsys.readouterr().out
- assert "id=ab12cd priority=0" in out
- assert "id=ef56gh priority=1" in out
-
-
-def test_interactive_auth_add_accepts_non_registry_configured_provider(
- tmp_path, monkeypatch
-):
- hermes_home = tmp_path / "hermes"
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- _write_auth_store(tmp_path, {"version": 1, "providers": {}})
- _write_groq_provider_config(tmp_path, provider_key="private-groq")
-
- from hermes_cli import auth_commands
-
- monkeypatch.setattr(auth_commands, "_pick_provider", lambda _prompt: "private-groq")
- monkeypatch.setattr(auth_commands, "line_input", lambda _prompt: "private")
- monkeypatch.setattr(auth_commands, "masked_secret_prompt", lambda _prompt: "private-key")
-
- auth_commands._interactive_add()
-
- payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
- assert payload["credential_pool"]["private-groq"][0]["access_token"] == "private-key"
+ assert "private-groq" in capsys.readouterr().out
def test_interactive_auth_add_normalizes_display_name_to_provider_key(
@@ -648,17 +564,11 @@ def test_auth_add_codex_warns_when_login_is_same_account_as_pooled_entry(tmp_pat
from agent.credential_pool import load_pool
err = _add_codex_twice(tmp_path, monkeypatch, capsys, _codex_jwt("[email protected]", "acct-A", "user-1"))
- assert "same OpenAI account as openai-codex credential #1" in err
- assert '"[email protected]"' in err and "hermes auth remove openai-codex 1" in err
+ assert "[email protected]" in err
# The warning informs; it never blocks the add.
assert len(load_pool("openai-codex").entries()) == 2
-def test_auth_add_codex_stays_quiet_for_a_different_account(tmp_path, monkeypatch, capsys):
- err = _add_codex_twice(tmp_path, monkeypatch, capsys, _codex_jwt("[email protected]", "acct-B", "user-2"))
- assert "same OpenAI account" not in err
-
-
def test_codex_auth_status_reports_pool_only_credential(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
_write_auth_store(tmp_path, _codex_pool_only_store())
@@ -684,61 +594,6 @@ def test_codex_runtime_pool_only_rate_limit_is_not_missing_auth(tmp_path, monkey
assert exc_info.value.relogin_required is False
-def test_auth_add_xai_oauth_sets_active_provider(tmp_path, monkeypatch):
- """hermes auth add xai-oauth must set active_provider and write a pool entry.
-
- Regression history:
- - Early path called ``pool.add_entry()`` without ``active_provider``, so
- the setup wizard reported "No inference provider configured".
- - Intermediate path fixed that by routing through ``_save_xai_oauth_tokens``
- (singleton), which set active_provider but collapsed multi-account adds.
- - Current path mirrors openai-codex: pool-only ``manual:device_code`` entry
- plus ``mark_provider_active_if_unset`` on first add.
- """
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- _write_auth_store(tmp_path, {"version": 1, "providers": {}})
- access_token = "xai-test-access-token"
- monkeypatch.setattr(
- "hermes_cli.auth._xai_oauth_device_code_login",
- lambda **kwargs: {
- "tokens": {
- "access_token": access_token,
- "refresh_token": "xai-refresh-token",
- "id_token": "",
- "token_type": "Bearer",
- },
- "discovery": {"token_endpoint": "https://auth.x.ai/token"},
- "redirect_uri": "",
- "base_url": "https://api.x.ai/v1",
- "last_refresh": "2026-06-02T10:00:00Z",
- "source": "oauth-device-code",
- },
- )
-
- from hermes_cli.auth_commands import auth_add_command
-
- class _Args:
- provider = "xai-oauth"
- auth_type = "oauth"
- api_key = None
- label = None
- timeout = None
- no_browser = False
-
- auth_add_command(_Args())
-
- payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
- # active_provider must be set — the core of the original regression
- assert payload["active_provider"] == "xai-oauth"
- # Pool-only multi-account path: no providers.xai-oauth singleton write
- assert "xai-oauth" not in payload.get("providers", {})
- entries = payload["credential_pool"]["xai-oauth"]
- entry = next(item for item in entries if item["source"] == "manual:device_code")
- assert entry["access_token"] == access_token
- assert entry["refresh_token"] == "xai-refresh-token"
- assert entry["base_url"] == "https://api.x.ai/v1"
-
-
def test_auth_add_xai_oauth_keeps_distinct_pool_accounts(tmp_path, monkeypatch):
"""Two ``hermes auth add xai-oauth`` runs must produce independent pool entries.
@@ -978,15 +833,11 @@ def test_logout_resets_codex_config_when_auth_state_already_cleared(tmp_path, mo
logout_command(SimpleNamespace(provider="openai-codex"))
- out = capsys.readouterr().out
- assert "Logged out of OpenAI Codex." in out
config_text = (hermes_home / "config.yaml").read_text()
assert "provider: auto" in config_text
assert "base_url: https://openrouter.ai/api/v1" in config_text
-
-
def test_unsuppress_credential_source_clears_marker(tmp_path, monkeypatch):
"""unsuppress_credential_source() removes a previously-set marker."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
@@ -1024,8 +875,6 @@ def test_unsuppress_credential_source_preserves_other_markers(tmp_path, monkeypa
assert is_source_suppressed("anthropic", "claude_code") is True
-
-
# =============================================================================
# Unified credential-source stickiness — every source Hermes reads from has a
# registered RemovalStep in agent.credential_sources, and every seeding path
@@ -1063,61 +912,6 @@ def test_seed_from_singletons_respects_hermes_pkce_suppression(tmp_path, monkeyp
assert "hermes_pkce" not in active
-
-
-def test_credential_sources_registry_has_expected_steps():
- """Sanity check — the registry contains the expected RemovalSteps.
-
- Adding a new credential source is routine, so this is a structural
- invariant check (every step has a description, every step is unique,
- core steps are present) rather than a frozen snapshot. Frozen
- snapshots of catalog-like data violate the AGENTS.md "don't write
- change-detector tests" rule — they break every time someone adds a
- provider.
- """
- from agent.credential_sources import _REGISTRY
-
- descriptions = [step.description for step in _REGISTRY]
- # No empty descriptions, no duplicates.
- assert all(d for d in descriptions), "Every removal step must have a description"
- assert len(descriptions) == len(set(descriptions)), (
- f"Registry has duplicate step descriptions: {descriptions}"
- )
- # Core steps must be present — these are the ones the rest of the code
- # assumes exist. When deliberately dropping one, update this list.
- required = {
- "gh auth token / COPILOT_GITHUB_TOKEN / GH_TOKEN",
- "Any env-seeded credential (XAI_API_KEY, DEEPSEEK_API_KEY, etc.)",
- "~/.claude/.credentials.json",
- "~/.hermes/.anthropic_oauth.json",
- "auth.json providers.nous",
- "auth.json providers.openai-codex + ~/.codex/auth.json",
- "auth.json providers.minimax-oauth",
- "~/.qwen/oauth_creds.json",
- "Custom provider config.yaml api_key field",
- }
- missing = required - set(descriptions)
- assert not missing, f"Registry missing required steps: {missing}"
-
-
-def test_credential_sources_find_step_copilot_before_generic_env(tmp_path, monkeypatch):
- """copilot env:GH_TOKEN must dispatch to the copilot step, not the
- generic env-var step. The copilot step handles the duplicate-source
- problem (same token seeded as both gh_cli and env:<VAR>); the generic
- env step would only suppress one of the variants.
- """
- from agent.credential_sources import find_removal_step
-
- step = find_removal_step("copilot", "env:GH_TOKEN")
- assert step is not None
- assert "copilot" in step.description.lower() or "gh" in step.description.lower()
-
- # Generic step still matches any other provider's env var
- step = find_removal_step("xai", "env:XAI_API_KEY")
- assert step is not None
- assert "env-seeded" in step.description.lower()
-
-
def test_auth_remove_copilot_suppresses_all_variants(tmp_path, monkeypatch):
"""Removing any copilot source must suppress gh_cli + all env:* variants
so the duplicate-seed paths don't resurrect the credential.
@@ -1197,27 +991,10 @@ def test_auth_remove_env_seeded_dotenv_with_bom_no_shell_hint(tmp_path, monkeypa
auth_remove_command(SimpleNamespace(provider="deepseek", target="1"))
out = capsys.readouterr().out
- assert "Cleared DEEPSEEK_API_KEY from .env" in out
+ assert "DEEPSEEK_API_KEY" not in (hermes_home / ".env").read_text(encoding="utf-8-sig")
assert "still set in your shell environment" not in out
-def test_qwen_oauth_login_marks_active_through_moved_owner(monkeypatch):
- """`_mark_qwen_oauth_active` lives in `auth_qwen`; the login flow must reach it
- without depending on a re-export from the `auth` facade (AttributeError on head before)."""
- import hermes_cli.auth_commands as auth_commands
- import hermes_cli.auth_qwen as auth_qwen
-
- creds = {"access_token": "tok"}
- marked = []
- monkeypatch.setattr(
- auth_commands.auth_mod, "resolve_qwen_runtime_credentials", lambda **kw: creds
- )
- monkeypatch.setattr(auth_qwen, "_mark_qwen_oauth_active", lambda c: marked.append(c))
-
- assert auth_commands._qwen_oauth_login(None) is creds
- assert marked == [creds]
-
-
def test_auth_add_openrouter_oauth_persists_pkce_key_without_touching_api_key_default(tmp_path, monkeypatch):
"""`hermes auth add openrouter --type oauth` stores the PKCE-minted key as an ``api_key`` pool row
(OpenRouter returns a plain key, no refresh pair) that ``resolve_provider("auto")`` picks up with no
diff --git a/tests/hermes_cli/test_auth_key_prefix_skip.py b/tests/hermes_cli/test_auth_key_prefix_skip.py
index 27fa9a3666b..dde69d1f7cc 100644
--- a/tests/hermes_cli/test_auth_key_prefix_skip.py
+++ b/tests/hermes_cli/test_auth_key_prefix_skip.py
@@ -18,7 +18,6 @@ The fix:
"""
import logging
-import os
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -86,7 +85,6 @@ class TestMalformedEnvKeySkipped:
assert source == "credential_pool:openrouter"
warnings = [r for r in caplog.records if "OPENROUTER_API_KEY" in r.getMessage()]
assert warnings, "expected a WARNING naming the malformed env var"
- assert "sk-or-" in warnings[0].getMessage()
def test_malformed_env_key_with_empty_pool_returns_empty(
self, isolated_hermes_home, caplog
diff --git a/tests/hermes_cli/test_auth_loopback_ssh_hint.py b/tests/hermes_cli/test_auth_loopback_ssh_hint.py
deleted file mode 100644
index 268d72bac40..00000000000
--- a/tests/hermes_cli/test_auth_loopback_ssh_hint.py
+++ /dev/null
@@ -1,67 +0,0 @@
-"""Unit tests for _print_loopback_ssh_hint() in hermes_cli/auth.py.
-
-The helper warns users that loopback OAuth flows (Spotify) don't work over
-SSH unless they set up an `ssh -L` port forward between their laptop's
-browser and the remote host's loopback listener.
-
-xAI Grok OAuth no longer uses this helper — its login is device-code-only —
-but the Spotify integration still relies on it.
-"""
-
-from __future__ import annotations
-
-import io
-import contextlib
-import socket
-
-
-from hermes_cli import auth as auth_mod
-import hermes_cli.auth_device_flow as auth_device_flow
-
-
-def _cap(fn):
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- fn()
- return buf.getvalue()
-
-
-def test_loopback_ssh_hint_silent_when_not_remote(monkeypatch):
- monkeypatch.setattr(auth_mod, "_is_remote_session", lambda: False)
- monkeypatch.setattr(auth_device_flow, "_is_remote_session", lambda: False)
- out = _cap(lambda: auth_mod._print_loopback_ssh_hint(
- "http://127.0.0.1:43827/spotify/callback", docs_url=auth_mod.SPOTIFY_DOCS_URL
- ))
- assert out == ""
-
-
-def test_loopback_ssh_hint_has_visual_header(monkeypatch):
- """The hint should print a divider and header so it stands out in noisy output."""
- monkeypatch.setattr(auth_mod, "_is_remote_session", lambda: True)
- monkeypatch.setattr(auth_device_flow, "_is_remote_session", lambda: True)
- out = _cap(lambda: auth_mod._print_loopback_ssh_hint(
- "http://127.0.0.1:43827/callback"
- ))
- assert "Remote session detected" in out
- assert "---" in out # divider is present
-
-
-class TestSshUserAtHost:
- def test_resolves_user_and_hostname(self, monkeypatch):
- monkeypatch.setenv("USER", "alice")
- monkeypatch.delenv("LOGNAME", raising=False)
- monkeypatch.setattr(socket, "gethostname", lambda: "myserver")
- assert auth_mod._ssh_user_at_host() == "alice@myserver"
-
-
- def test_placeholder_when_no_env_vars(self, monkeypatch):
- monkeypatch.delenv("USER", raising=False)
- monkeypatch.delenv("LOGNAME", raising=False)
- monkeypatch.setattr(socket, "gethostname", lambda: "host1")
- assert auth_mod._ssh_user_at_host() == "<user>@host1"
-
-
- def test_placeholder_when_empty_hostname(self, monkeypatch):
- monkeypatch.setenv("USER", "dave")
- monkeypatch.setattr(socket, "gethostname", lambda: "")
- assert auth_mod._ssh_user_at_host() == "dave@<this-host>"
diff --git a/tests/hermes_cli/test_auth_nous_provider.py b/tests/hermes_cli/test_auth_nous_provider.py
index 7f5f1177278..5db36184206 100644
--- a/tests/hermes_cli/test_auth_nous_provider.py
+++ b/tests/hermes_cli/test_auth_nous_provider.py
@@ -11,7 +11,7 @@ from pathlib import Path
import httpx
import pytest
-from hermes_cli.auth import AuthError, get_provider_auth_state, resolve_nous_runtime_credentials
+from hermes_cli.auth import AuthError
# =============================================================================
@@ -58,7 +58,6 @@ class TestResolveVerifyFallback:
)
-
def test_insecure_takes_precedence_over_missing_ca(self):
from hermes_cli.auth import _resolve_verify
@@ -83,8 +82,6 @@ class TestResolveVerifyFallback:
assert result is False
-
-
def _setup_nous_auth(
hermes_home: Path,
*,
@@ -293,67 +290,6 @@ def test_resolve_nous_runtime_credentials_reauths_when_invoke_scope_missing(
assert "credential_pool" not in payload or not payload["credential_pool"].get("nous")
-
-
-def test_removed_legacy_session_env_var_does_not_change_jwt_auth(tmp_path, monkeypatch):
- import hermes_cli.auth as auth_mod
-
- hermes_home = tmp_path / "hermes"
- token = _invoke_jwt(seconds=3600)
- _setup_nous_auth(
- hermes_home,
- access_token=token,
- scope=auth_mod.DEFAULT_NOUS_SCOPE,
- expires_at=_future_iso(3600),
- expires_in=3600,
- )
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- monkeypatch.setenv("HERMES_AGENT_USE_LEGACY_SESSION_KEYS", "true")
-
- creds = auth_mod.resolve_nous_runtime_credentials()
-
- assert creds["api_key"] == token
- payload = json.loads((hermes_home / "auth.json").read_text())
- assert payload["providers"]["nous"]["agent_key"] == token
-
- requested_scopes = []
- login_token = _invoke_jwt(seconds=3600)
-
- def _fake_request_device_code(*, client, portal_base_url, client_id, scope):
- del client, portal_base_url, client_id
- requested_scopes.append(scope)
- return {
- "device_code": "device",
- "user_code": "user",
- "verification_uri": "https://portal.example.com/device",
- "verification_uri_complete": "https://portal.example.com/device?code=user",
- "expires_in": 600,
- "interval": 1,
- }
-
- def _fake_poll_for_token(**kwargs):
- del kwargs
- return {
- "access_token": login_token,
- "refresh_token": "refresh-token",
- "expires_in": 900,
- "scope": auth_mod.DEFAULT_NOUS_SCOPE,
- }
-
- monkeypatch.setattr(auth_mod, "_request_device_code", _fake_request_device_code)
- monkeypatch.setattr(auth_mod, "_poll_for_token", _fake_poll_for_token)
-
- result = auth_mod._nous_device_code_login(
- portal_base_url="https://portal.example.com",
- inference_base_url="https://inference.example.com/v1",
- open_browser=False,
- timeout_seconds=1,
- )
-
- assert requested_scopes == [auth_mod.DEFAULT_NOUS_SCOPE]
- assert result["agent_key"] == login_token
-
-
def test_nous_inference_auth_logs_do_not_include_secret_values(
tmp_path,
monkeypatch,
@@ -464,12 +400,6 @@ def test_get_nous_auth_status_empty_returns_not_logged_in(tmp_path, monkeypatch)
assert status["logged_in"] is False
-
-
-
-
-
-
# =============================================================================
# _login_nous: "Skip (keep current)" must preserve prior provider + model
# =============================================================================
@@ -590,7 +520,7 @@ class TestLoginNousSkipKeepsCurrent:
hermes_home, config_path, auth_path = self._setup_home_with_openrouter(
tmp_path, monkeypatch,
)
- free_tier_calls = self._patch_login_internals(
+ self._patch_login_internals(
monkeypatch, prompt_returns="xiaomi/mimo-v2-pro",
)
@@ -603,7 +533,6 @@ class TestLoginNousSkipKeepsCurrent:
cfg_after = yaml.safe_load(config_path.read_text())
assert cfg_after["model"]["provider"] == "nous"
assert cfg_after["model"]["default"] == "xiaomi/mimo-v2-pro"
- assert free_tier_calls == [{"force_fresh": True}]
auth_after = json.loads(auth_path.read_text())
assert auth_after["active_provider"] == "nous"
@@ -670,50 +599,6 @@ def _full_state_fixture() -> dict:
}
-def test_persist_nous_credentials_writes_both_pool_and_providers(tmp_path, monkeypatch):
- """Helper must populate BOTH credential_pool.nous AND providers.nous.
-
- Regression guard: before this helper existed, `hermes auth add nous`
- wrote only the pool. After the Nous agent_key's 24h TTL expired, the
- 401-recovery path in run_agent.py called resolve_nous_runtime_credentials
- which reads providers.nous, found it empty, raised AuthError, and the
- agent failed with "Non-retryable client error". Both stores must stay
- in sync at write time.
- """
- from hermes_cli.auth import persist_nous_credentials, NOUS_DEVICE_CODE_SOURCE
-
- hermes_home = tmp_path / "hermes"
- hermes_home.mkdir(parents=True, exist_ok=True)
- (hermes_home / "auth.json").write_text(json.dumps({
- "version": 1, "providers": {},
- }))
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- state = _full_state_fixture()
- entry = persist_nous_credentials(state)
-
- assert entry is not None
- assert entry.provider == "nous"
- assert entry.source == NOUS_DEVICE_CODE_SOURCE
-
- payload = json.loads((hermes_home / "auth.json").read_text())
-
- # providers.nous populated with the full state (new behaviour)
- singleton = payload["providers"]["nous"]
- assert singleton["access_token"] == state["access_token"]
- assert singleton["refresh_token"] == "refresh-tok"
- assert singleton["agent_key"] == state["agent_key"]
- assert singleton["agent_key_expires_at"] == state["agent_key_expires_at"]
-
- # credential_pool.nous has exactly one canonical device_code entry
- pool_entries = payload["credential_pool"]["nous"]
- assert len(pool_entries) == 1, pool_entries
- pool_entry = pool_entries[0]
- assert pool_entry["source"] == NOUS_DEVICE_CODE_SOURCE
- assert pool_entry["agent_key"] == state["agent_key"]
- assert pool_entry["inference_base_url"] == "https://inference.example.com/v1"
-
-
def test_persist_nous_credentials_idempotent_no_duplicate_pool_entries(tmp_path, monkeypatch):
"""Re-running persist must upsert — not accumulate duplicate device_code rows.
@@ -760,32 +645,6 @@ def test_persist_nous_credentials_idempotent_no_duplicate_pool_entries(tmp_path,
)
-def test_persist_nous_credentials_no_label_uses_auto_derived(tmp_path, monkeypatch):
- """When the caller doesn't pass ``label``, the auto-derived fingerprint
- is used (unchanged default behaviour — regression guard).
- """
- from hermes_cli.auth import persist_nous_credentials
-
- hermes_home = tmp_path / "hermes"
- hermes_home.mkdir(parents=True, exist_ok=True)
- (hermes_home / "auth.json").write_text(json.dumps({
- "version": 1, "providers": {},
- }))
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- entry = persist_nous_credentials(_full_state_fixture())
- assert entry is not None
- # label_from_token derives from the access_token; exact value depends on
- # the fingerprinter but it must not be empty and must not equal an
- # arbitrary user string we never passed.
- assert entry.label
- assert entry.label != "my-personal"
-
- # No "label" key embedded in providers.nous when the caller didn't supply one.
- payload = json.loads((hermes_home / "auth.json").read_text())
- assert "label" not in payload["providers"]["nous"]
-
-
def test_refresh_token_reuse_detection_surfaces_actionable_message():
"""Regression for #15099.
@@ -820,11 +679,6 @@ def test_refresh_token_reuse_detection_surfaces_actionable_message():
refresh_token="rt_consumed_elsewhere",
)
- message = str(exc_info.value)
- assert "refresh-token reuse" in message.lower() or "refresh token reuse" in message.lower()
- # The message must mention the external-process cause and give next steps.
- assert "external process" in message.lower() or "monitoring script" in message.lower()
- assert "hermes auth add nous" in message.lower()
# Must still be classified as invalid_grant + relogin_required.
assert exc_info.value.code == "invalid_grant"
assert exc_info.value.relogin_required is True
@@ -870,8 +724,6 @@ def test_refresh_token_exchange_sends_refresh_token_header():
}
-
-
# =============================================================================
# Shared Nous token store — cross-profile persistence (Codex-style auto-import)
# =============================================================================
@@ -971,8 +823,6 @@ def test_persist_nous_credentials_mirrors_to_shared_store(
assert str(_nous_shared_store_path()).startswith(str(shared_store_env))
-
-
def test_try_import_shared_rehydrates_on_success(shared_store_env, monkeypatch):
"""Happy path: stored refresh_token is accepted, forced refresh
returns a fresh access_token JWT, and the returned dict has
@@ -1009,14 +859,6 @@ def test_try_import_shared_rehydrates_on_success(shared_store_env, monkeypatch):
assert result["client_id"] == "hermes-cli"
-
-
-
-
-
-
-
-
class TestStalePortalBaseUrlMigration:
"""_migrate_stale_nous_portal_url auto-corrects stale portal_base_url on load."""
@@ -1042,9 +884,6 @@ class TestStalePortalBaseUrlMigration:
assert nous["portal_base_url"] == DEFAULT_NOUS_PORTAL_URL
-
-
-
def test_runtime_credentials_rejects_http_for_production_portal(
self, tmp_path, monkeypatch,
):
@@ -1098,32 +937,10 @@ class TestStalePortalBaseUrlMigration:
# =============================================================================
-class TestNousDeviceAuthTimeoutMessage:
- def test_timeout_message_mentions_captcha_login_and_retry(self):
- from hermes_cli.auth import _nous_device_auth_timeout_message
-
- msg = _nous_device_auth_timeout_message("https://portal.nousresearch.com")
- assert "CAPTCHA" in msg
- assert "hermes portal" in msg
- assert "https://portal.nousresearch.com/login" in msg
- # Must NOT point at the nonexistent /device page (live Portal 404s it).
- assert "/device" not in msg
-
- def test_timeout_message_falls_back_to_default_portal(self):
- from hermes_cli.auth import (
- DEFAULT_NOUS_PORTAL_URL,
- _nous_device_auth_timeout_message,
- )
-
- msg = _nous_device_auth_timeout_message("")
- assert f"{DEFAULT_NOUS_PORTAL_URL.rstrip('/')}/login" in msg
-
-
def test_poll_for_token_timeout_raises_actionable_message():
"""The poll deadline must raise the CAPTCHA-aware guidance at the SOURCE,
so both the CLI login and the dashboard poller (web_server_oauth._nous_poller,
which surfaces str(e) to the UI) inherit it."""
- import httpx
import pytest
import hermes_cli.auth as auth_mod
@@ -1139,7 +956,7 @@ def test_poll_for_token_timeout_raises_actionable_message():
from typing import cast
- with pytest.raises(TimeoutError) as excinfo:
+ with pytest.raises(TimeoutError):
auth_mod._poll_for_token(
client=cast(httpx.Client, _PendingClient()),
portal_base_url="https://portal.nousresearch.com",
@@ -1149,55 +966,4 @@ def test_poll_for_token_timeout_raises_actionable_message():
poll_interval=1,
)
- msg = str(excinfo.value)
- assert "CAPTCHA" in msg
- assert "hermes portal" in msg
- assert "https://portal.nousresearch.com/login" in msg
-
-
-def test_nous_device_code_login_timeout_raises_actionable_message(monkeypatch):
- """Poll timeout must surface the CAPTCHA-aware guidance through the CLI
- login flow (propagates unchanged from _poll_for_token)."""
- import pytest
-
- import hermes_cli.auth as auth_mod
-
- monkeypatch.setattr(
- auth_mod,
- "_request_device_code",
- lambda **kwargs: {
- "device_code": "device",
- "user_code": "SMCL-97YT",
- "verification_uri": "https://portal.nousresearch.com/manage-subscription",
- "verification_uri_complete": (
- "https://portal.nousresearch.com/manage-subscription"
- "?user_code=SMCL-97YT"
- ),
- "expires_in": 600,
- "interval": 1,
- },
- )
-
- def _timeout(**kwargs):
- raise TimeoutError(
- auth_mod._nous_device_auth_timeout_message(
- kwargs.get("portal_base_url", "")
- )
- )
-
- monkeypatch.setattr(auth_mod, "_poll_for_token", _timeout)
- monkeypatch.setattr(auth_mod.webbrowser, "open", lambda url: True)
- monkeypatch.setattr("builtins.print", lambda *a, **k: None)
-
- with pytest.raises(TimeoutError) as excinfo:
- auth_mod._nous_device_code_login(
- portal_base_url="https://portal.nousresearch.com",
- inference_base_url="https://inference.example.com/v1",
- open_browser=False,
- timeout_seconds=1,
- )
- msg = str(excinfo.value)
- assert "CAPTCHA" in msg
- assert "hermes portal" in msg
- assert "https://portal.nousresearch.com/login" in msg
diff --git a/tests/hermes_cli/test_auth_qwen_provider.py b/tests/hermes_cli/test_auth_qwen_provider.py
index 42c7b4fb726..844bb0eba42 100644
--- a/tests/hermes_cli/test_auth_qwen_provider.py
+++ b/tests/hermes_cli/test_auth_qwen_provider.py
@@ -6,22 +6,14 @@ resolve_qwen_runtime_credentials, get_qwen_auth_status.
"""
import json
-import stat
import time
-from pathlib import Path
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
from hermes_cli.auth import (
AuthError,
DEFAULT_QWEN_BASE_URL,
- QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,
- _qwen_cli_auth_path,
- _read_qwen_cli_tokens,
- _save_qwen_cli_tokens,
- _qwen_access_token_is_expiring,
- _refresh_qwen_cli_tokens,
resolve_qwen_runtime_credentials,
get_qwen_auth_status,
)
@@ -77,9 +69,6 @@ def qwen_env(tmp_path, monkeypatch):
# _qwen_cli_auth_path
# ---------------------------------------------------------------------------
-def test_qwen_cli_auth_path_returns_expected_location():
- path = _qwen_cli_auth_path()
- assert path == Path.home() / ".qwen" / "oauth_creds.json"
# ---------------------------------------------------------------------------
@@ -201,7 +190,6 @@ def test_model_flow_qwen_oauth_stale_token_shows_reauth_guidance(qwen_env, monke
_model_flow_qwen_oauth({}, current_model="qwen3-coder-plus")
out = capsys.readouterr().out
- assert "Run: qwen auth qwen-oauth" in out
assert "Qwen refresh rejected" in out
assert prompt_called["value"] is False
assert update_called["value"] is False
diff --git a/tests/hermes_cli/test_auth_store_lock_concurrent.py b/tests/hermes_cli/test_auth_store_lock_concurrent.py
deleted file mode 100644
index 30788abe170..00000000000
--- a/tests/hermes_cli/test_auth_store_lock_concurrent.py
+++ /dev/null
@@ -1,80 +0,0 @@
-"""Regression test for a Windows-only PermissionError under lock contention.
-
-``_file_lock()`` (backing ``_auth_store_lock()``) ensures its lock file has
-at least 1 byte of content before opening it for ``msvcrt.locking()`` (which
-requires a non-empty file). That "ensure content" write was unguarded: under
-real concurrency, one thread/process's ``msvcrt.locking()`` byte-range lock
-can already be held on the file at the exact moment another thread runs the
-same ensure-content check, and the write collides and raises
-``PermissionError`` -- uncaught, since it happens before the retry loop the
-rest of the function uses for exactly this kind of contention.
-
-This was found by a stress test for the Anthropic OAuth credential-pool fix
-(``tests/agent/test_anthropic_oauth_stress.py``), which reliably reproduces
-it (16/20 concurrent refreshes hit PermissionError pre-fix, deterministically
-across repeated runs) because the surrounding CredentialPool work widens the
-race window enough for real OS-level thread interleaving to land on it. That
-test is the authoritative regression guard for the exact failure mode. This
-file is deliberately a minimal, isolated stress test against
-``_auth_store_lock()`` directly -- best-effort coverage that does not always
-land on the same narrow window in isolation, but exercises the SAME shared
-primitive Codex/xAI/Nous already depend on for their single-use-refresh-token
-protection, so this bug was never Anthropic-specific.
-"""
-
-from __future__ import annotations
-
-import threading
-
-import pytest
-
-from hermes_cli.auth import _auth_store_lock
-
-CONCURRENCY = 40
-
-
-def hermes_home(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- return tmp_path
-
-
-def test_many_concurrent_lock_acquisitions_do_not_raise_permission_error(hermes_home):
- """CONCURRENCY threads race to acquire/release the same auth-store lock.
-
- None of them should ever see an uncaught PermissionError/OSError from
- the lock-file "ensure content" pre-check -- only the intended
- TimeoutError (never expected here, since each critical section is
- instant) should be a possible failure mode.
- """
- errors: dict[int, BaseException] = {}
- entered = 0
- entered_lock = threading.Lock()
- # Synchronize all threads to hit the lock-file "ensure content" pre-check
- # at (as close as the OS scheduler allows to) the exact same instant --
- # the race only exists on the very first acquisition against a fresh
- # lock file, so a tight barrier maximizes the odds of reproducing it
- # instead of relying on incidental thread-start jitter.
- barrier = threading.Barrier(CONCURRENCY)
-
- def _run(idx: int) -> None:
- nonlocal entered
- try:
- barrier.wait(timeout=10)
- with _auth_store_lock(timeout_seconds=10.0):
- with entered_lock:
- entered += 1
- except BaseException as exc: # pragma: no cover - failure diagnostics
- errors[idx] = exc
-
- threads = [threading.Thread(target=_run, args=(i,)) for i in range(CONCURRENCY)]
- for t in threads:
- t.start()
- for t in threads:
- t.join(timeout=30)
-
- still_alive = [t for t in threads if t.is_alive()]
- assert not still_alive, f"{len(still_alive)}/{CONCURRENCY} threads never finished"
- assert not errors, f"unexpected exceptions acquiring the lock concurrently: {errors!r}"
- assert entered == CONCURRENCY
diff --git a/tests/hermes_cli/test_auth_store_read_failure.py b/tests/hermes_cli/test_auth_store_read_failure.py
index e48979970b1..f922cfdae7d 100644
--- a/tests/hermes_cli/test_auth_store_read_failure.py
+++ b/tests/hermes_cli/test_auth_store_read_failure.py
@@ -12,7 +12,6 @@ to have preserved one when the copy actually landed.
import errno
import json
-import logging
import pytest
@@ -75,24 +74,3 @@ def test_healthy_store_is_returned_unchanged(store_file):
assert result["providers"]["nous"]["api_key"] == "secret"
-def test_log_does_not_claim_a_backup_that_was_not_written(
- store_file, monkeypatch, caplog
-):
- """The old message advertised the .corrupt path even when copy2 failed."""
- import shutil
-
- store_file.write_text("{ not json", encoding="utf-8")
-
- def _no_copy(*args, **kwargs):
- raise OSError(errno.EMFILE, "Too many open files")
-
- monkeypatch.setattr(shutil, "copy2", _no_copy)
-
- with caplog.at_level(logging.WARNING, logger="hermes_cli.auth"):
- result = auth._load_auth_store(store_file)
-
- assert result == {"version": auth.AUTH_STORE_VERSION, "providers": {}}
- assert not store_file.with_suffix(".json.corrupt").exists()
- text = caplog.text
- assert "could NOT be preserved" in text
- assert "Corrupt file preserved at" not in text
diff --git a/tests/hermes_cli/test_auth_store_windows_encoding.py b/tests/hermes_cli/test_auth_store_windows_encoding.py
index 12792f04492..fefd9d32e3d 100644
--- a/tests/hermes_cli/test_auth_store_windows_encoding.py
+++ b/tests/hermes_cli/test_auth_store_windows_encoding.py
@@ -17,12 +17,10 @@ from __future__ import annotations
import json
from pathlib import Path
-from unittest import mock
import pytest
import hermes_cli.auth as auth
-import hermes_cli.auth_codex as auth_codex
# --- helpers ---------------------------------------------------------------
@@ -138,51 +136,6 @@ class TestAuthStoreEncodingRoundTrip:
# --- the fix: readers pass an explicit encoding ---------------------------
-class TestExplicitEncodingPassed:
- """The readers must not rely on the locale default (cp1252 on Windows).
-
- We assert read_text is called with an explicit UTF-8 encoding. This is the
- regression guard: a future refactor that drops the encoding kwarg would
- reintroduce the Windows data-loss bug.
- """
-
- def test_load_auth_store_passes_utf8_encoding(self, hermes_home):
- auth_path = hermes_home / "auth.json"
- _write_utf8(auth_path, {"version": auth.AUTH_STORE_VERSION, "providers": {}})
-
- with mock.patch.object(
- Path, "read_text", wraps=Path.read_text
- ) as spy:
- auth._load_auth_store(auth_path)
-
- assert spy.call_count == 1
- kwargs = spy.call_args.kwargs
- assert "encoding" in kwargs, "read_text() must pass an explicit encoding"
- assert "utf-8" in str(kwargs["encoding"]).lower()
-
- def test_codex_store_reader_passes_utf8_encoding(self, tmp_path, monkeypatch):
- """The ~/.codex/auth.json reader must pass an explicit UTF-8 encoding."""
- codex_home = tmp_path / "codex"
- codex_home.mkdir()
- (codex_home / "auth.json").write_text(
- json.dumps({"tokens": {"access_token": "a", "refresh_token": "r"}}),
- encoding="utf-8",
- )
- monkeypatch.setenv("CODEX_HOME", str(codex_home))
- # Bypass the JWT-expiry check so a fake token doesn't short-circuit.
- monkeypatch.setattr(auth, "_codex_access_token_is_expiring", lambda *a, **k: False)
- monkeypatch.setattr(auth_codex, "_codex_access_token_is_expiring", lambda *a, **k: False)
-
- with mock.patch.object(Path, "read_text", wraps=Path.read_text) as spy:
- auth._import_codex_cli_tokens()
-
- # _import_codex_cli_tokens reads exactly one file; assert that read
- # carried an explicit UTF-8 encoding. (The bound-method spy captures
- # kwargs but not the bound `self`, so we check the single read directly.)
- assert spy.call_count >= 1, "expected a read of the codex auth.json"
- for call in spy.call_args_list:
- assert "encoding" in call.kwargs, "codex read_text() must pass encoding"
- assert "utf-8" in str(call.kwargs["encoding"]).lower()
# --- sibling readers of the same ~/.hermes/auth.json in other modules -------
diff --git a/tests/hermes_cli/test_auth_usable_secret.py b/tests/hermes_cli/test_auth_usable_secret.py
deleted file mode 100644
index cb24ef5ee26..00000000000
--- a/tests/hermes_cli/test_auth_usable_secret.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""Tests for placeholder API key detection in hermes_cli.auth."""
-
-from hermes_cli.auth import has_usable_secret
-
-
-def test_has_usable_secret_rejects_documented_placeholder_key() -> None:
- """Network-exposed API server key must reject static documentation placeholders."""
- assert not has_usable_secret("your_api_key_here", min_length=8)
-
-
-def test_has_usable_secret_accepts_generated_key() -> None:
- """Random-looking keys should still be accepted."""
- assert has_usable_secret("b4d59f7fe8b857d0b367ef0f5710b6a4", min_length=8)
diff --git a/tests/hermes_cli/test_auth_xai_oauth_provider.py b/tests/hermes_cli/test_auth_xai_oauth_provider.py
index 3303bea33ef..68c3ea14621 100644
--- a/tests/hermes_cli/test_auth_xai_oauth_provider.py
+++ b/tests/hermes_cli/test_auth_xai_oauth_provider.py
@@ -10,17 +10,9 @@ import pytest
from hermes_cli.auth import (
AuthError,
DEFAULT_XAI_OAUTH_BASE_URL,
- PROVIDER_REGISTRY,
- XAI_OAUTH_CLIENT_ID,
- XAI_OAUTH_SCOPE,
_read_xai_oauth_tokens,
_refresh_xai_oauth_tokens,
_save_xai_oauth_tokens,
- _xai_access_token_is_expiring,
- _xai_oauth_poll_device_token,
- _xai_oauth_request_device_code,
- _xai_validate_inference_base_url,
- format_auth_error,
get_xai_oauth_auth_status,
refresh_xai_oauth_pure,
resolve_provider,
@@ -122,12 +114,6 @@ def _patch_httpx_client(monkeypatch, response):
# ---------------------------------------------------------------------------
-def test_xai_oauth_provider_registered():
- assert "xai-oauth" in PROVIDER_REGISTRY
- pconfig = PROVIDER_REGISTRY["xai-oauth"]
- assert pconfig.id == "xai-oauth"
- assert pconfig.auth_type == "oauth_external"
- assert pconfig.inference_base_url == DEFAULT_XAI_OAUTH_BASE_URL
def test_resolve_provider_normalizes_xai_oauth_aliases():
@@ -395,33 +381,8 @@ def test_refresh_xai_oauth_pure_403_marked_tier_denied_not_relogin(monkeypatch):
)
assert exc.value.code == "xai_oauth_tier_denied"
assert exc.value.relogin_required is False
- message = str(exc.value).lower()
- assert "403" in message
- assert "xai_api_key" in message
- assert "tier" in message
-def test_format_auth_error_tier_denied_does_not_suggest_relogin():
- """``xai_oauth_tier_denied`` must not append the re-authenticate hint.
-
- Regression for #26847: telling a tier-gated user to ``hermes model``
- is actively wrong — re-logging in won't change xAI's allowlist
- decision. The full message (with ``XAI_API_KEY`` fallback) is built
- into the error itself.
- """
- err = AuthError(
- "xAI token refresh failed with HTTP 403. Response: forbidden. "
- "This OAuth account is not authorized for xAI API access — "
- "xAI may be restricting API/OAuth use to specific SuperGrok tiers. "
- "Set ``XAI_API_KEY`` and switch to ``provider: xai``.",
- provider="xai-oauth",
- code="xai_oauth_tier_denied",
- relogin_required=False,
- )
- rendered = format_auth_error(err)
- assert "re-authenticate" not in rendered.lower()
- assert "hermes model" not in rendered.lower()
- assert "XAI_API_KEY" in rendered
def test_xai_oauth_discovery_raises_typed_error_on_malformed_json(monkeypatch):
@@ -697,47 +658,6 @@ def test_login_xai_oauth_relogin_clears_suppression_and_reseeds(tmp_path, monkey
# ---------------------------------------------------------------------------
-def test_pool_sync_back_writes_to_singleton(tmp_path, monkeypatch):
- """When the pool refreshes a singleton-seeded xAI entry, the new tokens
- must be written back to providers["xai-oauth"] so that
- resolve_xai_oauth_runtime_credentials() (which reads the singleton)
- doesn't keep using the consumed refresh token."""
- from agent.credential_pool import load_pool
-
- hermes_home = tmp_path / "hermes"
- expired = _jwt_with_exp(int(time.time()) - 10)
- _setup_hermes_auth(hermes_home, access_token=expired, refresh_token="rt-old")
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- new_access = _jwt_with_exp(int(time.time()) + 2 * 60 * 60)
-
- def _fake_refresh(access_token, refresh_token, **kwargs):
- assert refresh_token == "rt-old"
- return {
- "access_token": new_access,
- "refresh_token": "rt-new",
- "id_token": "",
- "expires_in": 3600,
- "token_type": "Bearer",
- "last_refresh": "2026-05-15T01:00:00Z",
- }
-
- monkeypatch.setattr("hermes_cli.auth.refresh_xai_oauth_pure", _fake_refresh)
-
- pool = load_pool("xai-oauth")
- selected = pool.select()
- assert selected is not None
- assert selected.access_token == new_access
- assert selected.refresh_token == "rt-new"
-
- # Singleton must reflect refreshed tokens — otherwise the next process
- # to load credentials would re-seed the consumed refresh token.
- auth_path = hermes_home / "auth.json"
- raw = json.loads(auth_path.read_text())
- state = raw["providers"]["xai-oauth"]
- assert state["tokens"]["access_token"] == new_access
- assert state["tokens"]["refresh_token"] == "rt-new"
- assert state["last_refresh"] == "2026-05-15T01:00:00Z"
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py b/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py
index 497703dde7e..bc713cb1320 100644
--- a/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py
+++ b/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py
@@ -8,7 +8,6 @@ the session provider (the "sticky provider fallback pollution" bug).
"""
import pytest
-from hermes_cli import main_provider_setup
class _FakePool:
@@ -104,48 +103,3 @@ def test_picker_shows_exhausted_pool_provider(monkeypatch):
"Picker must show exhausted-pool providers so the user can select "
"a different model under the same provider"
)
-
-
-
-
-class _StopPicker(BaseException):
- """Aborts a picker right after it requests its provider list, before any
- interactive prompt. Subclasses BaseException so the picker's own
- ``except Exception`` guards don't swallow it."""
-
-
-def _spy_list_authenticated(recorded: dict):
- def _spy(*_args, **kwargs):
- recorded.update(kwargs)
- raise _StopPicker
- return _spy
-
-
-def test_aux_task_picker_requests_exhausted_pool_visibility(monkeypatch):
- """The ``hermes model`` auxiliary-task picker (``_aux_select_for_task``)
- must request exhausted-pool visibility (``for_picker=True``) like the
- ``/model`` picker (#66584).
-
- The aux picker writes a *persistent* per-task provider/model config that
- the user runs later — long after a momentary rate-limit cooldown clears —
- so silently hiding a provider whose keys are all exhausted is exactly the
- bug the #66584 picker fix addressed, one interactive picker over.
- """
- import hermes_cli.main as main
-
- recorded: dict = {}
- monkeypatch.setattr(
- "hermes_cli.model_switch.list_authenticated_providers",
- _spy_list_authenticated(recorded),
- )
- monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
-
- with pytest.raises(_StopPicker):
- main_provider_setup._aux_select_for_task("compression")
-
- assert recorded.get("for_picker") is True, (
- "aux-task picker must pass for_picker=True so exhausted-pool providers "
- "stay selectable (before the fix it omitted the flag → hidden)"
- )
-
-
diff --git a/tests/hermes_cli/test_aux_config.py b/tests/hermes_cli/test_aux_config.py
index f26baa47fa0..a0b7edde81e 100644
--- a/tests/hermes_cli/test_aux_config.py
+++ b/tests/hermes_cli/test_aux_config.py
@@ -12,31 +12,14 @@ here (they're stdin-driven curses prompts).
from __future__ import annotations
-import pytest
-from hermes_cli.config import DEFAULT_CONFIG, load_config
-from hermes_cli.main_provider_setup import _AUX_TASKS, _DELEGATION_TASK_KEY, _delegation_cfg_as_task, _format_aux_current, _reset_aux_to_auto, _save_aux_choice
+from hermes_cli.config import load_config
+from hermes_cli.main_provider_setup import _DELEGATION_TASK_KEY, _delegation_cfg_as_task, _format_aux_current, _reset_aux_to_auto, _save_aux_choice
# ── Default config ──────────────────────────────────────────────────────────
-def test_title_generation_present_in_default_config():
- """`title_generation` task must be defined in DEFAULT_CONFIG.
-
- Regression for an existing gap: title_generator.py calls
- ``call_llm(task="title_generation", ...)`` but the task was missing
- from DEFAULT_CONFIG["auxiliary"], so the config-backed timeout/provider
- overrides never worked for that task.
- """
- assert "title_generation" in DEFAULT_CONFIG["auxiliary"]
- tg = DEFAULT_CONFIG["auxiliary"]["title_generation"]
- assert tg["enabled"] is True
- assert tg["provider"] == "auto"
- assert tg["model"] == ""
- assert tg["prefer_fast_model"] is False
- assert tg["timeout"] > 0
- assert tg["extra_body"] == {}
@@ -164,33 +147,3 @@ def test_delegation_cfg_as_task_projection():
assert _format_aux_current(_delegation_cfg_as_task({"delegation": "bogus"})) == "auto"
-def test_leave_unchanged_replaces_cancel_label(tmp_path, monkeypatch):
- """The bottom cancel entry now reads 'Leave unchanged' (UX polish)."""
- from pathlib import Path
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- (tmp_path / ".hermes").mkdir(exist_ok=True)
-
- from hermes_cli import main as main_mod
- import hermes_cli.main_provider_setup as hermes_cli_main_provider_setup
-
- captured: list[list[str]] = []
-
- def fake_prompt(choices, *, default=0):
- captured.append(list(choices))
- # Pick 'Leave unchanged' (last item) to exit cleanly
- for i, label in enumerate(choices):
- if label == "Leave unchanged":
- return i
- raise AssertionError("Leave unchanged not in provider list")
-
- monkeypatch.setattr(main_mod, "_prompt_provider_choice", fake_prompt)
- monkeypatch.setattr(hermes_cli_main_provider_setup, "_prompt_provider_choice", fake_prompt)
-
- main_mod.select_provider_and_model()
-
- assert captured, "provider menu never rendered"
- labels = captured[0]
- assert "Leave unchanged" in labels
- assert "Cancel" not in labels, "Cancel label should be replaced"
- assert any("Configure auxiliary models" in label for label in labels)
diff --git a/tests/hermes_cli/test_aux_picker_inventory.py b/tests/hermes_cli/test_aux_picker_inventory.py
index 27336409e99..ca750b0c0c6 100644
--- a/tests/hermes_cli/test_aux_picker_inventory.py
+++ b/tests/hermes_cli/test_aux_picker_inventory.py
@@ -23,7 +23,6 @@ from unittest.mock import patch
import pytest
import yaml
-from hermes_cli import main_provider_setup
CONFIG = {
@@ -115,45 +114,3 @@ def test_aux_picker_requests_exhausted_pool_visibility(configured_home):
# ─── Seam guard ─────────────────────────────────────────────────────────
-def test_aux_pickers_route_through_the_shared_substrate(configured_home):
- """Neither aux picker may call ``list_authenticated_providers`` directly.
-
- This is the regression that produced #52642 and #66624 as two separate
- contributor PRs against the same two call sites: a picker calling the
- low-level function re-derives its own kwargs and drops whichever slice
- of user config the author didn't think about. Both pickers must reach
- the provider list only through ``build_aux_picker_rows``.
- """
- import hermes_cli.tools_config as tools_config
-
- direct_calls = []
- substrate_calls = []
-
- def _direct(**kwargs):
- direct_calls.append(kwargs)
- return []
-
- def _substrate(**kwargs):
- substrate_calls.append(kwargs)
- return []
-
- # Abort each picker at its first prompt, right after it has asked for its
- # provider list. The vision picker returns early on empty rows; the
- # aux-task picker still renders auto/custom/back, so cancel its menu.
- with (
- patch("hermes_cli.model_switch.list_authenticated_providers", _direct),
- patch("hermes_cli.inventory.build_aux_picker_rows", _substrate),
- patch("hermes_cli.main_provider_setup._prompt_provider_choice", return_value=None),
- ):
- main_provider_setup._aux_select_for_task("compression")
- tools_config._configure_vision_provider_model({}, {})
-
- assert len(substrate_calls) == 2, (
- "both the aux-task picker and the vision picker must source providers "
- f"from build_aux_picker_rows (got {len(substrate_calls)} calls)"
- )
- assert direct_calls == [], (
- "aux pickers must not call list_authenticated_providers directly — "
- "route through hermes_cli.inventory.build_aux_picker_rows so custom "
- "providers, exclusions, and picker visibility stay consistent"
- )
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 4ba38f0234e..43587fc3849 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -138,8 +138,7 @@ class TestShouldExclude:
"""state-snapshots/ is excluded for the same reason as backups/: every
quick / pre-update snapshot holds its own copy of state.db, so zipping
the tree would ship the DB once per retained snapshot."""
- from hermes_cli.backup import _EXCLUDED_DIRS, _QUICK_SNAPSHOTS_DIR, _should_exclude
- assert _QUICK_SNAPSHOTS_DIR in _EXCLUDED_DIRS
+ from hermes_cli.backup import _QUICK_SNAPSHOTS_DIR, _should_exclude
assert _should_exclude(Path(_QUICK_SNAPSHOTS_DIR) / "20260814-203829-2026-08-15" / "state.db")
assert _should_exclude(Path(_QUICK_SNAPSHOTS_DIR) / "20260814-203829-2026-08-15" / "manifest.json")
# Named profiles accumulate snapshots too.
@@ -552,9 +551,7 @@ class TestImport:
from hermes_cli.backup import run_import
run_import(Namespace(zipfile=str(zip_path), force=True))
- out = capsys.readouterr().out
- assert "Done. Your Hermes configuration has been restored." in out
- assert "hermes gateway install" in out
+ assert (hermes_home / "config.yaml").read_text() == "model: test\n"
@@ -705,19 +702,6 @@ class TestRoundTrip:
# Validate / detect-prefix unit tests
# ---------------------------------------------------------------------------
-class TestFormatSize:
- def test_bytes(self):
- from hermes_cli.sizefmt import format_bytes as _format_size
- assert _format_size(512) == "512 B"
-
- def test_kilobytes(self):
- from hermes_cli.sizefmt import format_bytes as _format_size
- assert "KB" in _format_size(2048)
-
-
- def test_terabytes(self):
- from hermes_cli.sizefmt import format_bytes as _format_size
- assert "TB" in _format_size(2 * 1024 ** 4)
class TestValidation:
@@ -782,7 +766,6 @@ class TestBackupEdgeCases:
assert run_backup(Namespace(output=str(out_zip), keep=1)) is False
assert out_zip.exists()
assert good_old.exists(), "an incomplete run must not rotate the last complete backup out"
- assert "Backup incomplete" in capsys.readouterr().out
with pytest.raises(SystemExit) as exc:
cmd_backup(Namespace(output=str(tmp_path / "out2.zip"), quick=False))
assert exc.value.code == 1
@@ -866,27 +849,6 @@ class TestImportEdgeCases:
- def test_progress_with_many_files(self, tmp_path, monkeypatch):
- """Import shows progress with 500+ files."""
- hermes_home = tmp_path / ".hermes"
- hermes_home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
-
- zip_path = tmp_path / "big.zip"
- files = {"config.yaml": "model: test\n"}
- for i in range(600):
- files[f"sessions/s{i:04d}.json"] = "{}"
-
- self._make_backup_zip(zip_path, files)
-
- args = Namespace(zipfile=str(zip_path), force=True)
-
- from hermes_cli.backup import run_import
- run_import(args)
-
- assert (hermes_home / "config.yaml").exists()
- assert (hermes_home / "sessions" / "s0599.json").exists()
class _ExplodingMember:
@@ -1329,49 +1291,6 @@ class TestSafeCopyDb:
assert not dst.exists()
- def test_locked_source_fails_fast_not_hang(self, tmp_path):
- import subprocess
- import sys
- import time
-
- from hermes_cli.backup import _safe_copy_db
- src = tmp_path / "locked.db"
- dst = tmp_path / "copy.db"
-
- conn = sqlite3.connect(str(src))
- conn.execute("CREATE TABLE t (x INTEGER)")
- conn.commit()
- conn.close()
-
- # Hold an EXCLUSIVE transaction in a separate process. POSIX file
- # locks only conflict across processes, so an in-process connection
- # cannot reproduce the "database is locked" condition.
- holder = (
- "import sqlite3, time\n"
- f"c = sqlite3.connect({str(src)!r})\n"
- "c.execute('BEGIN EXCLUSIVE')\n"
- "print('LOCKED', flush=True)\n"
- "time.sleep(60)\n"
- )
- proc = subprocess.Popen(
- [sys.executable, "-c", holder],
- stdout=subprocess.PIPE,
- text=True,
- )
- try:
- assert proc.stdout is not None
- assert proc.stdout.readline().strip() == "LOCKED"
- started = time.monotonic()
- result = _safe_copy_db(src, dst)
- elapsed = time.monotonic() - started
- assert result is False
- # The busy timeout is 5s, so a fast failure lands around there.
- # The regression this guards against is backup() retrying
- # SQLITE_BUSY forever, which would never return at all.
- assert elapsed < 30
- finally:
- proc.kill()
- proc.wait()
def test_is_zeroed_sqlite_file_detects_nul_header(self, tmp_path):
@@ -1431,42 +1350,13 @@ class TestQuickSnapshot:
monkeypatch.setattr(backup_mod, "_safe_copy_db", boom)
snap_id = backup_mod.create_quick_snapshot(hermes_home=hermes_home)
- err = capsys.readouterr().out
- assert "SQLite safe copy FAILED" in err or "CRITICAL" in err
- assert "state.db" in err
- # Other small files may still snapshot
- if snap_id:
- manifest = (hermes_home / "state-snapshots" / snap_id / "manifest.json")
- assert manifest.exists()
- data = json.loads(manifest.read_text(encoding="utf-8"))
- assert "state.db" not in data.get("files", {})
- assert "state.db" in data.get("failed_dbs", [])
-
- def test_restore_refused_db_is_not_counted(self, hermes_home, monkeypatch):
- """A refused live-safe restore (holder detected, backup leg failed) must
- not be counted as a restored file — `hermes import` reports it, and
- /snapshot restore must not claim success for that file either."""
- import hermes_cli.backup as backup_mod
- from hermes_cli.backup import create_quick_snapshot, restore_quick_snapshot
-
- snap_id = create_quick_snapshot(hermes_home=hermes_home)
- monkeypatch.setattr(backup_mod, "_safe_restore_db", lambda src, dst: False)
- restored_log: list[str] = []
- real_info = backup_mod.logger.info
- monkeypatch.setattr(
- backup_mod.logger, "info",
- lambda msg, *a, **kw: restored_log.append(msg % a if a else msg) or real_info(msg, *a, **kw),
- )
+ # Other small files still snapshot; the failed DB is recorded, not silently dropped.
+ assert snap_id
+ manifest = (hermes_home / "state-snapshots" / snap_id / "manifest.json")
+ data = json.loads(manifest.read_text(encoding="utf-8"))
+ assert "state.db" not in data.get("files", {})
+ assert "state.db" in data.get("failed_dbs", [])
- restore_quick_snapshot(snap_id, hermes_home=hermes_home)
-
- manifest = json.loads(
- (backup_mod._quick_snapshot_root(hermes_home) / snap_id / "manifest.json").read_text()
- )
- non_db = [rel for rel in manifest.get("files", {}) if not rel.endswith(".db")]
- summary = [line for line in restored_log if line.startswith("Restored ")]
- assert summary, restored_log
- assert summary[-1].startswith(f"Restored {len(non_db)} files"), summary[-1]
def test_restore_state_db_live_connection(self, hermes_home):
"""Restoring state.db must update data visible through a live connection.
@@ -1618,9 +1508,6 @@ class TestQuickSnapshot:
)
assert second_id in snap_ids
- out = capsys.readouterr().out
- assert "skipping state.db" in out.lower() or "skipping snapshot prune" in out.lower()
-
class TestQuickSnapshotProjectsKanban:
"""Regression for #52889: projects.db / kanban.db must survive an upgrade.
@@ -1876,10 +1763,7 @@ class TestRunPreUpdateBackup:
self._set_mode(hermes_home, "full")
from hermes_cli.update_cmd import _run_pre_update_backup
snap_id = _run_pre_update_backup(Namespace(no_backup=False, backup=False))
- out = capsys.readouterr().out
assert snap_id is not None
- assert "Pre-update snapshot" in out
- assert "Creating pre-update backup" in out
assert len(self._zips(hermes_home)) == 1
@@ -2299,7 +2183,6 @@ class TestImportHonorsHermesHomeOverride:
import argparse
- import hermes_constants
from hermes_cli import backup as backup_mod
monkeypatch.setattr(
@@ -2437,28 +2320,7 @@ class TestImportLiveSessionDatabase:
assert os.stat(live_db).st_ino == inode_before
assert _count_rows(live_db) == (2, 4)
- def test_older_backup_reports_replaced_sessions(self, tmp_path, monkeypatch, capsys):
- """Importing a backup that predates recorded work says what it dropped."""
- from hermes_cli.backup import run_import
-
- home, live_db, zip_path = self._prepare(tmp_path, monkeypatch)
- run_import(Namespace(zipfile=str(zip_path), force=True))
-
- out = capsys.readouterr().out
- assert "Session data replaced by older backup contents" in out
- assert "3 session(s) / 12 message(s) -> 2 / 4" in out
-
- def test_newer_backup_reports_nothing(self, tmp_path, monkeypatch, capsys):
- """No warning when the import does not shrink the database."""
- from hermes_cli.backup import run_import
- home, live_db, zip_path = self._prepare(
- tmp_path, monkeypatch, live=(1, 1), backup=(3, 4)
- )
- run_import(Namespace(zipfile=str(zip_path), force=True))
-
- out = capsys.readouterr().out
- assert "Session data replaced by older backup contents" not in out
def test_refused_restore_is_reported_and_leaves_db_intact(
self, tmp_path, monkeypatch, capsys
@@ -2471,9 +2333,6 @@ class TestImportLiveSessionDatabase:
backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True))
- out = capsys.readouterr().out
- assert "files skipped" in out
- assert "state.db" in out
# The pre-import database is still the one on disk.
assert _count_rows(live_db) == (3, 12)
diff --git a/tests/hermes_cli/test_backup_path_errors.py b/tests/hermes_cli/test_backup_path_errors.py
index 74b8ed13bc9..9ffb5e09d66 100644
--- a/tests/hermes_cli/test_backup_path_errors.py
+++ b/tests/hermes_cli/test_backup_path_errors.py
@@ -6,7 +6,6 @@ print a one-line error and exit 1 instead.
"""
from argparse import Namespace
-from pathlib import Path
import pytest
@@ -34,5 +33,4 @@ def test_backup_unwritable_parent_errors_cleanly(tmp_path, monkeypatch, capsys):
assert exc.value.code == 1
out = capsys.readouterr().out
- assert "cannot write backup" in out.lower()
assert "Traceback" not in out
diff --git a/tests/hermes_cli/test_bang_shell_mode.py b/tests/hermes_cli/test_bang_shell_mode.py
index ae74a1a0edb..08d11ba35af 100644
--- a/tests/hermes_cli/test_bang_shell_mode.py
+++ b/tests/hermes_cli/test_bang_shell_mode.py
@@ -190,10 +190,6 @@ class TestBangHandlerDispatch:
assert cli.handle_bang_shell("!exit 3") is True
assert any("exited 3" in line for line in _printed(cli))
- def test_zero_exit_prints_no_exit_line(self):
- cli = _make_cli()
- cli.handle_bang_shell("!true")
- assert not any("exited" in line for line in _printed(cli))
def test_disabled_context_falls_through(self, monkeypatch):
"""Gateway sessions must not execute bang commands."""
@@ -316,16 +312,6 @@ class TestBangLeavesHistoryByteIdentical:
_SEED_HISTORY, sort_keys=True
)
- def test_role_alternation_is_preserved_across_many_bangs(self):
- cli = _make_cli(history=copy.deepcopy(_SEED_HISTORY))
- before = json.dumps(cli.conversation_history, sort_keys=True)
-
- for _ in range(5):
- cli.handle_bang_shell("!echo repeated")
-
- assert json.dumps(cli.conversation_history, sort_keys=True) == before
- roles = [m["role"] for m in cli.conversation_history]
- assert roles == ["system", "user", "assistant", "user", "assistant", "tool"]
diff --git a/tests/hermes_cli/test_banner.py b/tests/hermes_cli/test_banner.py
index 70f3b4b1ccd..5a2be7a13b0 100644
--- a/tests/hermes_cli/test_banner.py
+++ b/tests/hermes_cli/test_banner.py
@@ -25,66 +25,13 @@ def test_cprint_falls_back_to_plain_print_when_prompt_toolkit_has_no_console(cap
-def test_build_welcome_banner_title_falls_back_when_no_tag():
- """Without a resolvable tag, the panel title renders as plain text (no hyperlink escape)."""
- import io
- from unittest.mock import patch as _patch
- import hermes_cli.banner as _banner
- import model_tools as _mt
- import tools.mcp_tool as _mcp
- from tools import mcp_tool_discovery as _mcp_discovery
-
- _banner._latest_release_cache = None
- buf = io.StringIO()
- with (
- _patch.object(_mt, "check_tool_availability", return_value=(["web"], [])),
- _patch.object(_banner, "get_available_skills", return_value={}),
- _patch.object(_banner, "get_update_result", return_value=None),
- _patch.object(_mcp_discovery, "get_mcp_status", return_value=[]),
- _patch.object(_banner, "get_latest_release_tag", return_value=None),
- ):
- console = Console(file=buf, force_terminal=True, color_system="truecolor", width=160)
- _banner.build_welcome_banner(
- console=console, model="x", cwd="/tmp",
- session_id="abc123",
- tools=[{"function": {"name": "read_file"}}],
- get_toolset_for_tool=lambda n: "file",
- )
- raw = buf.getvalue()
- assert "Hermes Agent v" in raw, "Version label missing from title"
- assert "\x1b]8;" not in raw, "OSC-8 hyperlink should not be emitted without a tag"
-def test_build_welcome_banner_non_moa_unchanged(tmp_path, monkeypatch):
- """A normal provider still renders the bare model slug, no MoA prefix."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- (tmp_path / ".hermes").mkdir()
-
- with (
- patch.object(model_tools, "check_tool_availability", return_value=([], [])),
- patch.object(banner, "get_available_skills", return_value={}),
- patch.object(banner, "get_update_result", return_value=None),
- patch.object(tools.mcp_tool_discovery, "get_mcp_status", return_value=[]),
- ):
- console = Console(record=True, force_terminal=False, color_system=None, width=160)
- banner.build_welcome_banner(
- console=console,
- model="anthropic/claude-opus-4.8",
- cwd="/tmp/project",
- tools=[],
- enabled_toolsets=[],
- provider="openrouter",
- )
-
- out = console.export_text()
- assert "claude-opus-4.8" in out
- assert "MoA:" not in out
-
def test_empty_model_shows_the_free_tier_route_when_it_carries_inference(tmp_path, monkeypatch):
"""The banner prints before credentials resolve, so ``model`` is empty on a fresh install. On the
@@ -111,27 +58,3 @@ def test_empty_model_shows_the_free_tier_route_when_it_carries_inference(tmp_pat
assert "no model configured" in render(False)
-def test_build_welcome_banner_does_not_center_pad_hero_art():
- """A braille hero relies on its own U+2800 padding for symmetry; Rich centering inserts
- ASCII spaces around the left column and distorts the silhouette (#9879). The hero line
- must start flush at the column start."""
- import io
- from types import SimpleNamespace
- from tools import mcp_tool_discovery as _mcp_discovery
-
- skin = SimpleNamespace(banner_hero="[green]\u2800X[/]", banner_logo="")
- buf = io.StringIO()
- with (
- patch.object(model_tools, "check_tool_availability", return_value=([], [])),
- patch.object(banner, "get_available_skills", return_value={}),
- patch.object(banner, "get_update_result", return_value=None),
- patch.object(banner, "get_latest_release_tag", return_value=None),
- patch.object(_mcp_discovery, "get_mcp_status", return_value=[]),
- patch.object(banner, "_active_skin", return_value=skin),
- ):
- console = Console(file=buf, force_terminal=False, color_system=None, width=80)
- banner.build_welcome_banner(console=console, model="m", cwd="/tmp", tools=[],
- get_toolset_for_tool=lambda _: None)
-
- hero_line = next(line for line in buf.getvalue().splitlines() if "\u2800X" in line)
- assert hero_line.startswith("\u2502 \u2800X"), repr(hero_line)
diff --git a/tests/hermes_cli/test_banner_git_state.py b/tests/hermes_cli/test_banner_git_state.py
index 816842ccd1d..f2ef5266abf 100644
--- a/tests/hermes_cli/test_banner_git_state.py
+++ b/tests/hermes_cli/test_banner_git_state.py
@@ -3,42 +3,8 @@ from unittest.mock import MagicMock, patch
-def test_format_banner_version_label_on_upstream_main():
- from hermes_cli import banner
-
- with patch.object(
- banner,
- "get_git_banner_state",
- return_value={"upstream": "b2f477a3", "local": "b2f477a3", "ahead": 0},
- ):
- value = banner.format_banner_version_label()
-
- assert value.endswith("· upstream b2f477a3")
- assert "local" not in value
-
-
-def test_get_git_banner_state_reads_origin_and_head(tmp_path):
- from hermes_cli import banner
-
- repo_dir = tmp_path / "repo"
- (repo_dir / ".git").mkdir(parents=True)
-
- results = {
- ("git", "rev-parse", "--short=8", "origin/main"): MagicMock(returncode=0, stdout="b2f477a3\n"),
- ("git", "rev-parse", "--short=8", "HEAD"): MagicMock(returncode=0, stdout="af8aad31\n"),
- ("git", "rev-list", "--count", "origin/main..HEAD"): MagicMock(returncode=0, stdout="3\n"),
- }
-
- def fake_run(cmd, **kwargs):
- key = tuple(cmd)
- if key not in results:
- raise AssertionError(f"unexpected command: {cmd}")
- return results[key]
- with patch("hermes_cli.banner.subprocess.run", side_effect=fake_run):
- state = banner.get_git_banner_state(repo_dir)
- assert state == {"upstream": "b2f477a3", "local": "af8aad31", "ahead": 3}
def test_check_via_local_git_ssh_fastpath_ahead_not_behind(tmp_path):
@@ -48,7 +14,6 @@ def test_check_via_local_git_ssh_fastpath_ahead_not_behind(tmp_path):
is an ancestor of HEAD — that is "ahead", and reporting it as behind
nudges the user into `hermes update`, which can wipe the carried work.
"""
- from unittest.mock import MagicMock
from hermes_cli import banner
@@ -75,7 +40,6 @@ def test_check_via_local_git_ssh_fastpath_ahead_not_behind(tmp_path):
def test_check_via_local_git_ssh_fastpath_genuinely_behind(tmp_path):
"""SSH fast path reports the exact count (compare API) when behind."""
- from unittest.mock import MagicMock
from hermes_cli import banner
@@ -103,7 +67,6 @@ def test_check_via_local_git_ssh_fastpath_genuinely_behind(tmp_path):
def test_check_via_local_git_ssh_fastpath_offline_keeps_sentinel(tmp_path):
"""Behind + compare API unreachable = honest no-count sentinel, never 1."""
- from unittest.mock import MagicMock
from hermes_cli import banner
diff --git a/tests/hermes_cli/test_banner_skills.py b/tests/hermes_cli/test_banner_skills.py
index 85d028d191b..c3b6a8ba3a9 100644
--- a/tests/hermes_cli/test_banner_skills.py
+++ b/tests/hermes_cli/test_banner_skills.py
@@ -45,18 +45,3 @@ def test_get_available_skills_null_category_becomes_general():
assert result["general"] == ["orphan-skill"]
-def test_get_available_skills_is_memoized():
- """Second call must not re-walk the skills tree (startup perf contract)."""
- import hermes_cli.banner as banner
- calls = []
-
- def fake_find(**kwargs):
- calls.append(1)
- return list(_MOCK_SKILLS)
-
- with patch("tools.skills_tool._find_all_skills", side_effect=fake_find):
- first = banner.get_available_skills()
- second = banner.get_available_skills()
-
- assert first == second
- assert len(calls) == 1
diff --git a/tests/hermes_cli/test_banner_skills_width.py b/tests/hermes_cli/test_banner_skills_width.py
index 7fc2d37c5ec..adee7e48fe4 100644
--- a/tests/hermes_cli/test_banner_skills_width.py
+++ b/tests/hermes_cli/test_banner_skills_width.py
@@ -57,11 +57,3 @@ def test_small_category_shows_all_skills():
assert "+2 more" not in text
-def test_skills_respect_category_label_width():
- """Skills display should account for the category label prefix width."""
- # A category with a long name should have less room for skills
- skills = {"very-long-category-name": [f"skill-{i:02d}" for i in range(10)]}
- text = _build_banner_with_skills(skills, term_width=120)
-
- # Should still show at least some skills
- assert "skill-00" in text
diff --git a/tests/hermes_cli/test_bedrock_model_picker.py b/tests/hermes_cli/test_bedrock_model_picker.py
index f20d6e92974..b6c39db1ce1 100644
--- a/tests/hermes_cli/test_bedrock_model_picker.py
+++ b/tests/hermes_cli/test_bedrock_model_picker.py
@@ -232,16 +232,8 @@ class TestBedrockRegionRouting:
class TestBedrockOverlayRegistration:
"""bedrock entry in HERMES_OVERLAYS is correctly configured."""
- def test_bedrock_overlay_exists(self):
- from hermes_cli.providers import HERMES_OVERLAYS
- assert "bedrock" in HERMES_OVERLAYS
- def test_bedrock_label(self):
- from hermes_cli.providers import get_label
- label = get_label("bedrock")
- assert label # non-empty
- assert "bedrock" in label.lower() or "aws" in label.lower()
def test_bedrock_aliases_resolve(self):
from hermes_cli.providers import normalize_provider
diff --git a/tests/hermes_cli/test_bedrock_region_scoped_picker.py b/tests/hermes_cli/test_bedrock_region_scoped_picker.py
index 37a3a32b38c..1a202ba14eb 100644
--- a/tests/hermes_cli/test_bedrock_region_scoped_picker.py
+++ b/tests/hermes_cli/test_bedrock_region_scoped_picker.py
@@ -6,7 +6,6 @@ eu-central-2 picker produces configs AWS rejects regardless of credentials.
"""
from hermes_cli.model_setup_flows_bedrock import (
- BEDROCK_GEO_PREFIXES,
bedrock_model_routable_from_region,
bedrock_region_geo_prefix,
)
@@ -36,17 +35,3 @@ class TestRoutableFromRegion:
-class TestGeoPrefixContract:
- def test_every_geo_prefix_maps_to_a_routable_region_or_is_alias(self):
- """Invariant: each geo prefix is either reachable from some region's
- geo mapping or an ap-family alias — no dead entries."""
- mapped = {
- bedrock_region_geo_prefix(r)
- for r in (
- "us-east-1", "eu-central-2", "ap-southeast-1",
- "ca-central-1", "sa-east-1", "me-south-1", "af-south-1",
- )
- }
- ap_aliases = {"apac.", "jp."}
- for prefix in BEDROCK_GEO_PREFIXES:
- assert prefix in mapped or prefix in ap_aliases
diff --git a/tests/hermes_cli/test_billing_cli.py b/tests/hermes_cli/test_billing_cli.py
deleted file mode 100644
index fa1679af527..00000000000
--- a/tests/hermes_cli/test_billing_cli.py
+++ /dev/null
@@ -1,124 +0,0 @@
-"""Tests for the /billing CLI handler (cli.py::_show_billing).
-
-Focus on the non-interactive (no live prompt_toolkit app) path — the same
-discipline as the /credits non-interactive test: it must render text, never
-invoke the modal (which would read the slash-worker's JSON-RPC stdin and hang).
-Plus role/kill-switch gating and logged-out handling.
-"""
-
-from __future__ import annotations
-
-from decimal import Decimal
-
-import pytest
-
-import agent.billing_view as bv
-from agent.billing_view import BillingState, CardInfo, MonthlyCap
-from cli import HermesCLI
-
-
-def cli():
- obj = HermesCLI.__new__(HermesCLI) # bypass __init__ (no full app needed)
- obj._app = None # non-interactive: forces the text path
- return obj
-
-
-def _boom_modal(*a, **kw):
- raise AssertionError("modal must NOT be called in non-interactive mode")
-
-
-
-
-
-
-
-
-# ── Card visibility + the add-card path (inline w/ NAS card-resolver) ──
-
-
-def _scripted(*responses):
- it = iter(responses)
-
- def _modal(self, **kw):
- return next(it)
-
- return _modal
-
-
-def test_topup_overview_splits_onetime_from_automatic_copy(cli, monkeypatch, capsys):
- # (c): the interactive /topup overview states the one-time-vs-automatic
- # distinction up front in each first sentence, and keeps "credits" out of the
- # dollars-only surface. Auto-reload OFF → the automatic line omits amounts.
- cli._app = object() # interactive → reaches the split-copy explainer
- state = BillingState(
- logged_in=True, role="OWNER", balance_usd=Decimal("50"),
- cli_billing_enabled=True, charge_presets=(Decimal("25"),),
- card=CardInfo(brand="Visa", last4="4242"),
- portal_url="https://portal/billing",
- )
- monkeypatch.setattr(bv, "build_billing_state", lambda *a, **kw: state)
- # Overview prints the explainer, then the action modal → back out with "cancel".
- monkeypatch.setattr(HermesCLI, "_prompt_text_input_modal", _scripted("cancel"), raising=False)
- cli._show_billing("/topup")
- out = capsys.readouterr().out
-
- assert "Add funds now — a single charge, added to your balance today." in out
- assert "Refill when low — charges your card automatically when your balance falls below" in out
- # Dollars-only surface: no "credits" word leaks into /topup.
- assert "credits" not in out.lower()
-
-
-def test_topup_automatic_copy_generic_when_amounts_missing(cli, monkeypatch, capsys):
- # (5): auto-reload "enabled" but amounts absent (partial response) → generic
- # copy, never "charges — automatically … below —.".
- from agent.billing_view import AutoReload
-
- cli._app = object()
- state = BillingState(
- logged_in=True, role="OWNER", balance_usd=Decimal("50"),
- cli_billing_enabled=True, charge_presets=(Decimal("25"),),
- card=CardInfo(brand="Visa", last4="4242"),
- auto_reload=AutoReload(enabled=True, threshold_usd=None, reload_to_usd=None),
- portal_url="https://portal/billing",
- )
- monkeypatch.setattr(bv, "build_billing_state", lambda *a, **kw: state)
- monkeypatch.setattr(HermesCLI, "_prompt_text_input_modal", _scripted("cancel"), raising=False)
- cli._show_billing("/topup")
- out = capsys.readouterr().out
-
- assert (
- "Refill when low — charges your card automatically when your balance "
- "falls below the amount you set."
- ) in out
- assert "charges — automatically" not in out
-
-
-
-
-
-
-
-
-def test_buy_flow_no_card_back_abandons(cli, monkeypatch, capsys):
- cli._app = object()
- nocard = BillingState(
- logged_in=True, role="OWNER", cli_billing_enabled=True,
- charge_presets=(Decimal("25"),), card=None,
- portal_url="https://portal/billing",
- )
- calls = {"n": 0}
-
- def _no_fetch(*a, **kw):
- calls["n"] += 1
- return nocard
-
- monkeypatch.setattr(bv, "build_billing_state", _no_fetch)
- monkeypatch.setattr(HermesCLI, "_prompt_text_input_modal", _scripted("cancel"), raising=False)
-
- cli._billing_buy_flow(nocard)
- out = capsys.readouterr().out
-
- assert "Add a card first" in out
- assert "Cancelled. No funds added." in out
- assert calls["n"] == 0 # backed out before any re-check
diff --git a/tests/hermes_cli/test_bitwarden_status.py b/tests/hermes_cli/test_bitwarden_status.py
deleted file mode 100644
index d9a86305ffe..00000000000
--- a/tests/hermes_cli/test_bitwarden_status.py
+++ /dev/null
@@ -1,110 +0,0 @@
-from __future__ import annotations
-
-from argparse import Namespace
-from pathlib import Path
-
-
-def _bitwarden_config(*, enabled: bool = True, server_url: str = "") -> dict:
- return {
- "secrets": {
- "bitwarden": {
- "enabled": enabled,
- "access_token_env": "BWS_ACCESS_TOKEN",
- "project_id": "proj-123",
- "server_url": server_url,
- "cache_ttl_seconds": 300,
- "override_existing": True,
- "auto_install": True,
- }
- }
- }
-
-
-def test_status_surfaces_failed_token_validation(monkeypatch, capsys):
- from hermes_cli import secrets_cli
-
- seen = {}
-
- monkeypatch.setattr(
- secrets_cli,
- "load_config",
- lambda: _bitwarden_config(server_url="https://vault.bitwarden.eu"),
- )
- monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.invalid-token")
- monkeypatch.setattr(
- secrets_cli.bw,
- "find_bws",
- lambda install_if_missing=False: Path("/tmp/bws"),
- )
- monkeypatch.setattr(secrets_cli, "_bws_version", lambda _binary: "bws v2.1.0")
-
- def _fake_list_projects(binary, token, console, *, server_url=""):
- seen["binary"] = binary
- seen["token"] = token
- seen["server_url"] = server_url
- console.print(" bws project list failed: Doesn't contain a decryption key")
- console.print(
- " This usually means the access token is wrong or revoked. "
- "Double-check it in the Bitwarden web app."
- )
- return None
-
- monkeypatch.setattr(secrets_cli, "_list_projects", _fake_list_projects)
-
- assert secrets_cli.cmd_status(Namespace()) == 0
-
- out = capsys.readouterr().out
- assert "Token in env" in out
- assert "Token validation" in out
- assert "failed" in out
- assert "Doesn't contain a decryption key" in out
- assert "wrong or revoked" in out
- assert seen == {
- "binary": Path("/tmp/bws"),
- "token": "0.invalid-token",
- "server_url": "https://vault.bitwarden.eu",
- }
-
-
-def test_status_warns_when_token_does_not_look_like_bsm_token(monkeypatch, capsys):
- from hermes_cli import secrets_cli
-
- monkeypatch.setattr(secrets_cli, "load_config", lambda: _bitwarden_config())
- monkeypatch.setenv("BWS_ACCESS_TOKEN", "not-a-bitwarden-token")
- monkeypatch.setattr(
- secrets_cli.bw,
- "find_bws",
- lambda install_if_missing=False: Path("/tmp/bws"),
- )
- monkeypatch.setattr(secrets_cli, "_bws_version", lambda _binary: "bws v2.1.0")
- monkeypatch.setattr(
- secrets_cli,
- "_list_projects",
- lambda binary, token, console, *, server_url="": [],
- )
-
- assert secrets_cli.cmd_status(Namespace()) == 0
-
- out = capsys.readouterr().out
- assert "Token validation" in out
- assert "passed" in out
- assert "doesn't start with '0.'" in out
-
-
-def test_status_marks_validation_as_not_checked_without_bws_binary(monkeypatch, capsys):
- from hermes_cli import secrets_cli
-
- monkeypatch.setattr(secrets_cli, "load_config", lambda: _bitwarden_config())
- monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.token-present")
- monkeypatch.setattr(
- secrets_cli.bw,
- "find_bws",
- lambda install_if_missing=False: None,
- )
-
- assert secrets_cli.cmd_status(Namespace()) == 0
-
- out = capsys.readouterr().out
- assert "Token validation" in out
- assert "not checked" in out
- assert "bws not installed" in out
diff --git a/tests/hermes_cli/test_bracketed_paste_timeout.py b/tests/hermes_cli/test_bracketed_paste_timeout.py
index 58eb2184961..873d0c3e7ca 100644
--- a/tests/hermes_cli/test_bracketed_paste_timeout.py
+++ b/tests/hermes_cli/test_bracketed_paste_timeout.py
@@ -4,46 +4,11 @@ Verifies the production helper in cli.py monkey-patches prompt_toolkit's
Vt100Parser.feed() so the parser auto-escapes from bracketed-paste mode when
the ESC[201~ end mark is never received.
"""
-import ast
import importlib
-import logging
import time
-from pathlib import Path
from unittest.mock import MagicMock
-from prompt_toolkit.keys import Keys
-
-
-ROOT = Path(__file__).resolve().parents[2]
-CLI_PATH = ROOT / "hermes_cli" / "cli_terminal_input.py"
-
-
-def _load_production_patch_helper():
- """Load _apply_bracketed_paste_timeout_patch (hermes_cli/cli_terminal_input.py) without importing cli.
-
- Importing cli.py pulls optional runtime deps that aren't required for this
- parser-level regression. AST-loading the exact helper keeps the test tied
- to production code while avoiding unrelated import side effects. If the
- production helper is removed, this test fails.
- """
- source = CLI_PATH.read_text(encoding="utf-8")
- tree = ast.parse(source)
- helper_node = next(
- (
- node
- for node in tree.body
- if isinstance(node, ast.FunctionDef)
- and node.name == "_apply_bracketed_paste_timeout_patch"
- ),
- None,
- )
- assert helper_node is not None, (
- "hermes_cli/cli_terminal_input.py must define _apply_bracketed_paste_timeout_patch()"
- )
- helper_source = ast.get_source_segment(source, helper_node)
- namespace = {"time": time, "logger": logging.getLogger("test.cli")}
- exec(helper_source, namespace)
- return namespace["_apply_bracketed_paste_timeout_patch"]
+from hermes_cli.cli_terminal_input import _apply_bracketed_paste_timeout_patch
def _reset_and_apply_production_patch():
@@ -55,7 +20,7 @@ def _reset_and_apply_production_patch():
# does not redefine, so clear Hermes' sentinel before re-applying.
if hasattr(vt100_mod, "_hermes_bp_timeout_patched"):
delattr(vt100_mod, "_hermes_bp_timeout_patched")
- _load_production_patch_helper()()
+ _apply_bracketed_paste_timeout_patch()
assert getattr(vt100_mod, "_hermes_bp_timeout_patched", False)
return vt100_mod
diff --git a/tests/hermes_cli/test_branch_command.py b/tests/hermes_cli/test_branch_command.py
index 053e605e513..2c1ac73a9fd 100644
--- a/tests/hermes_cli/test_branch_command.py
+++ b/tests/hermes_cli/test_branch_command.py
@@ -66,17 +66,6 @@ def cli_instance(tmp_path, session_db):
class TestBranchCommandCLI:
"""Test the /branch command logic for the CLI."""
- def test_branch_creates_new_session(self, cli_instance, session_db):
- """Branching should create a new session in the DB."""
- from cli import HermesCLI
-
- # Call the real method on the mock, using the real implementation
- HermesCLI._handle_branch_command(cli_instance, "/branch")
-
- # Verify a new session was created
- assert cli_instance.session_id != "20260403_120000_abc123"
- new_session = session_db.get_session(cli_instance.session_id)
- assert new_session is not None
def test_failed_branch_creation_leaves_original_session_open(self, cli_instance, session_db):
"""Branching is child-first: when create_session fails the user stays on the original
@@ -125,13 +114,6 @@ class TestBranchCommandCLI:
assert cli_instance.session_id == "20260403_120000_abc123"
- def test_branch_sets_resumed_flag(self, cli_instance, session_db):
- """Branch should set _resumed=True to prevent auto-title generation."""
- from cli import HermesCLI
-
- HermesCLI._handle_branch_command(cli_instance, "/branch")
-
- assert cli_instance._resumed is True
def test_branch_fires_on_session_switch_hook(self, cli_instance, session_db):
@@ -163,21 +145,6 @@ class TestBranchCommandCLI:
-class TestBranchCommandDef:
- """Test the CommandDef registration for /branch."""
-
- def test_branch_in_registry(self):
- """The branch command should be in the command registry."""
- from hermes_cli.commands import COMMAND_REGISTRY
- names = [c.name for c in COMMAND_REGISTRY]
- assert "branch" in names
-
-
- def test_branch_in_session_category(self):
- """The branch command should be in the Session category."""
- from hermes_cli.commands import COMMAND_REGISTRY
- branch = next(c for c in COMMAND_REGISTRY if c.name == "branch")
- assert branch.category == "Session"
class TestBranchFlushesBeforeEndSession:
diff --git a/tests/hermes_cli/test_budget_source.py b/tests/hermes_cli/test_budget_source.py
deleted file mode 100644
index 744997f2be1..00000000000
--- a/tests/hermes_cli/test_budget_source.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Launch and growth decisions must price against CAPACITY, not live-free
-VRAM. Both execute through a server bounce — the outgoing instance's memory
-is freed before the new one loads — so a probe that reads the predecessor's
-(or the grown model's own) residency as 'gone' vetoes configurations that
-genuinely fit. Symptom when this regresses: a model the pane promised
-'144K on GPU' launches with its weights pinned to CPU and single-digit
-tokens/s while the card sits 60% empty."""
-
-from __future__ import annotations
-
-import ast
-import inspect
-
-
-def _planning_probe_calls(source: str) -> list[bool]:
- """Every probe_budget(...) call's planning= value in the source."""
- tree = ast.parse(source)
- out = []
- for node in ast.walk(tree):
- if (isinstance(node, ast.Call)
- and getattr(node.func, "id", getattr(node.func, "attr", ""))
- == "probe_budget"):
- planning = any(
- kw.arg == "planning"
- and isinstance(kw.value, ast.Constant)
- and kw.value.value is True
- for kw in node.keywords)
- out.append(planning)
- return out
-
-
-def test_bootstrap_presets_price_against_capacity():
- import hermes_cli.local_runtime.bootstrap as bootstrap
-
- calls = _planning_probe_calls(inspect.getsource(bootstrap))
- assert calls, "bootstrap no longer probes a budget? update this test"
- assert all(calls), (
- "bootstrap prices launch decisions against live-free VRAM; a "
- "restart/refresh probes while the outgoing server still holds the "
- "card, pinning fitting models to CPU")
-
-
-def test_growth_refit_prices_against_capacity():
- import hermes_cli.local_runtime.growth as growth
-
- calls = _planning_probe_calls(inspect.getsource(growth))
- assert calls, "growth no longer probes a budget? update this test"
- assert all(calls), (
- "growth re-fits against live-free VRAM; the grown model's own "
- "residency reads as unavailable and vetoes rungs that fit the "
- "post-bounce card")
diff --git a/tests/hermes_cli/test_busy_input_mode_command.py b/tests/hermes_cli/test_busy_input_mode_command.py
index 9eed9a2079c..750f826a9ca 100644
--- a/tests/hermes_cli/test_busy_input_mode_command.py
+++ b/tests/hermes_cli/test_busy_input_mode_command.py
@@ -83,16 +83,3 @@ class TestHandleBusyCommand(unittest.TestCase):
self.assertIn("Usage: /busy", printed)
-class TestBusyCommandRegistry(unittest.TestCase):
- def test_busy_in_registry(self):
- from hermes_cli.commands import COMMAND_REGISTRY
-
- names = [c.name for c in COMMAND_REGISTRY]
- assert "busy" in names
-
- def test_busy_subcommands_documented(self):
- from hermes_cli.commands import COMMAND_REGISTRY
-
- busy = next(c for c in COMMAND_REGISTRY if c.name == "busy")
- assert busy.args_hint == "[queue|steer|interrupt|status]"
- assert busy.category == "Configuration"
diff --git a/tests/hermes_cli/test_busy_policy_invariants.py b/tests/hermes_cli/test_busy_policy_invariants.py
index db2fc0c264c..120f431c2e5 100644
--- a/tests/hermes_cli/test_busy_policy_invariants.py
+++ b/tests/hermes_cli/test_busy_policy_invariants.py
@@ -10,41 +10,9 @@ rather than hand-maintained.
from hermes_cli.commands import (
ACTIVE_SESSION_BYPASS_COMMANDS,
COMMAND_REGISTRY,
- VALID_BUSY_POLICIES,
is_interrupt_then_dispatch,
- should_bypass_active_session,
)
-# The hand-written frozenset as it existed before the busy_policy refactor.
-# This is a behavior contract, not a snapshot: the derived set must remain a
-# SUPERSET of these names (each had an explicit mid-run handler in the old
-# Guard-2 if-chain and must keep bypassing the busy-reject catch-all).
-_HISTORICAL_BYPASS_NAMES = frozenset(
- {
- "agents",
- "approve",
- "bg",
- "btw",
- "commands",
- "deny",
- "help",
- "new",
- "profile",
- "queue",
- "restart",
- "status",
- "steer",
- "stop",
- "update",
- "version",
- }
-)
-
-
-
-
-
-
def test_bypass_set_is_derived_from_registry():
expected = frozenset(
cmd.name for cmd in COMMAND_REGISTRY if cmd.busy_policy != "reject"
diff --git a/tests/hermes_cli/test_catalog_reachability.py b/tests/hermes_cli/test_catalog_reachability.py
deleted file mode 100644
index 1b7fa5b9915..00000000000
--- a/tests/hermes_cli/test_catalog_reachability.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""Catalog reachability: every entry's repo and files must exist upstream.
-
-Existence is the contract; SIZES are advisory (they feed the estimator and
-progress bars, and downloads deliberately tolerate a stale size when
-upstream re-uploads — completeness is judged against the server's own
-declared length, never the catalog). Size drift prints as a warning so a
-catalog refresh can be batched deliberately; only a MISSING file or repo
-fails.
-
-Network-marked (skipped in hermetic CI unless explicitly enabled) — this is
-the test that catches wrong repo names (the Nemotron 401) and moved files.
-Run before any catalog commit:
-
- HERMES_TEST_NETWORK=1 scripts/run_tests.sh tests/hermes_cli/test_catalog_reachability.py
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import urllib.request
-
-import pytest
-
-pytestmark = pytest.mark.skipif(
- not os.environ.get("HERMES_TEST_NETWORK"),
- reason="network test; set HERMES_TEST_NETWORK=1 to run",
-)
-
-
-def test_every_catalog_file_resolves():
- from hermes_cli.local_runtime.catalog import CATALOG
-
- problems = []
- drift = []
- for entry in CATALOG:
- url = f"https://huggingface.co/api/models/{entry.repo}/tree/main?recursive=true"
- try:
- with urllib.request.urlopen(url, timeout=30) as r:
- files = {f["path"]: f.get("size") for f in json.load(r)}
- except Exception as exc: # noqa: BLE001
- problems.append(f"{entry.id}: repo {entry.repo} unreachable ({exc})")
- continue
- for variant in entry.variants:
- for asset in entry.download_files(variant):
- if asset.path not in files:
- problems.append(
- f"{entry.id}/{variant.quant}: {asset.path} not in {entry.repo}")
- continue
- live_size = files[asset.path]
- if live_size and live_size != asset.size_bytes:
- drift.append(
- f"{entry.id}/{variant.quant}: size drift on {asset.path} — "
- f"catalog {asset.size_bytes} vs live {live_size}")
- if drift:
- print("\nADVISORY size drift (downloads tolerate this; refresh when convenient):")
- print("\n".join(drift))
- assert not problems, "\n".join(problems)
-
diff --git a/tests/hermes_cli/test_catalog_variants.py b/tests/hermes_cli/test_catalog_variants.py
index bee1f3e8dd5..9245d43b9b2 100644
--- a/tests/hermes_cli/test_catalog_variants.py
+++ b/tests/hermes_cli/test_catalog_variants.py
@@ -4,7 +4,6 @@ synthetic budgets."""
from __future__ import annotations
-import pytest
from hermes_cli.local_runtime.catalog import (
CATALOG,
@@ -86,7 +85,7 @@ def test_small_card_gets_q4_spilled_never_below():
assert choice is not None
assert not choice.zero_spill
assert choice.reason_key == "smallest-fits-spilled"
- assert choice.variant.quant == "UD-Q4_K_M"
+ assert choice.variant.quant == entry.variants[-1].quant
def test_frontier_model_refused_on_consumer_card_offered_on_big_ram():
@@ -114,18 +113,6 @@ def test_selection_accounts_for_kv_not_just_weights():
assert not choice.zero_spill, "KV cost ignored — weights alone can't zero-spill"
-def test_floor_fallback_when_target_window_does_not_fit():
- """Cards where nothing clears the target keep the old rule: highest
- quality that zero-spills at the 64K floor (reason 'best-fits'), never
- a needless step down."""
- entry = catalog_by_id()["qwen3.8-27b"]
- # ~23.5 GiB usable: Q4 weights (16.7 GiB in-memory) + floor KV (2.2)
- # + overhead (1.5 + 0.9 mmproj + ~1.0 MTP-posture logits) fits, but
- # the 144K-target KV (+2.7 more) does not.
- choice = select_variant(entry, budget(23.5))
- assert choice is not None and choice.zero_spill
- assert choice.reason_key == "best-fits"
- assert choice.variant.quant == "UD-Q4_K_M"
def test_target_never_degrades_below_floor_choice():
diff --git a/tests/hermes_cli/test_certifi_repair.py b/tests/hermes_cli/test_certifi_repair.py
index 90fc72d98d0..a0a1d2a8422 100644
--- a/tests/hermes_cli/test_certifi_repair.py
+++ b/tests/hermes_cli/test_certifi_repair.py
@@ -20,7 +20,6 @@ import sys
import types
from pathlib import Path
-import pytest
import hermes_cli._early_recovery as er
import subprocess
@@ -131,7 +130,6 @@ class TestUpdateProbeScriptChecksBundle:
class TestDoctorCertificates:
def test_broken_bundle_fails_without_fix(self, monkeypatch, capsys, tmp_path):
- from hermes_cli import doctor as doctor_mod
monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "missing.pem"))
issues = []
@@ -142,7 +140,6 @@ class TestDoctorCertificates:
assert any("doctor --fix" in i for i in issues)
def test_fix_reinstalls_certifi_and_reverifies(self, monkeypatch, capsys, tmp_path):
- from hermes_cli import doctor as doctor_mod
# First verification fails, post-reinstall verification succeeds.
calls = {"verify": 0, "pip": []}
@@ -182,7 +179,6 @@ class TestDoctorCertificates:
def test_healthy_bundle_never_touches_pip(self, monkeypatch, capsys):
- from hermes_cli import doctor as doctor_mod
def _fail_run(*a, **k):
raise AssertionError("healthy bundle must not trigger a reinstall")
@@ -198,16 +194,3 @@ class TestDoctorCertificates:
# =========================================================================
-class TestSslGuardRepairHint:
- def test_missing_bundle_error_mentions_doctor_fix(self, monkeypatch, tmp_path):
- import certifi
-
- from agent.errors import SSLConfigurationError
- from agent.ssl_guard import verify_ca_bundle
-
- monkeypatch.setattr(certifi, "where", lambda: str(tmp_path / "gone.pem"))
- with pytest.raises(SSLConfigurationError) as excinfo:
- verify_ca_bundle()
- message = str(excinfo.value)
- assert "hermes doctor --fix" in message
- assert "certifi" in message
diff --git a/tests/hermes_cli/test_chat_q_exit_clear.py b/tests/hermes_cli/test_chat_q_exit_clear.py
index 6ad0c4674eb..bda4b168569 100644
--- a/tests/hermes_cli/test_chat_q_exit_clear.py
+++ b/tests/hermes_cli/test_chat_q_exit_clear.py
@@ -10,29 +10,6 @@ import cli as cli_mod
# ── A3.1 Test-First: verify _clear_terminal_on_exit gating ──────────────────
-def test_print_exit_summary_clears_screen_by_default(monkeypatch):
- """Default behavior: _print_exit_summary() calls _clear_terminal_on_exit()."""
- calls = []
-
- class FakeCLI:
- conversation_history = []
- session_start = None
-
- def _clear_terminal_on_exit(self):
- calls.append("clear")
-
- monkeypatch.setattr(cli_mod, "datetime", SimpleNamespace(
- now=lambda: SimpleNamespace(
- __sub__=lambda self, other: SimpleNamespace(
- total_seconds=lambda: 0
- )
- )
- ))
-
- fake = FakeCLI()
- cli_mod.HermesCLI._print_exit_summary(fake) # default clear_screen=True
-
- assert "clear" in calls, "_clear_terminal_on_exit should be called by default"
def test_print_exit_summary_skips_clear_when_clear_screen_false(monkeypatch):
@@ -107,14 +84,8 @@ def test_single_query_main_skips_clear_on_exit_summary(monkeypatch):
cli_mod.main(query="hello", quiet=False, toolsets="terminal")
assert exc_info.value.code == 0
- assert calls == [
- ("claim", "cli", False),
- "query-label",
- "advisories",
- ("chat", "hello", None),
- ("summary", False), # <-- clear_screen=False for single-query
- ("finalize", "sq-test"),
- ]
+ assert ("summary", False) in calls # clear_screen=False for single-query
+ assert ("summary", True) not in calls
assert len(clear_calls) == 0, (
"_clear_terminal_on_exit must NOT be called in single-query mode"
)
diff --git a/tests/hermes_cli/test_chat_query_file.py b/tests/hermes_cli/test_chat_query_file.py
index 4ce5f876e02..ecdd7a42d50 100644
--- a/tests/hermes_cli/test_chat_query_file.py
+++ b/tests/hermes_cli/test_chat_query_file.py
@@ -13,7 +13,6 @@ from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
-HOSTILE = 'hi "there" $(touch /tmp/pwned_by_dm_test) `id` \\ and a\nsecond line'
def _parse(argv):
@@ -34,19 +33,6 @@ def test_chat_parser_accepts_query_file():
assert args.query is None
-def test_query_file_reads_hostile_text_verbatim(tmp_path, monkeypatch):
- """The file body must reach args.query byte-identical — no shell pass."""
- f = tmp_path / "dm.txt"
- f.write_text(HOSTILE, encoding="utf-8")
-
- # Exercise the exact resolution block in hermes_cli.main by simulating it:
- # the block reads the file into args.query before dispatch.
- args = _parse(["chat", "--query-file", str(f)])
- assert args.query_file is not None
- body = Path(args.query_file).read_text(encoding="utf-8")
- assert body == HOSTILE
- assert "$(touch" in body # preserved, not executed
- assert not Path("/tmp/pwned_by_dm_test").exists()
def test_query_and_query_file_mutually_exclusive(tmp_path):
@@ -60,27 +46,3 @@ def test_query_and_query_file_mutually_exclusive(tmp_path):
assert exc.value.code == 2
-def test_bot_mode_protocol_never_inlines_message_into_shell():
- """The DM transport must use --query-file / stdin, not -q "…" inlining.
-
- The transport moved from prompt-injected instructions (bot_mode_probe)
- to the message_agent tool (bot_mode_dm) in Aug 2026 — the invariant now
- holds on the tool's command builder, and the probe must no longer teach
- any shellout at all.
- """
- sys.path.insert(0, str(REPO))
- try:
- import importlib
-
- dm = importlib.import_module("tools.bot_mode_dm")
- src = Path(dm.__file__).read_text(encoding="utf-8")
- probe = importlib.import_module("tools.bot_mode_probe")
- probe_src = Path(probe.__file__).read_text(encoding="utf-8")
- finally:
- sys.path.remove(str(REPO))
- assert "--query-file" in src
- assert '-q "Message from' not in src
- assert 'dm <peer>/<agent-name> "Message from' not in src
- # The protocol section teaches the tool, never a hand-rolled shellout.
- assert "message_agent" in probe_src
- assert "--query-file /tmp/dm.txt" not in probe_src
diff --git a/tests/hermes_cli/test_claw.py b/tests/hermes_cli/test_claw.py
index 01af25c2dcc..b6e4f008aa7 100644
--- a/tests/hermes_cli/test_claw.py
+++ b/tests/hermes_cli/test_claw.py
@@ -123,24 +123,6 @@ class TestArchiveDirectory:
# ---------------------------------------------------------------------------
-class TestClawCommand:
- """Test the claw_command router."""
-
- def test_routes_to_migrate(self):
- args = Namespace(claw_action="migrate", source=None, dry_run=True,
- preset="full", overwrite=False, migrate_secrets=False,
- workspace_target=None, skill_conflict="skip", yes=False)
- with patch.object(claw_mod, "_cmd_migrate") as mock:
- claw_mod.claw_command(args)
- mock.assert_called_once_with(args)
-
-
- def test_shows_help_for_no_action(self, capsys):
- args = Namespace(claw_action=None)
- claw_mod.claw_command(args)
- captured = capsys.readouterr()
- assert "migrate" in captured.out
- assert "cleanup" in captured.out
# ---------------------------------------------------------------------------
@@ -163,30 +145,6 @@ class TestCmdMigrate:
- def test_handles_migration_error(self, tmp_path, capsys):
- openclaw_dir = tmp_path / ".openclaw"
- openclaw_dir.mkdir()
- config_path = tmp_path / "config.yaml"
- config_path.write_text("", encoding="utf-8")
-
- args = Namespace(
- source=str(openclaw_dir),
- dry_run=True, preset="full", overwrite=False,
- migrate_secrets=False, workspace_target=None,
- skill_conflict="skip", yes=False,
- )
-
- with (
- patch.object(claw_mod, "_find_migration_script", return_value=tmp_path / "s.py"),
- patch.object(claw_mod, "_load_migration_module", side_effect=RuntimeError("boom")),
- patch.object(claw_mod, "get_config_path", return_value=config_path),
- patch.object(claw_mod, "save_config"),
- patch.object(claw_mod, "load_config", return_value={}),
- ):
- claw_mod._cmd_migrate(args)
-
- captured = capsys.readouterr()
- assert "Could not load migration script" in captured.out
def test_full_preset_does_not_enable_secrets_silently(self, tmp_path, capsys):
"""The 'full' preset must NOT auto-enable migrate_secrets.
@@ -317,51 +275,9 @@ class TestCmdCleanup:
# ---------------------------------------------------------------------------
-class TestPrintMigrationReport:
- """Test the report formatting function."""
-
- def test_dry_run_report(self, capsys):
- report = {
- "summary": {"migrated": 2, "skipped": 1, "conflict": 1, "error": 0},
- "items": [
- {"kind": "soul", "status": "migrated", "destination": "/home/user/.hermes/SOUL.md"},
- {"kind": "memory", "status": "migrated", "destination": "/home/user/.hermes/memories/MEMORY.md"},
- {"kind": "skills", "status": "conflict", "reason": "already exists"},
- {"kind": "tts-assets", "status": "skipped", "reason": "not found"},
- ],
- "preset": "full",
- }
- claw_mod._print_migration_report(report, dry_run=True)
- captured = capsys.readouterr()
- assert "Dry Run Results" in captured.out
- assert "Would migrate" in captured.out
- assert "2 would migrate" in captured.out
- assert "--dry-run" in captured.out
-
-
- def test_empty_report(self, capsys):
- report = {
- "summary": {"migrated": 0, "skipped": 0, "conflict": 0, "error": 0},
- "items": [],
- }
- claw_mod._print_migration_report(report, dry_run=False)
- captured = capsys.readouterr()
- assert "Nothing to migrate" in captured.out
class TestDetectOpenclawProcesses:
- def test_reports_union_of_exact_and_node_matches(self):
- with patch.object(claw_mod, "subprocess") as mock_subprocess:
- mock_subprocess.run.side_effect = [
- MagicMock(returncode=1, stdout=""), # systemctl
- MagicMock(returncode=0, stdout="1234\n"), # pgrep -x openclaw
- MagicMock(returncode=1, stdout=""), # pgrep -x openclaw-gatewa
- MagicMock(returncode=1, stdout=""), # pgrep -x clawd
- MagicMock(returncode=0, stdout="1234\n5678\n"), # node cmdline probe
- ]
- mock_subprocess.TimeoutExpired = subprocess.TimeoutExpired
- result = claw_mod._detect_openclaw_processes()
- assert result == ["openclaw process(es) (PIDs: 1234, 5678)"]
@pytest.mark.linux_only
def test_live_pgrep_ignores_argv_mentions_but_finds_node_openclaw(self, tmp_path):
diff --git a/tests/hermes_cli/test_cli_active_agent_ref_wiring.py b/tests/hermes_cli/test_cli_active_agent_ref_wiring.py
deleted file mode 100644
index 455f3118edf..00000000000
--- a/tests/hermes_cli/test_cli_active_agent_ref_wiring.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""Regression test for #49287 — the CLI memory-provider ``on_session_end``
-hook stopped firing on ``/exit`` after the god-file Phase 4 refactor
-(094aa85c37) moved agent construction into ``CLIAgentSetupMixin``.
-
-``_run_cleanup`` (in ``cli.py``) gates the memory-shutdown call on the
-module global ``cli._active_agent_ref``. The mixin used to set it with a
-bare ``global _active_agent_ref`` — correct while the code lived in
-``cli.py``, but after extraction that ``global`` binds the *mixin module's*
-namespace, leaving ``cli._active_agent_ref`` ``None`` forever. The cleanup
-``if _active_agent_ref:`` branch was then dead, so ``shutdown_memory_provider``
-(and therefore every provider's ``on_session_end``) never ran on CLI exit.
-
-The fix writes the reference onto the ``cli`` module explicitly. These tests
-assert that contract — the existing shutdown tests pass only because they
-hand-assign ``cli._active_agent_ref``, which is exactly what masked the bug.
-"""
-
-from __future__ import annotations
-
-import inspect
-
-
-def test_mixin_writes_active_agent_ref_to_cli_module():
- """The mixin's agent-setup code must publish the agent reference where
- ``_run_cleanup`` reads it — on the ``cli`` module, not the mixin module."""
- import cli as cli_mod
- from hermes_cli import cli_agent_setup_mixin as mixin_mod
-
- sentinel = object()
- prev_cli = getattr(cli_mod, "_active_agent_ref", None)
- prev_mixin = getattr(mixin_mod, "_active_agent_ref", "<unset>")
- try:
- # Reproduce the exact assignment the mixin performs after building
- # the agent (see CLIAgentSetupMixin near the AIAgent(...) construction).
- import cli as _cli
- _cli._active_agent_ref = sentinel
-
- # The cleanup path reads cli._active_agent_ref — it must see the value.
- assert cli_mod._active_agent_ref is sentinel
- finally:
- cli_mod._active_agent_ref = prev_cli
- if prev_mixin == "<unset>":
- if hasattr(mixin_mod, "_active_agent_ref"):
- delattr(mixin_mod, "_active_agent_ref")
- else:
- mixin_mod._active_agent_ref = prev_mixin
-
-
-def test_mixin_does_not_use_bare_global_for_active_agent_ref():
- """Guard against a regression to ``global _active_agent_ref`` inside the
- mixin: a bare module-local global would write the wrong namespace and
- silently re-break CLI memory shutdown. The source must target ``cli``."""
- from hermes_cli import cli_agent_setup_mixin as mixin_mod
-
- src = inspect.getsource(mixin_mod)
- assert "_active_agent_ref = self.agent" in src, (
- "mixin no longer publishes the agent reference for atexit cleanup"
- )
- # The assignment must go through the cli module, not a bare module global.
- # Inspect executable lines only (a bare ``global _active_agent_ref``
- # statement), ignoring prose in comments/docstrings that mention it.
- code_lines = [ln.split("#", 1)[0].strip() for ln in src.splitlines()]
- assert "global _active_agent_ref" not in code_lines, (
- "bare `global _active_agent_ref` in the mixin binds the wrong module "
- "namespace — cli._active_agent_ref stays None and memory shutdown dies "
- "(#49287). Write `cli._active_agent_ref = self.agent` instead."
- )
- assert "_cli._active_agent_ref = self.agent" in src, (
- "expected the agent reference to be published onto the cli module"
- )
diff --git a/tests/hermes_cli/test_cli_active_session_limit.py b/tests/hermes_cli/test_cli_active_session_limit.py
index b62cef45932..dbaf07cf38e 100644
--- a/tests/hermes_cli/test_cli_active_session_limit.py
+++ b/tests/hermes_cli/test_cli_active_session_limit.py
@@ -26,9 +26,8 @@ def test_cli_claim_active_session_respects_global_limit(tmp_path, monkeypatch):
try:
assert cli._claim_active_session("cli") is False
assert len(printed) == 1
- assert "active session limit (1/1)" in printed[0]
# Names the holding surface ("tui"), not the blocked one.
- assert "Held by: tui" in printed[0]
+ assert "tui" in printed[0]
held.release()
diff --git a/tests/hermes_cli/test_cli_approval_ui.py b/tests/hermes_cli/test_cli_approval_ui.py
index 34d1a560956..e5368e92bbf 100644
--- a/tests/hermes_cli/test_cli_approval_ui.py
+++ b/tests/hermes_cli/test_cli_approval_ui.py
@@ -311,42 +311,6 @@ class TestModalPaintNow:
assert cli._app.invalidate.called
- def _drive(self, cli, target, state_attr):
- result = {}
-
- def _run():
- result["value"] = target()
-
- with patch.object(cli_module, "_cprint"):
- thread = threading.Thread(target=_run, daemon=True)
- thread.start()
- deadline = time.time() + 2
- while getattr(cli, state_attr) is None and time.time() < deadline:
- time.sleep(0.01)
- assert getattr(cli, state_attr) is not None
- assert cli._app.invalidate.called, (
- f"{state_attr} panel was not painted despite throttle + resize gates"
- )
- # Reset so we can prove the response-received teardown also repaints
- # (the panel must clear at once, not be held by the throttle).
- cli._app.invalidate.reset_mock()
- getattr(cli, state_attr)["response_queue"].put(
- "deny" if state_attr == "_approval_state" else
- ("a" if state_attr == "_clarify_state" else "pw")
- )
- thread.join(timeout=2)
- # clarify returns immediately on a response (no teardown repaint);
- # approval and sudo repaint to tear the panel down.
- if state_attr != "_clarify_state":
- assert cli._app.invalidate.called, (
- f"{state_attr} panel was not repainted on teardown"
- )
- assert not thread.is_alive()
- return result["value"]
-
-
-
-
def test_secret_response_teardown_paints(self):
"""_submit_secret_response tears the secret panel down via _paint_now,
so the panel clears immediately rather than being held by the throttle."""
diff --git a/tests/hermes_cli/test_cli_background_busy_path.py b/tests/hermes_cli/test_cli_background_busy_path.py
index e22ce84f13b..d2837476832 100644
--- a/tests/hermes_cli/test_cli_background_busy_path.py
+++ b/tests/hermes_cli/test_cli_background_busy_path.py
@@ -20,60 +20,16 @@ mirroring tests/hermes_cli/test_cli_steer_busy_path.py.
from __future__ import annotations
-import importlib
-import sys
-from unittest.mock import MagicMock, patch
def _make_cli():
- """Create a HermesCLI instance with prompt_toolkit stubbed out."""
- _clean_config = {
- "model": {
- "default": "anthropic/claude-opus-4.6",
- "base_url": "https://openrouter.ai/api/v1",
- "provider": "auto",
- },
- "display": {"compact": False, "tool_progress": "all"},
- "agent": {},
- "terminal": {"env_type": "local"},
- }
- clean_env = {"LLM_MODEL": "", "HERMES_MAX_ITERATIONS": ""}
- prompt_toolkit_stubs = {
- "prompt_toolkit": MagicMock(),
- "prompt_toolkit.history": MagicMock(),
- "prompt_toolkit.styles": MagicMock(),
- "prompt_toolkit.patch_stdout": MagicMock(),
- "prompt_toolkit.application": MagicMock(),
- "prompt_toolkit.layout": MagicMock(),
- "prompt_toolkit.layout.processors": MagicMock(),
- "prompt_toolkit.filters": MagicMock(),
- "prompt_toolkit.layout.dimension": MagicMock(),
- "prompt_toolkit.layout.menus": MagicMock(),
- "prompt_toolkit.widgets": MagicMock(),
- "prompt_toolkit.key_binding": MagicMock(),
- "prompt_toolkit.completion": MagicMock(),
- "prompt_toolkit.formatted_text": MagicMock(),
- "prompt_toolkit.auto_suggest": MagicMock(),
- }
- with patch.dict(sys.modules, prompt_toolkit_stubs), patch.dict(
- "os.environ", clean_env, clear=False
- ):
- import cli as _cli_mod
-
- _cli_mod = importlib.reload(_cli_mod)
- with patch.object(_cli_mod, "get_tool_definitions", return_value=[]), patch.dict(
- _cli_mod.__dict__, {"CLI_CONFIG": _clean_config}
- ):
- return _cli_mod.HermesCLI()
+ """Bare HermesCLI (no __init__): the detector only reads _agent_running."""
+ from cli import HermesCLI
+
+ return HermesCLI.__new__(HermesCLI)
class TestBackgroundInlineDetector:
- def test_detects_background_when_agent_running(self):
- cli = _make_cli()
- cli._agent_running = True
- assert cli._should_handle_background_command_inline(
- "/bg inspect the test failures"
- ) is True
def test_detects_both_commands(self):
cli = _make_cli()
@@ -81,13 +37,6 @@ class TestBackgroundInlineDetector:
assert cli._should_handle_background_command_inline("/bg do work") is True
assert cli._should_handle_background_command_inline("/btw do work") is True
- def test_background_alias_still_resolves_to_bg(self):
- """The retired /background spelling no longer resolves to a command."""
- cli = _make_cli()
- cli._agent_running = True
- assert cli._should_handle_background_command_inline(
- "/background do work"
- ) is False
def test_ignores_background_when_agent_idle(self):
"""Idle input falls through to the normal process_loop dispatch."""
diff --git a/tests/hermes_cli/test_cli_background_tui_refresh.py b/tests/hermes_cli/test_cli_background_tui_refresh.py
deleted file mode 100644
index 7f86568cc32..00000000000
--- a/tests/hermes_cli/test_cli_background_tui_refresh.py
+++ /dev/null
@@ -1,102 +0,0 @@
-"""Tests for CLI background command TUI refresh behavior.
-
-Ensures the TUI is properly refreshed before printing background task output
-to prevent spinner/status bar overlap (#2718).
-"""
-
-from unittest.mock import MagicMock, patch
-
-
-from cli import HermesCLI
-
-
-def _make_cli():
- """Create a minimal HermesCLI instance for testing."""
- cli_obj = HermesCLI.__new__(HermesCLI)
- cli_obj.model = "test-model"
- cli_obj._background_tasks = {}
- cli_obj._background_task_counter = 0
- cli_obj.conversation_history = []
- cli_obj.agent = None
- cli_obj._app = None
- return cli_obj
-
-
-class TestBackgroundCommandTuiRefresh:
- """Tests for TUI refresh in background command output."""
-
- def test_invalidate_called_before_success_output(self):
- """App.invalidate() is called before printing background success output."""
- cli_obj = _make_cli()
- mock_app = MagicMock()
- cli_obj._app = mock_app
-
- # Track call order
- call_order = []
- original_invalidate = mock_app.invalidate
-
- def track_invalidate():
- call_order.append("invalidate")
- return original_invalidate()
-
- mock_app.invalidate = track_invalidate
-
- # Patch print to track when it's called
- with patch("builtins.print") as mock_print:
- mock_print.side_effect = lambda *args, **kwargs: call_order.append("print")
-
- # Simulate the background task output code path
- if cli_obj._app:
- cli_obj._app.invalidate()
- import time
- time.sleep(0.01) # reduced for test
- print()
-
- # Verify invalidate was called before print
- assert call_order[0] == "invalidate"
- assert "print" in call_order
-
- def test_invalidate_called_before_error_output(self):
- """App.invalidate() is called before printing background error output."""
- cli_obj = _make_cli()
- mock_app = MagicMock()
- cli_obj._app = mock_app
-
- call_order = []
- mock_app.invalidate.side_effect = lambda: call_order.append("invalidate")
-
- with patch("builtins.print") as mock_print:
- mock_print.side_effect = lambda *args, **kwargs: call_order.append("print")
-
- # Simulate error path
- if cli_obj._app:
- cli_obj._app.invalidate()
- import time
- time.sleep(0.01)
- print()
-
- assert call_order[0] == "invalidate"
- assert "print" in call_order
-
- def test_no_crash_when_app_is_none(self):
- """No crash when _app is None (non-TUI mode)."""
- cli_obj = _make_cli()
- cli_obj._app = None
-
- # This should not raise
- if cli_obj._app:
- cli_obj._app.invalidate()
- # If we get here without exception, test passes
-
- def test_background_task_thread_safety(self):
- """Background task tracking is thread-safe."""
- cli_obj = _make_cli()
-
- # Simulate adding and removing background tasks
- task_id = "test_task_1"
- cli_obj._background_tasks[task_id] = MagicMock()
- assert task_id in cli_obj._background_tasks
-
- # Clean up
- cli_obj._background_tasks.pop(task_id, None)
- assert task_id not in cli_obj._background_tasks
diff --git a/tests/hermes_cli/test_cli_browser_connect.py b/tests/hermes_cli/test_cli_browser_connect.py
index 50ab9354d97..7e496fe5df0 100644
--- a/tests/hermes_cli/test_cli_browser_connect.py
+++ b/tests/hermes_cli/test_cli_browser_connect.py
@@ -1,13 +1,7 @@
"""Tests for CLI browser CDP auto-launch helpers."""
-from contextlib import redirect_stdout
-from io import StringIO
-import os
-from queue import Queue
-import subprocess
from unittest.mock import patch
-from cli import HermesCLI
from hermes_cli.browser_connect import (
_wait_for_browser_debug_ready_or_exit,
get_chrome_debug_candidates,
@@ -17,17 +11,6 @@ from hermes_cli.browser_connect import (
)
-def _assert_chrome_debug_cmd(cmd, expected_chrome, expected_port):
- """Verify the auto-launch command has all required flags."""
- assert cmd[0] == expected_chrome
- assert f"--remote-debugging-port={expected_port}" in cmd
- assert "--no-first-run" in cmd
- assert "--no-default-browser-check" in cmd
- user_data_args = [a for a in cmd if a.startswith("--user-data-dir=")]
- assert len(user_data_args) == 1, "Expected exactly one --user-data-dir flag"
- assert "chrome-debug" in user_data_args[0]
-
-
class _FakeResponse:
status = 200
@@ -72,53 +55,9 @@ class TestChromeDebugLaunch:
- def test_linux_candidates_include_brave_origin_binary_name(self):
- brave = "/usr/bin/brave-origin"
-
- with patch("hermes_cli.browser_connect.shutil.which", side_effect=lambda name: brave if name == "brave-origin" else None), \
- patch("hermes_cli.browser_connect.os.path.isfile", side_effect=lambda path: path == brave):
- candidates = get_chrome_debug_candidates("Linux")
- command = manual_chrome_debug_command(9222, "Linux")
-
- assert candidates == [brave]
- assert command is not None
- assert command.startswith(f"{brave} --remote-debugging-port=9222")
-
- def test_linux_candidates_include_brave_origin_install_path(self):
- brave = "/opt/brave.com/brave-origin/brave-origin"
-
- with patch("hermes_cli.browser_connect.shutil.which", return_value=None), \
- patch("hermes_cli.browser_connect.os.path.isfile", side_effect=lambda path: path == brave):
- candidates = get_chrome_debug_candidates("Linux")
- command = manual_chrome_debug_command(9222, "Linux")
-
- assert candidates == [brave]
- assert command is not None
- assert command.startswith(f"{brave} --remote-debugging-port=9222")
-
- def test_linux_candidates_include_brave_origin_nightly_binary_name(self):
- brave = "/usr/bin/brave-origin-nightly"
-
- with patch("hermes_cli.browser_connect.shutil.which", side_effect=lambda name: brave if name == "brave-origin-nightly" else None), \
- patch("hermes_cli.browser_connect.os.path.isfile", side_effect=lambda path: path == brave):
- candidates = get_chrome_debug_candidates("Linux")
- command = manual_chrome_debug_command(9222, "Linux")
-
- assert candidates == [brave]
- assert command is not None
- assert command.startswith(f"{brave} --remote-debugging-port=9222")
- def test_linux_candidates_include_brave_origin_nightly_install_path(self):
- brave = "/opt/brave.com/brave-origin-nightly/brave-origin"
- with patch("hermes_cli.browser_connect.shutil.which", return_value=None), \
- patch("hermes_cli.browser_connect.os.path.isfile", side_effect=lambda path: path == brave):
- candidates = get_chrome_debug_candidates("Linux")
- command = manual_chrome_debug_command(9222, "Linux")
- assert candidates == [brave]
- assert command is not None
- assert command.startswith(f"{brave} --remote-debugging-port=9222")
def test_linux_candidates_include_official_brave_and_edge_stable_paths(self):
brave = "/usr/bin/brave-browser-stable"
diff --git a/tests/hermes_cli/test_cli_command_messages.py b/tests/hermes_cli/test_cli_command_messages.py
index e9d67dbd0d9..95bd4e995e1 100644
--- a/tests/hermes_cli/test_cli_command_messages.py
+++ b/tests/hermes_cli/test_cli_command_messages.py
@@ -7,42 +7,15 @@ findings cli-08/20/21/23/26/34, tools-runtime-13/14/20/27).
from __future__ import annotations
-import io
import re
from types import SimpleNamespace
-from rich.console import Console
-
-
-def _console():
- buf = io.StringIO()
- return Console(file=buf, force_terminal=False, width=200, highlight=False, markup=True), buf
# ── skills hub ────────────────────────────────────────────────────────────────────────────────
-def test_skill_fetch_failure_names_search_and_doctor():
- from hermes_cli.skills_hub import _print_fetch_failure
- c, buf = _console()
- _print_fetch_failure(c, sources=[], identifier="someone/typo-skill")
- out = buf.getvalue()
- assert "hermes skills search typo-skill" in out
- assert "hermes doctor" in out
- assert "from any source" not in out
-
-def test_scan_block_message_explains_force_and_points_at_inspect():
- from hermes_cli.skills_hub import _scan_block_message
- result = SimpleNamespace(verdict="dangerous", trust_level="community", findings=[1, 2, 3])
- msg = _scan_block_message(result, "acme/evil-skill")
- assert "3 high-risk pattern(s)" in msg
- assert "even with --force" in msg
- assert "hermes skills inspect acme/evil-skill" in msg
- assert "verdict" not in msg # scanner jargon stays in the audit log
- soft = _scan_block_message(SimpleNamespace(verdict="suspicious", trust_level="community", findings=[1]),
- "acme/meh")
- assert "Re-run with --force" in soft
# ── plugins ───────────────────────────────────────────────────────────────────────────────────
@@ -50,73 +23,21 @@ def test_scan_block_message_explains_force_and_points_at_inspect():
def test_plugin_clone_failure_leads_with_next_steps_and_escapes_git_output():
from hermes_cli.plugins_cmd import _clone_failure_message
msg = _clone_failure_message("https://github.com/acme/nope", "fatal: repository '[x]' not found")
- assert msg.startswith("Could not download the plugin from https://github.com/acme/nope")
- assert "hermes plugins search" in msg and "gh auth login" in msg
- assert "Details:" in msg
assert "\\[x]" in msg # Rich markup escaped so the raw git text renders verbatim
-def test_unknown_plugin_message_points_at_list_and_full_key_rule():
- from hermes_cli.plugins_cmd import _unknown_plugin_message
- msg = _unknown_plugin_message("firecrawl")
- assert "No plugin named 'firecrawl'" in msg
- assert "hermes plugins list" in msg and "web/firecrawl" in msg and "hermes plugins install" in msg
- assert "(none)" not in msg
# ── MCP ───────────────────────────────────────────────────────────────────────────────────────
-def test_banner_failed_mcp_line_shows_reason_and_command():
- from hermes_cli.banner import _mcp_server_line
- line = _mcp_server_line({"name": "gh", "transport": "stdio", "connected": False, "status": "failed",
- "error": "missing executable 'npx' (ensure Node.js is installed)"}, dim="grey", text="white")
- assert "could not connect" in line and "missing executable 'npx'" in line
- assert "hermes mcp test gh" in line
-
- auth = _mcp_server_line({"name": "linear", "transport": "http", "connected": False, "status": "failed",
- "error": "Client error '401 Unauthorized' for url"}, dim="grey", text="white")
- assert "hermes mcp login linear" in auth
-
-def test_mcp_probe_failure_unwraps_group_and_points_at_login_for_401():
- from hermes_cli.mcp_config import _probe_failure_next_step, _probe_failure_reason
- class _Resp:
- status_code = 401
-
- class _HttpErr(Exception):
- response = _Resp()
-
- group = ExceptionGroup("unhandled errors in a TaskGroup", [_HttpErr("Client error '401 Unauthorized'")])
- assert "ExceptionGroup" not in _probe_failure_reason(group)
- assert "401" in _probe_failure_reason(group)
- assert "hermes mcp login linear" in _probe_failure_next_step("linear", group)
-
- missing = FileNotFoundError(2, "No such file or directory", "npx")
- assert "config.yaml" in _probe_failure_next_step("gh", missing)
- assert "~/.hermes" not in _probe_failure_next_step("gh", missing) or "profiles" in _probe_failure_next_step("gh", missing)
# ── cron ──────────────────────────────────────────────────────────────────────────────────────
-def test_cron_delivery_failure_lines_have_no_status_literals_and_name_the_fix():
- from hermes_cli.cron import _cron_doctor_issues_for_job, _job_warnings, _last_run_display
- job = {"id": "job42", "last_status": "delivery_failed", "last_error": None,
- "last_delivery_error": "telegram: 502 Bad Gateway\nsecond raw line", "enabled": False,
- "last_fire_error": {"at": "2026-09-01T07:00:00+00:00",
- "detail": "scheduled fire could not be forwarded to the gateway api_server"}}
- texts = [_last_run_display(job), *_job_warnings(job), *_cron_doctor_issues_for_job(job)]
- joined = "\n".join(texts)
- assert "delivery_failed" not in joined and "delivery_queued" not in joined
- assert "second raw line" not in joined # only the first line of the raw blob is shown
- assert "hermes cron edit job42 --deliver" in joined
- assert "hermes gateway restart" in joined and "hermes cron run job42" in joined
- assert "gateway was unreachable" in joined
-def test_cron_queued_status_reads_as_in_progress():
- from hermes_cli.cron import _last_run_display
- assert "in progress" in _last_run_display({"last_status": "delivery_queued"})
# ── doctor / advisories / paths ───────────────────────────────────────────────────────────────
@@ -131,24 +52,5 @@ def test_advisory_remediation_uses_active_hermes_home(monkeypatch, tmp_path):
assert not re.search(r"~/\.hermes/\.env", text)
-def test_doctor_ack_failure_names_config_path_and_retry(monkeypatch, capsys):
- import hermes_cli.doctor as doctor
- monkeypatch.setattr("hermes_cli.security_advisories.ack_advisory", lambda _id: False)
- monkeypatch.setattr(doctor, "_DHH", "~/.hermes/profiles/work")
- from hermes_cli.security_advisories import ADVISORIES
- try:
- doctor._ack_advisory(ADVISORIES[0].id)
- except SystemExit as exc:
- assert exc.code == 1
- out = capsys.readouterr().out
- assert "~/.hermes/profiles/work/config.yaml" in out
- assert "hermes config path" in out and f"hermes doctor --ack {ADVISORIES[0].id}" in out
- assert "Failed to persist" not in out
-
-
-def test_backup_recovery_hint_cites_the_slash_command_not_a_fake_subcommand():
- from hermes_cli.backup import _snapshot_recovery_hint
- hint = _snapshot_recovery_hint()
- assert "/snapshot list" in hint and "/snapshot restore" in hint
- assert "hermes snapshot" not in hint # `hermes snapshot` is not a CLI subcommand
- assert "CLI only" in hint # /snapshot is cli_only; Desktop/gateway readers must not go looking for it
+
+
diff --git a/tests/hermes_cli/test_cli_context_warning.py b/tests/hermes_cli/test_cli_context_warning.py
index 82a86e1296f..29017b347e1 100644
--- a/tests/hermes_cli/test_cli_context_warning.py
+++ b/tests/hermes_cli/test_cli_context_warning.py
@@ -60,16 +60,6 @@ class TestLowContextWarning:
assert minimum_calls
- def test_warning_for_2048_context(self, cli_obj):
- """Warning shown for 2048 tokens (common LM Studio default)."""
- cli_obj.agent.context_compressor.context_length = 2048
- with patch("cli.get_tool_definitions", return_value=[]), \
- patch("hermes_cli.banner.build_welcome_banner"):
- cli_obj.show_banner()
-
- calls = [str(c) for c in cli_obj.console.print.call_args_list]
- warning_calls = [c for c in calls if "too low" in c]
- assert len(warning_calls) == 1
def test_no_warning_at_boundary(self, cli_obj):
"""No warning at exactly Hermes' minimum context length."""
@@ -82,16 +72,6 @@ class TestLowContextWarning:
warning_calls = [c for c in calls if "too low" in c]
assert len(warning_calls) == 0
- def test_no_warning_above_boundary(self, cli_obj):
- """No warning above Hermes' minimum context length."""
- cli_obj.agent.context_compressor.context_length = MINIMUM_CONTEXT_LENGTH + 1
- with patch("cli.get_tool_definitions", return_value=[]), \
- patch("hermes_cli.banner.build_welcome_banner"):
- cli_obj.show_banner()
-
- calls = [str(c) for c in cli_obj.console.print.call_args_list]
- warning_calls = [c for c in calls if "too low" in c]
- assert len(warning_calls) == 0
def test_ollama_specific_hint(self, cli_obj):
"""Ollama-specific fix shown when port 11434 detected."""
diff --git a/tests/hermes_cli/test_cli_delegate_background_notice.py b/tests/hermes_cli/test_cli_delegate_background_notice.py
index 23f293c1957..d5efde823e9 100644
--- a/tests/hermes_cli/test_cli_delegate_background_notice.py
+++ b/tests/hermes_cli/test_cli_delegate_background_notice.py
@@ -36,16 +36,6 @@ def test_background_dispatch_prints_resume_notice(monkeypatch):
assert "it finishes" in joined
-def test_background_batch_dispatch_pluralizes(monkeypatch):
- cli_obj = _make_cli()
- printed = _capture(monkeypatch)
-
- result = json.dumps({"status": "dispatched", "mode": "background", "count": 3})
- cli_obj._on_tool_complete("tc2", "delegate_task", {"tasks": []}, result)
-
- joined = "\n".join(printed)
- assert "3 tasks" in joined
- assert "they finish" in joined
def test_synchronous_delegate_result_prints_no_notice(monkeypatch):
diff --git a/tests/hermes_cli/test_cli_extension_hooks.py b/tests/hermes_cli/test_cli_extension_hooks.py
index 7599f24402e..f101da16c07 100644
--- a/tests/hermes_cli/test_cli_extension_hooks.py
+++ b/tests/hermes_cli/test_cli_extension_hooks.py
@@ -9,90 +9,14 @@ without overriding run().
from __future__ import annotations
-import importlib
-import sys
-from unittest.mock import MagicMock, patch
-from prompt_toolkit.key_binding import KeyBindings
-def _make_cli(**kwargs):
- """Create a HermesCLI with prompt_toolkit stubs (same pattern as test_cli_init)."""
- _clean_config = {
- "model": {
- "default": "anthropic/claude-opus-4.6",
- "base_url": "https://openrouter.ai/api/v1",
- "provider": "auto",
- },
- "display": {"compact": False, "tool_progress": "all"},
- "agent": {},
- "terminal": {"env_type": "local"},
- }
- clean_env = {"LLM_MODEL": "", "HERMES_MAX_ITERATIONS": ""}
- prompt_toolkit_stubs = {
- "prompt_toolkit": MagicMock(),
- "prompt_toolkit.history": MagicMock(),
- "prompt_toolkit.styles": MagicMock(),
- "prompt_toolkit.patch_stdout": MagicMock(),
- "prompt_toolkit.application": MagicMock(),
- "prompt_toolkit.layout": MagicMock(),
- "prompt_toolkit.layout.processors": MagicMock(),
- "prompt_toolkit.filters": MagicMock(),
- "prompt_toolkit.layout.dimension": MagicMock(),
- "prompt_toolkit.layout.menus": MagicMock(),
- "prompt_toolkit.widgets": MagicMock(),
- "prompt_toolkit.key_binding": MagicMock(),
- "prompt_toolkit.completion": MagicMock(),
- "prompt_toolkit.formatted_text": MagicMock(),
- "prompt_toolkit.auto_suggest": MagicMock(),
- }
- with patch.dict(sys.modules, prompt_toolkit_stubs), patch.dict(
- "os.environ", clean_env, clear=False
- ):
- import cli as _cli_mod
+def _make_cli():
+ """Bare HermesCLI (no __init__): the layout hooks need no init state."""
+ from cli import HermesCLI
- _cli_mod = importlib.reload(_cli_mod)
- with patch.object(_cli_mod, "get_tool_definitions", return_value=[]), patch.dict(
- _cli_mod.__dict__, {"CLI_CONFIG": _clean_config}
- ):
- return _cli_mod.HermesCLI(**kwargs)
-
-
-class TestExtensionHookDefaults:
- def test_extra_tui_widgets_default_empty(self):
- cli = _make_cli()
- assert cli._get_extra_tui_widgets() == []
-
- def test_register_extra_tui_keybindings_default_noop(self):
- cli = _make_cli()
- kb = KeyBindings()
- result = cli._register_extra_tui_keybindings(kb, input_area=None)
- assert result is None
- assert kb.bindings == []
-
- def test_build_tui_layout_children_returns_all_widgets_in_order(self):
- cli = _make_cli()
- children = cli._build_tui_layout_children(
- sudo_widget="sudo",
- secret_widget="secret",
- approval_widget="approval",
- clarify_widget="clarify",
- spinner_widget="spinner",
- spacer="spacer",
- status_bar="status",
- input_rule_top="top-rule",
- image_bar="image-bar",
- input_area="input-area",
- input_rule_bot="bottom-rule",
- voice_status_bar="voice-status",
- completions_menu="completions-menu",
- )
- # First element is Window(height=0), rest are the named widgets
- assert children[1:] == [
- "sudo", "secret", "approval", "clarify", "spinner",
- "spacer", "status", "top-rule", "image-bar", "input-area",
- "bottom-rule", "voice-status", "completions-menu",
- ]
+ return HermesCLI.__new__(HermesCLI)
class TestExtensionHookSubclass:
@@ -124,15 +48,3 @@ class TestExtensionHookSubclass:
assert children[spacer_idx + 3] == "status"
assert status_idx == spacer_idx + 3
- def test_extra_keybindings_can_add_bindings(self):
- cli = _make_cli()
- kb = KeyBindings()
-
- def _custom_hook(kb, *, input_area):
- @kb.add("f2")
- def _toggle(event):
- return None
-
- cli._register_extra_tui_keybindings = _custom_hook
- cli._register_extra_tui_keybindings(kb, input_area=None)
- assert len(kb.bindings) == 1
diff --git a/tests/hermes_cli/test_cli_external_editor.py b/tests/hermes_cli/test_cli_external_editor.py
index c176c192045..8a8c791af1a 100644
--- a/tests/hermes_cli/test_cli_external_editor.py
+++ b/tests/hermes_cli/test_cli_external_editor.py
@@ -67,17 +67,6 @@ def test_open_external_editor_expands_paste_placeholders_before_open(tmp_path):
assert buffer.calls == [False]
-def test_open_external_editor_sets_skip_collapse_flag_during_expansion(tmp_path):
- cli_obj = _make_cli()
- paste_file = tmp_path / "paste.txt"
- paste_file.write_text("a\nb\nc\nd\ne\nf", encoding="utf-8")
- buffer = _FakeBuffer(text=f"[Pasted text #1: 6 lines \u2192 {paste_file}]")
-
- # After expansion the flag should have been set (to prevent re-collapse)
- assert cli_obj._open_external_editor(buffer=buffer) is True
- # Flag is consumed by _on_text_changed, but since no handler is attached
- # in tests it stays True until the handler resets it.
- assert cli_obj._skip_paste_collapse is True
def test_inline_pastes_stores_full_content(tmp_path):
diff --git a/tests/hermes_cli/test_cli_goal_interrupt.py b/tests/hermes_cli/test_cli_goal_interrupt.py
index 37ee84ccc68..13be5cbaa47 100644
--- a/tests/hermes_cli/test_cli_goal_interrupt.py
+++ b/tests/hermes_cli/test_cli_goal_interrupt.py
@@ -130,24 +130,3 @@ class TestHealthyTurnStillRuns:
assert mgr.state.status == "done"
-class TestInterruptFlagLifecycle:
- def test_chat_resets_flag_at_entry(self, hermes_home):
- """chat() must reset _last_turn_interrupted at the top of each turn.
-
- This guards against stale flag state: if turn N was interrupted and
- turn N+1 runs clean, the hook must not see True from N.
- """
- # We can't run chat() end-to-end here, but we can assert the reset
- # is the first thing after the secret-capture registration by
- # inspecting the source shape.
- from cli import HermesCLI
- import inspect
-
- src = inspect.getsource(HermesCLI.chat)
- # Look for an explicit reset near the top of chat().
- head = src.split("if not self._ensure_runtime_credentials", 1)[0]
- assert "self._last_turn_interrupted = False" in head, (
- "chat() must reset _last_turn_interrupted before run_conversation "
- "runs — otherwise a prior turn's interrupt state leaks into the "
- "next turn's goal hook decision."
- )
diff --git a/tests/hermes_cli/test_cli_init.py b/tests/hermes_cli/test_cli_init.py
index 83ba5d041bc..bdd409628b5 100644
--- a/tests/hermes_cli/test_cli_init.py
+++ b/tests/hermes_cli/test_cli_init.py
@@ -73,14 +73,6 @@ def _make_cli(env_overrides=None, config_overrides=None, **kwargs):
class TestMaxTurnsResolution:
"""max_turns must always resolve to a positive integer, never None."""
- def test_default_max_turns_is_unlimited(self):
- # Default is now unlimited (max_turns caused more problems than it
- # solved). Still a positive int (the sys.maxsize sentinel), so loop
- # conditions like `count < max_iterations` keep working.
- import sys
- cli = _make_cli()
- assert isinstance(cli.max_turns, int)
- assert cli.max_turns == sys.maxsize
def test_explicit_max_turns_honored(self):
cli = _make_cli(max_turns=25)
@@ -95,15 +87,6 @@ class TestMaxTurnsResolution:
-class TestVerboseAndToolProgress:
- def test_default_verbose_is_bool(self):
- cli = _make_cli()
- assert isinstance(cli.verbose, bool)
-
- def test_tool_progress_mode_is_string(self):
- cli = _make_cli()
- assert isinstance(cli.tool_progress_mode, str)
- assert cli.tool_progress_mode in {"off", "new", "all", "verbose"}
class TestFallbackChainInit:
@@ -121,9 +104,6 @@ class TestFallbackChainInit:
class TestBusyInputMode:
- def test_default_busy_input_mode_is_interrupt(self):
- cli = _make_cli()
- assert cli.busy_input_mode == "interrupt"
def test_busy_input_mode_queue_is_honored(self):
cli = _make_cli(config_overrides={"display": {"busy_input_mode": "queue"}})
@@ -320,15 +300,6 @@ class TestPromptToolkitTerminalCompatibility:
assert _terminal_may_leak_cpr() is True
-class TestSingleQueryState:
- def test_voice_and_interrupt_state_initialized_before_run(self):
- """Single-query mode calls chat() without going through run()."""
- cli = _make_cli()
- assert cli._voice_tts is False
- assert cli._voice_mode is False
- assert cli._voice_tts_done.is_set()
- assert hasattr(cli, "_interrupt_queue")
- assert hasattr(cli, "_pending_input")
class TestHistoryDisplay:
@@ -387,8 +358,6 @@ class TestHistoryDisplay:
assert "Recent sessions" in output
assert "Checking Running Hermes Agent" in output
- assert "Use /resume" in output
- assert "session title" in output
@@ -510,10 +479,7 @@ class TestNestedDictModelDefaultPairing:
output = capsys.readouterr().out
assert "Unknown command" not in output
- assert "cli (local terminal)" in output
- assert "Tier:" in output
- assert "unrestricted" in output
- assert "Slash commands: all available" in output
+ assert output.strip()
def test_provider_prefixed_startup_model_overrides_stale_provider(self):
cli = _make_cli(
diff --git a/tests/hermes_cli/test_cli_interrupt_drain_regression.py b/tests/hermes_cli/test_cli_interrupt_drain_regression.py
index 9e87513e8c8..c54e46febfa 100644
--- a/tests/hermes_cli/test_cli_interrupt_drain_regression.py
+++ b/tests/hermes_cli/test_cli_interrupt_drain_regression.py
@@ -28,69 +28,23 @@ load-bearing piece.
from __future__ import annotations
-import importlib
import queue
-import sys
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
def _make_cli():
- """Build a HermesCLI instance with prompt_toolkit stubbed out.
-
- Mirrors the helper in ``test_cli_steer_busy_path.py``.
- """
- _clean_config = {
- "model": {
- "default": "anthropic/claude-opus-4.6",
- "base_url": "https://openrouter.ai/api/v1",
- "provider": "auto",
- },
- "display": {"compact": False, "tool_progress": "all"},
- "agent": {},
- "terminal": {"env_type": "local"},
- }
- clean_env = {"LLM_MODEL": "", "HERMES_MAX_ITERATIONS": ""}
- prompt_toolkit_stubs = {
- "prompt_toolkit": MagicMock(),
- "prompt_toolkit.history": MagicMock(),
- "prompt_toolkit.styles": MagicMock(),
- "prompt_toolkit.patch_stdout": MagicMock(),
- "prompt_toolkit.application": MagicMock(),
- "prompt_toolkit.layout": MagicMock(),
- "prompt_toolkit.layout.processors": MagicMock(),
- "prompt_toolkit.filters": MagicMock(),
- "prompt_toolkit.layout.dimension": MagicMock(),
- "prompt_toolkit.layout.menus": MagicMock(),
- "prompt_toolkit.widgets": MagicMock(),
- "prompt_toolkit.key_binding": MagicMock(),
- "prompt_toolkit.completion": MagicMock(),
- "prompt_toolkit.formatted_text": MagicMock(),
- "prompt_toolkit.auto_suggest": MagicMock(),
- }
- with patch.dict(sys.modules, prompt_toolkit_stubs), patch.dict(
- "os.environ", clean_env, clear=False
- ):
- import cli as _cli_mod
-
- _cli_mod = importlib.reload(_cli_mod)
- with patch.object(_cli_mod, "get_tool_definitions", return_value=[]), patch.dict(
- _cli_mod.__dict__, {"CLI_CONFIG": _clean_config}
- ):
- return _cli_mod.HermesCLI()
+ """Bare HermesCLI (no __init__) with just the two queues the drain touches."""
+ from cli import HermesCLI
+
+ cli = HermesCLI.__new__(HermesCLI)
+ cli._interrupt_queue = queue.Queue()
+ cli._pending_input = queue.Queue()
+ return cli
class TestInterruptQueueDrain:
"""``_drain_interrupt_queue_to_pending_input`` re-queues stray messages."""
- def test_drains_single_pending_message_into_pending_input(self):
- cli = _make_cli()
- cli._interrupt_queue.put("typed during agent turn")
-
- cli._drain_interrupt_queue_to_pending_input()
-
- assert cli._interrupt_queue.empty()
- assert cli._pending_input.qsize() == 1
- assert cli._pending_input.get_nowait() == "typed during agent turn"
def test_preserves_order_when_draining_multiple_messages(self):
cli = _make_cli()
@@ -105,13 +59,6 @@ class TestInterruptQueueDrain:
drained.append(cli._pending_input.get_nowait())
assert drained == ["first", "second", "third"]
- def test_noop_when_interrupt_queue_is_empty(self):
- cli = _make_cli()
-
- cli._drain_interrupt_queue_to_pending_input()
-
- assert cli._interrupt_queue.empty()
- assert cli._pending_input.empty()
def test_skips_falsy_messages(self):
cli = _make_cli()
diff --git a/tests/hermes_cli/test_cli_light_mode.py b/tests/hermes_cli/test_cli_light_mode.py
index fb5d3fb15e1..96c4a235706 100644
--- a/tests/hermes_cli/test_cli_light_mode.py
+++ b/tests/hermes_cli/test_cli_light_mode.py
@@ -158,10 +158,6 @@ class TestSkinConfigHook:
set_active_skin(previous)
- def test_hook_installed(self, cli_mod):
- from hermes_cli.skin_engine import SkinConfig
-
- assert getattr(SkinConfig, "_hermes_light_mode_hook_installed", False) is True
def test_hook_is_idempotent(self, cli_mod):
# Calling the installer twice must not double-wrap (the marker
diff --git a/tests/hermes_cli/test_cli_loading_indicator.py b/tests/hermes_cli/test_cli_loading_indicator.py
index dd7bdb68d13..00430a6bdc7 100644
--- a/tests/hermes_cli/test_cli_loading_indicator.py
+++ b/tests/hermes_cli/test_cli_loading_indicator.py
@@ -25,7 +25,7 @@ class TestCLILoadingIndicator:
print("skills done")
with patch.object(cli_obj, "_handle_skills_command", side_effect=fake_handle), \
- patch.object(cli_obj, "_invalidate") as invalidate_mock:
+ patch.object(cli_obj, "_invalidate"):
assert cli_obj.process_command("/skills search kubernetes")
output = capsys.readouterr().out
@@ -38,35 +38,4 @@ class TestCLILoadingIndicator:
}
assert cli_obj._command_running is False
assert cli_obj._command_status == ""
- assert invalidate_mock.call_count == 2
- def test_reload_mcp_sets_busy_state_and_prints_status(self, capsys):
- cli_obj = self._make_cli()
- seen = {}
-
- def fake_reload():
- seen["running"] = cli_obj._command_running
- seen["status"] = cli_obj._command_status
- print("reload done")
-
- # /reload-mcp now wraps the actual reload in a prompt-cache-invalidation
- # confirmation prompt (commit 4d7fc0f37). This test exercises the
- # loading-indicator path, not the confirmation UX, so pre-approve the
- # reload via config so the handler goes straight into _reload_mcp().
- fake_cfg = {"approvals": {"mcp_reload_confirm": False}}
-
- with patch.object(cli_obj, "_reload_mcp", side_effect=fake_reload), \
- patch.object(cli_obj, "_invalidate") as invalidate_mock, \
- patch("cli.load_cli_config", return_value=fake_cfg):
- assert cli_obj.process_command("/reload-mcp")
-
- output = capsys.readouterr().out
- assert "⏳ Reloading MCP servers..." in output
- assert "reload done" in output
- assert seen == {
- "running": True,
- "status": "Reloading MCP servers...",
- }
- assert cli_obj._command_running is False
- assert cli_obj._command_status == ""
- assert invalidate_mock.call_count == 2
diff --git a/tests/hermes_cli/test_cli_mcp_config_watch.py b/tests/hermes_cli/test_cli_mcp_config_watch.py
index 28587338797..24e07e61e6b 100644
--- a/tests/hermes_cli/test_cli_mcp_config_watch.py
+++ b/tests/hermes_cli/test_cli_mcp_config_watch.py
@@ -1,6 +1,4 @@
"""Tests for automatic MCP reload when config.yaml mcp_servers section changes."""
-import time
-from pathlib import Path
from unittest.mock import MagicMock, patch
from utils import file_signature
@@ -97,9 +95,7 @@ class TestMCPConfigWatch:
obj._reload_mcp.assert_not_called()
out = capsys.readouterr().out
- assert "reload skipped" in out
- assert "/reload-mcp" in out
- assert "prompt cache" in out
+ assert "/reload-mcp" in out # tells the user how to apply it manually
def test_optout_updates_snapshot_so_reload_mcp_applies_cleanly(self, tmp_path):
"""After an opted-out change, the watcher must not re-notify every
diff --git a/tests/hermes_cli/test_cli_model_once.py b/tests/hermes_cli/test_cli_model_once.py
index 4e4be13c8a9..3d9ed743859 100644
--- a/tests/hermes_cli/test_cli_model_once.py
+++ b/tests/hermes_cli/test_cli_model_once.py
@@ -89,7 +89,6 @@ def test_cli_model_once_records_restore_and_does_not_persist(monkeypatch):
assert stub.provider == "anthropic"
assert stub.agent.calls[-1]["new_model"] == "claude-sonnet-4.6"
assert stub._pending_one_turn_model_restore["model"] == "old/model"
- assert "next turn only" in printed[-1]
def test_cli_restore_model_runtime_snapshot_restores_agent():
diff --git a/tests/hermes_cli/test_cli_new_session.py b/tests/hermes_cli/test_cli_new_session.py
index cbad4d58aca..ef53127aecb 100644
--- a/tests/hermes_cli/test_cli_new_session.py
+++ b/tests/hermes_cli/test_cli_new_session.py
@@ -243,39 +243,6 @@ def test_clear_command_starts_new_session_before_redrawing(tmp_path):
assert cli.conversation_history == []
-def test_new_session_resets_token_counters(tmp_path):
- """Regression test for #2099: /new must zero all token counters."""
- cli = _prepare_cli_with_active_session(tmp_path)
-
- # Verify counters are non-zero before reset
- agent = cli.agent
- assert agent.session_total_tokens > 0
- assert agent.session_api_calls > 0
- assert agent.context_compressor.compression_count > 0
-
- cli.process_command("/new")
-
- # All agent token counters must be zero
- assert agent.session_total_tokens == 0
- assert agent.session_input_tokens == 0
- assert agent.session_output_tokens == 0
- assert agent.session_prompt_tokens == 0
- assert agent.session_completion_tokens == 0
- assert agent.session_cache_read_tokens == 0
- assert agent.session_cache_write_tokens == 0
- assert agent.session_reasoning_tokens == 0
- assert agent.session_api_calls == 0
- assert agent.session_estimated_cost_usd == 0.0
- assert agent.session_cost_status == "unknown"
- assert agent.session_cost_source == "none"
-
- # Context compressor counters must also be zero
- comp = agent.context_compressor
- assert comp.last_prompt_tokens == 0
- assert comp.last_completion_tokens == 0
- assert comp.last_total_tokens == 0
- assert comp.compression_count == 0
- assert comp._context_probed is False
def test_new_session_with_title(capsys):
diff --git a/tests/hermes_cli/test_cli_output.py b/tests/hermes_cli/test_cli_output.py
index 5a75aecbaaa..7fec516ef80 100644
--- a/tests/hermes_cli/test_cli_output.py
+++ b/tests/hermes_cli/test_cli_output.py
@@ -42,32 +42,6 @@ def test_line_input_preserves_builtin_input_for_redirected_stdin(monkeypatch):
assert seen["prompt"] == "Enter model name: "
-def test_line_input_falls_back_to_input_when_prompt_toolkit_raises_oserror(monkeypatch):
- """isatty() can report True while the asyncio selector still rejects stdin.
-
- Under a `curl ... | bash` install the setup wizard reattaches stdin from
- /dev/tty, so isatty() is True and the guard above passes. prompt_toolkit
- then fails to register fd 0 with the event-loop selector (observed on
- macOS, where kqueue raises OSError EINVAL / "Invalid argument"). line_input
- must degrade to the built-in reader instead of letting the OSError abort
- the whole wizard.
- """
- seen = {}
-
- def raising_prompt(*_args, **_kwargs):
- raise OSError(22, "Invalid argument")
-
- def fake_input(prompt_text):
- seen["prompt"] = prompt_text
- return "fallback-value"
-
- monkeypatch.setattr(cli_output.sys, "stdin", _TTY())
- monkeypatch.setattr(cli_output.sys, "stdout", _TTY())
- monkeypatch.setattr("prompt_toolkit.prompt", raising_prompt)
- monkeypatch.setattr("builtins.input", fake_input)
-
- assert cli_output.line_input("Choice [1/2]: ") == "fallback-value"
- assert seen["prompt"] == "Choice [1/2]: "
def test_line_input_falls_back_to_input_on_any_prompt_toolkit_failure(monkeypatch):
diff --git a/tests/hermes_cli/test_cli_partial_update_hint.py b/tests/hermes_cli/test_cli_partial_update_hint.py
index 94deb9206bf..492ad0f7d74 100644
--- a/tests/hermes_cli/test_cli_partial_update_hint.py
+++ b/tests/hermes_cli/test_cli_partial_update_hint.py
@@ -16,7 +16,7 @@ import types
import pytest
-from hermes_constants import emit_partial_update_hint, partial_update_hint
+from hermes_constants import emit_partial_update_hint
def _chat_args(**overrides):
@@ -79,15 +79,8 @@ def test_emit_hint_for_missing_resolve_turn_limit():
text = buf.getvalue()
assert "resolve_turn_limit" in text
assert "hermes update" in text
- assert "partially-updated" in text
-def test_emit_hint_for_missing_split_model_config_default():
- exc = _missing_config_name_error("split_model_config_default")
- assert partial_update_hint(exc)
- buf = io.StringIO()
- assert emit_partial_update_hint(exc, file=buf) is True
- assert "hermes update" in buf.getvalue()
def test_emit_hint_stays_silent_for_third_party_import_error():
@@ -117,7 +110,6 @@ def test_cmd_chat_prints_update_hint_when_config_helper_is_missing(
err = capsys.readouterr().err
assert name in err
assert "hermes update" in err
- assert "partially-updated" in err
def test_cmd_chat_still_reraises_unrelated_import_errors(main_mod, monkeypatch):
diff --git a/tests/hermes_cli/test_cli_prefix_matching.py b/tests/hermes_cli/test_cli_prefix_matching.py
index f04f523d505..73063319e96 100644
--- a/tests/hermes_cli/test_cli_prefix_matching.py
+++ b/tests/hermes_cli/test_cli_prefix_matching.py
@@ -24,13 +24,6 @@ class TestSlashCommandPrefixMatching:
- def test_ambiguous_prefix_shows_suggestions(self):
- """/re matches multiple commands — should show ambiguous message."""
- cli_obj = _make_cli()
- with patch("cli._cprint") as mock_cprint:
- cli_obj.process_command("/re")
- printed = " ".join(str(c) for c in mock_cprint.call_args_list)
- assert "Ambiguous" in printed or "Did you mean" in printed
@@ -49,20 +42,6 @@ class TestSlashCommandPrefixMatching:
unknown = any("Unknown command" in p for p in printed)
assert not unknown, f"Expected skill prefix to match, got: {printed}"
- def test_ambiguous_between_builtin_and_skill(self):
- """Ambiguous prefix spanning builtin + skill commands shows suggestions."""
- cli_obj = _make_cli()
- # /help-extra is a fake skill that shares /hel prefix with /help
- fake_skill = {"/help-extra": {"name": "Help Extra", "description": "test"}}
-
- import cli as cli_mod
- with patch.object(cli_mod, '_skill_commands', fake_skill), patch.object(cli_obj, 'show_help') as mock_help:
- cli_obj.process_command("/help")
-
- # /help is an exact match so should work normally, not show ambiguous
- mock_help.assert_called_once()
- printed = " ".join(str(c) for c in cli_obj.console.print.call_args_list)
- assert "Ambiguous" not in printed
def test_shortest_match_preferred_over_longer_skill(self):
"""/qui should dispatch to /quit (5 chars) not report ambiguous with /quint-pipeline (15 chars)."""
diff --git a/tests/hermes_cli/test_cli_preloaded_skills.py b/tests/hermes_cli/test_cli_preloaded_skills.py
index 1c2b5e8bb60..264c18bca36 100644
--- a/tests/hermes_cli/test_cli_preloaded_skills.py
+++ b/tests/hermes_cli/test_cli_preloaded_skills.py
@@ -1,53 +1,8 @@
from __future__ import annotations
-import importlib
-import os
-import sys
-from unittest.mock import MagicMock, patch
-
import pytest
-def _make_real_cli(**kwargs):
- clean_config = {
- "model": {
- "default": "anthropic/claude-opus-4.6",
- "base_url": "https://openrouter.ai/api/v1",
- "provider": "auto",
- },
- "display": {"compact": False, "tool_progress": "all"},
- "agent": {},
- "terminal": {"env_type": "local"},
- }
- clean_env = {"LLM_MODEL": "", "HERMES_MAX_ITERATIONS": ""}
- prompt_toolkit_stubs = {
- "prompt_toolkit": MagicMock(),
- "prompt_toolkit.history": MagicMock(),
- "prompt_toolkit.styles": MagicMock(),
- "prompt_toolkit.patch_stdout": MagicMock(),
- "prompt_toolkit.application": MagicMock(),
- "prompt_toolkit.layout": MagicMock(),
- "prompt_toolkit.layout.processors": MagicMock(),
- "prompt_toolkit.filters": MagicMock(),
- "prompt_toolkit.layout.dimension": MagicMock(),
- "prompt_toolkit.layout.menus": MagicMock(),
- "prompt_toolkit.widgets": MagicMock(),
- "prompt_toolkit.key_binding": MagicMock(),
- "prompt_toolkit.completion": MagicMock(),
- "prompt_toolkit.formatted_text": MagicMock(),
- }
- with patch.dict(sys.modules, prompt_toolkit_stubs), patch.dict(
- "os.environ", clean_env, clear=False
- ):
- import cli as cli_mod
-
- cli_mod = importlib.reload(cli_mod)
- with patch.object(cli_mod, "get_tool_definitions", return_value=[]), patch.dict(
- cli_mod.__dict__, {"CLI_CONFIG": clean_config}
- ):
- return cli_mod.HermesCLI(**kwargs)
-
-
class _DummyCLI:
def __init__(self, **kwargs):
self.kwargs = kwargs
@@ -134,22 +89,3 @@ def test_main_raises_for_unknown_preloaded_skill(monkeypatch):
_real_finalize(created["cli"])
-def test_show_banner_does_not_print_skills():
- """show_banner() no longer prints the activated skills line — it moved to run()."""
- cli_obj = _make_real_cli(compact=False)
- cli_obj.preloaded_skills = ["hermes-agent-dev", "github-auth"]
- cli_obj.console = MagicMock()
-
- with patch("hermes_cli.banner.build_welcome_banner") as mock_banner, patch(
- "shutil.get_terminal_size", return_value=os.terminal_size((120, 40))
- ):
- cli_obj.show_banner()
-
- print_calls = [
- call.args[0]
- for call in cli_obj.console.print.call_args_list
- if call.args and isinstance(call.args[0], str)
- ]
- startup_lines = [line for line in print_calls if "Activated skills:" in line]
- assert len(startup_lines) == 0
- assert mock_banner.call_count == 1
diff --git a/tests/hermes_cli/test_cli_provider_resolution.py b/tests/hermes_cli/test_cli_provider_resolution.py
index 270ccc2d176..36fb71e27ad 100644
--- a/tests/hermes_cli/test_cli_provider_resolution.py
+++ b/tests/hermes_cli/test_cli_provider_resolution.py
@@ -9,7 +9,6 @@ import pytest
from hermes_cli.auth import AuthError
from hermes_cli import main as hermes_main
import hermes_cli.main_provider_setup as hermes_cli_main_provider_setup
-from hermes_cli import model_setup_flows
from hermes_cli import model_switch
@@ -263,21 +262,6 @@ def test_provider_flag_logs_when_custom_default_model_cannot_resolve(monkeypatch
)
-def test_hermes_cli_init_does_not_eagerly_resolve_runtime_provider(monkeypatch):
- cli = _import_cli()
- calls = {"count": 0}
-
- def _unexpected_runtime_resolve(**kwargs):
- calls["count"] += 1
- raise AssertionError("resolve_runtime_provider should not be called in HermesCLI.__init__")
-
- monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", _unexpected_runtime_resolve)
- monkeypatch.setattr("hermes_cli.runtime_provider.format_runtime_provider_error", lambda exc: str(exc))
-
- shell = cli.HermesCLI(model="gpt-5", compact=True, max_turns=1)
-
- assert shell is not None
- assert calls["count"] == 0
def test_runtime_resolution_failure_is_not_sticky(monkeypatch):
@@ -444,18 +428,6 @@ def test_ensure_runtime_credentials_records_quota_vs_bad_key(monkeypatch, tmp_pa
assert bad_shell._credentials_rate_limited is False
-def test_cli_turn_routing_uses_primary_when_disabled(monkeypatch):
- cli = _import_cli()
- shell = cli.HermesCLI(model="gpt-5", compact=True, max_turns=1)
- shell.provider = "openrouter"
- shell.api_mode = "chat_completions"
- shell.base_url = "https://openrouter.ai/api/v1"
- shell.api_key = "sk-primary"
-
- result = shell._resolve_turn_agent_config("what time is it in tokyo?")
-
- assert result["model"] == "gpt-5"
- assert result["runtime"]["provider"] == "openrouter"
@@ -673,7 +645,7 @@ def test_custom_entry_model_swap_re_resolves_reasoning(monkeypatch):
-def test_model_flow_custom_saves_verified_v1_base_url(monkeypatch, capsys):
+def test_model_flow_custom_saves_verified_v1_base_url(monkeypatch):
monkeypatch.setattr(
"hermes_cli.config.get_env_value",
lambda key: "" if key in {"OPENAI_BASE_URL", "OPENAI_API_KEY"} else "",
@@ -706,11 +678,10 @@ def test_model_flow_custom_saves_verified_v1_base_url(monkeypatch, capsys):
monkeypatch.setattr("builtins.input", lambda _prompt="": next(answers))
monkeypatch.setattr("hermes_cli.secret_prompt.masked_secret_prompt", lambda _prompt="": next(answers))
- hermes_main._model_flow_custom({})
- output = capsys.readouterr().out
+ caller_cfg = {}
+ hermes_main._model_flow_custom(caller_cfg)
- assert "Saving the working base URL instead" in output
- assert "Detected model: llm" in output
+ assert caller_cfg["model"]["base_url"] == "http://localhost:8000/v1"
# OPENAI_BASE_URL is no longer saved to .env — config.yaml is authoritative
assert "OPENAI_BASE_URL" not in saved_env
assert saved_env["MODEL"] == "llm"
@@ -840,10 +811,6 @@ def test_cmd_model_forwards_nous_login_tls_options(monkeypatch):
# _auto_provider_name — unit tests
# ---------------------------------------------------------------------------
-def test_auto_provider_name_localhost():
- from hermes_cli.main_provider_setup import _auto_provider_name
- assert _auto_provider_name("http://localhost:11434/v1") == "Local (localhost:11434)"
- assert _auto_provider_name("http://127.0.0.1:1234/v1") == "Local (127.0.0.1:1234)"
@@ -908,7 +875,6 @@ def test_custom_endpoint_key_env_is_a_valid_posix_name_for_ip_endpoints():
raise on exactly the local-proxy setups this is meant to protect. The
fixed prefix makes the result valid by construction.
"""
- import re
from hermes_cli.config import _ENV_VAR_NAME_RE, custom_endpoint_key_env
diff --git a/tests/hermes_cli/test_cli_quiet_stdout_leak.py b/tests/hermes_cli/test_cli_quiet_stdout_leak.py
index ef49ba20c1a..5e935d981d0 100644
--- a/tests/hermes_cli/test_cli_quiet_stdout_leak.py
+++ b/tests/hermes_cli/test_cli_quiet_stdout_leak.py
@@ -1,81 +1,7 @@
-"""`hermes chat -Q` must not leak presentation output into stdout (#93220).
-
-The quiet single-query branch lives inline in ``_run_single_query_mode``
-(``hermes_cli/cli_single_query.py``, re-exported by ``cli``; no standalone
-function to call), so these pin the branch's required statements
-at the source level — the established convention for behavior with no
-runtime mirror (see the install.ps1 source-text tests). Deleting any
-neutralization reintroduces a leak:
-
-- ``reasoning_callback`` → streaming ``┌─ Reasoning ─┐`` box
-- ``tool_complete_callback`` → full file diffs via render_edit_diff_with_delta
-- ``tool_progress_callback`` → MoA reference blocks (printed before the
- mode check in _on_tool_progress)
-- ``tool_start_callback`` → snapshot capture paired with tool_complete
-- ``agent.tool_progress_mode`` → executor's direct progress prints
-"""
+"""`hermes chat -Q` must not leak presentation output into stdout (#93220)."""
from __future__ import annotations
-from pathlib import Path
-
-import cli as cli_mod
-
-_QUIET_ANCHOR = "# Quiet mode: suppress banner, spinner, tool previews."
-
-
-def _quiet_branch() -> str:
- """Return the source of the quiet single-query branch.
-
- The callback neutralizations live in ``_configure_quiet_agent`` (called from
- the quiet branch of ``_run_single_query_mode``); the branch itself is the
- window from the quiet-mode anchor to the ``_run_quiet_single_query`` hand-off.
- """
- import inspect
-
- source = Path(inspect.getsourcefile(cli_mod._run_single_query_mode)).read_text(encoding="utf-8")
- start = source.index(_QUIET_ANCHOR)
- branch = source[start : start + 8000]
- helper = inspect.getsource(cli_mod._configure_quiet_agent).replace("agent.", "cli.agent.")
- return helper + branch
-
-
-def test_quiet_branch_clears_reasoning_callback():
- branch = _quiet_branch()
- assert "cli.agent.reasoning_callback = None" in branch, (
- "-Q must clear the reasoning callback on the live agent, or the "
- "streaming Reasoning box renders into captured stdout (#93220)."
- )
-
-
-def test_quiet_branch_clears_inline_diff_callbacks():
- branch = _quiet_branch()
- for attr in (
- "cli.agent.tool_start_callback = None",
- "cli.agent.tool_complete_callback = None",
- ):
- assert attr in branch, (
- f"-Q must set `{attr}`: the inline-diff callbacks print full "
- "file diffs via render_edit_diff_with_delta and are gated by "
- "neither quiet_mode nor tool_progress_mode (#93220)."
- )
-
-
-def test_quiet_branch_clears_tool_progress_callback():
- branch = _quiet_branch()
- assert "cli.agent.tool_progress_callback = None" in branch, (
- "-Q must clear tool_progress_callback: _on_tool_progress prints "
- "MoA reference blocks before its tool_progress_mode check (#93220)."
- )
-
-
-def test_quiet_branch_syncs_tool_progress_off_to_agent():
- branch = _quiet_branch()
- assert 'cli.agent.tool_progress_mode = "off"' in branch, (
- "-Q must sync tool_progress_mode='off' to the live agent so the "
- "tool_executor rendering path stays silent (#93220)."
- )
-
def test_suppress_status_output_gates_quiet_tool_messages():
"""The executor's [tool]/[done] fallback must stay silent under -Q.
@@ -99,22 +25,3 @@ def test_suppress_status_output_gates_quiet_tool_messages():
assert agent._should_emit_quiet_tool_messages() is False
-def test_quiet_branch_neutralizations_precede_run_conversation():
- branch = _quiet_branch()
- # The turn itself runs inside ``_run_quiet_single_query``; the quiet branch
- # must finish neutralizing the callbacks before it hands off to that helper.
- import inspect
-
- assert "run_conversation(" in inspect.getsource(cli_mod._run_quiet_single_query)
- assert "_configure_quiet_agent(cli.agent)" in branch
- run_idx = branch.index("_run_quiet_single_query(cli,")
- assert branch.index("_configure_quiet_agent(cli.agent)") < run_idx
- for attr in (
- "cli.agent.reasoning_callback = None",
- "cli.agent.tool_progress_callback = None",
- "cli.agent.tool_start_callback = None",
- "cli.agent.tool_complete_callback = None",
- ):
- assert branch.index(attr) < run_idx, (
- f"`{attr}` must run before the run_conversation hand-off in the quiet branch"
- )
diff --git a/tests/hermes_cli/test_cli_reload_skills.py b/tests/hermes_cli/test_cli_reload_skills.py
index 1b728bc3c14..315c6547baf 100644
--- a/tests/hermes_cli/test_cli_reload_skills.py
+++ b/tests/hermes_cli/test_cli_reload_skills.py
@@ -43,12 +43,8 @@ class TestReloadSkillsCLI:
cli._reload_skills()
out = capsys.readouterr().out
- assert "Added Skills:" in out
- assert "- alpha: Run alpha to do xyz" in out
- assert "- beta: Run beta to do abc" in out
- assert "Removed Skills:" in out
- assert "- gamma: Old removed skill" in out
- assert "3 skill(s) available" in out
+ for name in ("alpha", "beta", "gamma"):
+ assert name in out
# Must NOT pollute conversation_history — alternation-safe.
assert cli.conversation_history == []
@@ -56,13 +52,8 @@ class TestReloadSkillsCLI:
# One-shot note queued with system-prompt-style formatting.
note = getattr(cli, "_pending_skills_reload_note", None)
assert note is not None
- assert note.startswith("[USER INITIATED SKILLS RELOAD:")
- assert note.endswith("Use skills_list to see the updated catalog.]")
- assert "Added Skills:" in note
- assert " - alpha: Run alpha to do xyz" in note
- assert " - beta: Run beta to do abc" in note
- assert "Removed Skills:" in note
- assert " - gamma: Old removed skill" in note
+ for name in ("alpha", "beta", "gamma"):
+ assert name in note
def test_reports_no_changes_and_queues_nothing(self, capsys):
cli = _make_cli()
@@ -78,9 +69,6 @@ class TestReloadSkillsCLI:
):
cli._reload_skills()
- out = capsys.readouterr().out
- assert "No new skills detected" in out
- assert "1 skill(s) available" in out
assert cli.conversation_history == []
assert getattr(cli, "_pending_skills_reload_note", None) is None
@@ -92,8 +80,6 @@ class TestReloadSkillsCLI:
):
cli._reload_skills()
- out = capsys.readouterr().out
- assert "Skills reload failed" in out
- assert "boom" in out
+ assert "boom" in capsys.readouterr().out
assert cli.conversation_history == []
assert getattr(cli, "_pending_skills_reload_note", None) is None
diff --git a/tests/hermes_cli/test_cli_resume_command.py b/tests/hermes_cli/test_cli_resume_command.py
index 56a51f8d87e..3654996697d 100644
--- a/tests/hermes_cli/test_cli_resume_command.py
+++ b/tests/hermes_cli/test_cli_resume_command.py
@@ -1,5 +1,4 @@
import os
-from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from cli import HermesCLI
@@ -33,30 +32,9 @@ class TestCliResumeCommand:
output = capsys.readouterr().out
assert shown is True
- assert "1" in output
- assert "2" in output
assert "Coding" in output
assert "Research" in output
- assert "/resume 2" in output
- assert "/resume <session title>" in output
- def test_show_recent_sessions_uses_prompt_toolkit_safe_print(self):
- cli_obj = _make_cli()
- cli_obj._list_recent_sessions = MagicMock(return_value=[
- {"id": "sess_002", "title": "Coding", "preview": "build feature", "last_active": None},
- ])
-
- running_app = SimpleNamespace(_is_running=True)
- with (
- patch("prompt_toolkit.application.get_app_or_none", return_value=running_app),
- patch("cli._cprint") as mock_cprint,
- ):
- shown = cli_obj._show_recent_sessions(reason="sessions")
-
- assert shown is True
- printed = "\n".join(call.args[0] for call in mock_cprint.call_args_list)
- assert "Recent sessions" in printed
- assert "Coding" in printed
def test_handle_resume_by_index_switches_to_numbered_session(self):
@@ -84,7 +62,6 @@ class TestCliResumeCommand:
printed = " ".join(str(call) for call in mock_cprint.call_args_list)
assert cli_obj.session_id == "sess_001"
- assert "Resumed session sess_001" in printed
assert "Research" in printed
def test_handle_resume_by_index_out_of_range(self):
@@ -96,9 +73,7 @@ class TestCliResumeCommand:
with patch("cli._cprint") as mock_cprint:
cli_obj._handle_resume_command("/resume 9")
- printed = " ".join(str(call) for call in mock_cprint.call_args_list)
- assert "out of range" in printed.lower()
- assert "/resume" in printed
+ assert mock_cprint.called
assert cli_obj.session_id == "current_session"
diff --git a/tests/hermes_cli/test_cli_save_config_value.py b/tests/hermes_cli/test_cli_save_config_value.py
index d1f0a3ef52d..f7528333783 100644
--- a/tests/hermes_cli/test_cli_save_config_value.py
+++ b/tests/hermes_cli/test_cli_save_config_value.py
@@ -1,7 +1,6 @@
"""Tests for save_config_value() in cli.py — atomic write behavior."""
from pathlib import Path
-from unittest.mock import MagicMock
import yaml
@@ -28,15 +27,6 @@ class TestSaveConfigValueAtomic:
monkeypatch.setattr("cli._hermes_home", hermes_home)
return config_path
- def test_calls_roundtrip_yaml_update(self, config_env, monkeypatch):
- """save_config_value must preserve user-edited YAML structure."""
- mock_update = MagicMock()
- monkeypatch.setattr("utils.atomic_roundtrip_yaml_update", mock_update)
-
- from cli import save_config_value
- save_config_value("display.skin", "mono")
-
- mock_update.assert_called_once_with(config_env, "display.skin", "mono")
def test_creates_nested_keys(self, config_env):
diff --git a/tests/hermes_cli/test_cli_shift_enter_newline.py b/tests/hermes_cli/test_cli_shift_enter_newline.py
index 35a874aed89..02c3ae7505e 100644
--- a/tests/hermes_cli/test_cli_shift_enter_newline.py
+++ b/tests/hermes_cli/test_cli_shift_enter_newline.py
@@ -45,10 +45,6 @@ def test_install_registers_all_three_sequences():
-def test_install_returns_zero_when_already_correct():
- """Idempotency — running install twice should not report a second change."""
- install_shift_enter_alias()
- assert install_shift_enter_alias() == 0
def test_csi_u_shift_enter_parses_as_alt_enter():
@@ -64,11 +60,3 @@ def test_csi_u_shift_enter_parses_as_alt_enter():
-def test_plain_enter_remains_distinct_from_alt_enter():
- """Plain Enter must keep emitting a single key (submit), not a two-key
- Alt+Enter tuple — otherwise we would have broken submit."""
- enter = _parse("\r")
- alt_enter = _parse("\x1b\r")
- assert enter != alt_enter
- assert len(enter) == 1
- assert len(alt_enter) == 2
diff --git a/tests/hermes_cli/test_cli_skin_integration.py b/tests/hermes_cli/test_cli_skin_integration.py
index c094bcacfaf..7fb564fa0cc 100644
--- a/tests/hermes_cli/test_cli_skin_integration.py
+++ b/tests/hermes_cli/test_cli_skin_integration.py
@@ -31,18 +31,15 @@ def _make_cli_stub():
class TestCliSkinPromptIntegration:
- def test_ares_prompt_fragments_use_skin_symbol(self):
- cli = _make_cli_stub()
-
- set_active_skin("ares")
- assert cli._get_tui_prompt_fragments() == [("class:prompt", "⚔ ")]
def test_secret_prompt_fragments_preserve_secret_state(self):
cli = _make_cli_stub()
cli._secret_state = {"response_queue": object()}
set_active_skin("ares")
- assert cli._get_tui_prompt_fragments() == [("class:sudo-prompt", "🔑 ⚔ ")]
+ frags = cli._get_tui_prompt_fragments()
+ assert frags[0][0] == "class:sudo-prompt"
+ assert get_active_skin().get_branding("prompt_symbol").strip() in frags[0][1]
def test_narrow_terminals_compact_voice_recording_prompt_fragments(self):
@@ -80,7 +77,6 @@ class TestCliSkinPromptIntegration:
set_active_skin("ares")
assert cli._apply_tui_skin_style() is True
assert cli._app.style is not None
- cli._invalidate.assert_called_once_with(min_interval=0.0)
def test_handle_skin_command_refreshes_live_tui(self, capsys):
cli = _make_cli_stub()
@@ -88,23 +84,12 @@ class TestCliSkinPromptIntegration:
with patch("cli.save_config_value", return_value=True):
cli._handle_skin_command("/skin ares")
- output = capsys.readouterr().out
- assert "Skin set to: ares (saved)" in output
- assert "Prompt + TUI colors updated." in output
+ assert get_active_skin().name == "ares"
assert cli._app.style is not None
class TestCompactBannerSkinIntegration:
- def test_poseidon_compact_banner_uses_skin_branding_instead_of_nous_hermes(self):
- set_active_skin("poseidon")
-
- with patch("cli.shutil.get_terminal_size", return_value=SimpleNamespace(columns=90)), \
- patch.dict(_build_compact_banner.__globals__, {"format_banner_version_label": lambda: "Hermes Agent v0.1.0 (test)"}):
- banner = _build_compact_banner()
-
- assert "Poseidon Agent" in banner
- assert "NOUS HERMES" not in banner
def test_poseidon_compact_banner_uses_skin_colors(self):
set_active_skin("poseidon")
@@ -114,6 +99,7 @@ class TestCompactBannerSkinIntegration:
patch.dict(_build_compact_banner.__globals__, {"format_banner_version_label": lambda: "Hermes Agent v0.1.0 (test)"}):
banner = _build_compact_banner()
+ assert skin.get_branding("agent_name") in banner
assert skin.get_color("banner_border") in banner
assert skin.get_color("banner_title") in banner
assert skin.get_color("banner_dim") in banner
diff --git a/tests/hermes_cli/test_cli_startup_model_cost_guard.py b/tests/hermes_cli/test_cli_startup_model_cost_guard.py
index 6ad2347efb1..d336539adba 100644
--- a/tests/hermes_cli/test_cli_startup_model_cost_guard.py
+++ b/tests/hermes_cli/test_cli_startup_model_cost_guard.py
@@ -106,7 +106,6 @@ def test_cmd_chat_rejects_noninteractive_gpt55_pro_startup_override(
assert not fake_cli
err = capsys.readouterr().err
assert "EXPENSIVE MODEL WARNING" in err
- assert "did you mean to select openai/gpt-5.5?" in err
assert "non-interactive" in err
diff --git a/tests/hermes_cli/test_cli_status_bar.py b/tests/hermes_cli/test_cli_status_bar.py
index 9094a3a8fae..738f3c0c436 100644
--- a/tests/hermes_cli/test_cli_status_bar.py
+++ b/tests/hermes_cli/test_cli_status_bar.py
@@ -92,14 +92,6 @@ class TestCLIStatusBar:
assert cli_obj._status_bar_visible is False
- def test_context_style_thresholds(self):
- cli_obj = _make_cli()
-
- assert cli_obj._status_bar_context_style(None) == "class:status-bar-dim"
- assert cli_obj._status_bar_context_style(10) == "class:status-bar-good"
- assert cli_obj._status_bar_context_style(50) == "class:status-bar-warn"
- assert cli_obj._status_bar_context_style(81) == "class:status-bar-bad"
- assert cli_obj._status_bar_context_style(95) == "class:status-bar-critical"
def test_build_status_bar_text_for_wide_terminal(self):
cli_obj = _attach_agent(
@@ -157,32 +149,10 @@ class TestCLIStatusBar:
- def test_minimal_tui_chrome_threshold(self):
- cli_obj = _make_cli()
-
- assert cli_obj._use_minimal_tui_chrome(width=63) is True
- assert cli_obj._use_minimal_tui_chrome(width=64) is False
-
- def test_scheduled_unsuppress_debounces_resize_storm(self):
- """A fresh resize cancels the pending unsuppress and restarts it."""
- cli_obj = _make_cli()
- cli_obj._status_bar_unsuppress_timer = None
- cli_obj._status_bar_suppressed_after_resize = True
- app = MagicMock()
- app.loop = None
- # First schedule (long delay) then a second should cancel the first.
- cli_obj._schedule_status_bar_unsuppress(app, delay=5.0)
- first_timer = cli_obj._status_bar_unsuppress_timer
- assert first_timer is not None
- cli_obj._schedule_status_bar_unsuppress(app, delay=0.01)
- assert first_timer is not cli_obj._status_bar_unsuppress_timer
- assert not first_timer.is_alive() or first_timer.finished.is_set()
- time.sleep(0.1)
- assert cli_obj._status_bar_suppressed_after_resize is False
@@ -195,17 +165,6 @@ class TestCLIStatusBar:
assert cli_obj._spinner_widget_height(width=64) == 2
- def test_voice_status_bar_compacts_on_narrow_terminals(self):
- cli_obj = _make_cli()
- cli_obj._voice_mode = True
- cli_obj._voice_recording = False
- cli_obj._voice_processing = False
- cli_obj._voice_tts = True
- cli_obj._voice_continuous = True
-
- fragments = cli_obj._get_voice_status_fragments(width=50)
-
- assert fragments == [("class:voice-status", " 🎤 Ctrl+B ")]
# Round-13 Copilot review regressions on #19835. The label in voice
@@ -233,36 +192,6 @@ class TestCLIStatusBar:
-class TestCLIUsageReport:
- def test_show_usage_omits_cost_reporting(self, capsys):
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_230,
- completion_tokens=2_220,
- total_tokens=12_450,
- api_calls=7,
- context_tokens=12_450,
- context_length=200_000,
- compressions=1,
- )
- cli_obj.verbose = False
-
- cli_obj._show_usage()
- output = capsys.readouterr().out
-
- # Token counts and session metadata still shown.
- assert "Model:" in output
- assert "Input tokens:" in output
- assert "Output tokens:" in output
- assert "Total tokens:" in output
- assert "Session duration:" in output
- assert "Compressions:" in output
- # Cost and cache-hit reporting is removed everywhere.
- assert "Total cost:" not in output
- assert "Cost status:" not in output
- assert "Cost source:" not in output
- assert "Cache read tokens:" not in output
- assert "Cache write tokens:" not in output
class TestCLIUsageNoAgentAccountLimits:
@@ -349,36 +278,8 @@ class TestStatusBarWidthSource:
assert text.endswith(" weekly-digest ")
assert cli_obj._status_bar_display_width(text) == 100
- def test_fragments_use_pt_width_over_shutil(self):
- """When prompt_toolkit reports a width, shutil.get_terminal_size must not be used."""
- from unittest.mock import MagicMock, patch
- cli_obj = self._make_wide_cli()
- mock_app = MagicMock()
- mock_app.output.get_size.return_value = MagicMock(columns=120)
- with patch("prompt_toolkit.application.get_app", return_value=mock_app) as mock_get_app, \
- patch("shutil.get_terminal_size") as mock_shutil:
- cli_obj._get_status_bar_fragments()
-
- mock_shutil.assert_not_called()
-
-
- def test_build_status_bar_text_uses_pt_width(self):
- """_build_status_bar_text() must also prefer prompt_toolkit width."""
- from unittest.mock import MagicMock, patch
- cli_obj = self._make_wide_cli()
-
- mock_app = MagicMock()
- mock_app.output.get_size.return_value = MagicMock(columns=80)
-
- with patch("prompt_toolkit.application.get_app", return_value=mock_app), \
- patch("shutil.get_terminal_size") as mock_shutil:
- text = cli_obj._build_status_bar_text() # no explicit width
-
- mock_shutil.assert_not_called()
- assert isinstance(text, str)
- assert len(text) > 0
@@ -397,13 +298,6 @@ class TestIdleSinceLastTurn:
assert label == "✓ 42s"
- def test_snapshot_carries_idle_since(self):
- cli_obj = _make_cli()
- cli_obj._last_turn_finished_at = time.time() - 10
- cli_obj._prompt_start_time = None
- cli_obj._prompt_duration = 5.0
- snapshot = cli_obj._get_status_bar_snapshot()
- assert snapshot["idle_since"].startswith("✓ ")
@@ -426,24 +320,6 @@ class TestStatusBarFieldConfig:
text = cli_obj._build_status_bar_text(width=width)
return text
- def test_default_fields_show_all(self):
- """With no config, all default fields appear."""
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_230,
- completion_tokens=2_220,
- total_tokens=12_450,
- api_calls=7,
- context_tokens=12_450,
- context_length=200_000,
- compressions=7,
- )
- with patch.object(cli_mod, "CLI_CONFIG", {}):
- text = cli_obj._build_status_bar_text(width=120)
- assert "claude-sonnet-4-20250514" in text
- assert "12.4K/200K" in text
- assert "🗜️" in text
- assert "15m" in text
def test_only_model_and_duration(self):
text = self._cli_with_fields(["model", "duration"])
@@ -453,48 +329,15 @@ class TestStatusBarFieldConfig:
assert "🗜️" not in text
assert "%" not in text
- def test_only_model(self):
- text = self._cli_with_fields(["model"])
- assert "claude-sonnet-4-20250514" in text
- assert "15m" not in text
- assert "12.4K/200K" not in text
- def test_context_pct_only(self):
- text = self._cli_with_fields(["context_pct"])
- assert "%" in text
- assert "claude-sonnet-4-20250514" not in text
- def test_compressions_only(self):
- text = self._cli_with_fields(["compressions"])
- assert "🗜️ 7" in text
- assert "claude-sonnet-4-20250514" not in text
def test_total_tokens_when_explicitly_requested(self):
text = self._cli_with_fields(["model", "total_tokens"])
assert "Σ12.4K" in text
assert "claude-sonnet-4-20250514" in text
- def test_total_tokens_hidden_by_default(self):
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_230,
- completion_tokens=2_220,
- total_tokens=12_450,
- api_calls=7,
- context_tokens=12_450,
- context_length=200_000,
- compressions=7,
- )
- with patch.object(cli_mod, "CLI_CONFIG", {}):
- text = cli_obj._build_status_bar_text(width=120)
- assert "Σ" not in text
- def test_narrow_terminal_drops_context_detail(self):
- """Narrow terminal (<76) ignores context_detail even if configured."""
- text = self._cli_with_fields(["model", "context_detail", "duration"], width=60)
- assert "claude-sonnet-4-20250514" in text
- assert "15m" in text
- assert "12.4K/200K" not in text
def test_field_config_never_empties_the_bar(self):
"""A fields list matching nothing still anchors on the model name."""
@@ -522,13 +365,6 @@ class TestStatusBarFieldConfig:
assert not any("🗜️" in t for t in frag_texts)
assert not any("12.4K" in t for t in frag_texts)
- def test_field_order_is_fixed(self):
- """Config controls visibility, not ordering — model stays first."""
- text = self._cli_with_fields(["duration", "model", "compressions"])
- model_pos = text.find("claude-sonnet-4-20250514")
- comp_pos = text.find("🗜️")
- dur_pos = text.find("15m")
- assert 0 <= model_pos < comp_pos < dur_pos
def test_empty_fields_list_uses_defaults(self):
text = self._cli_with_fields([])
@@ -536,14 +372,6 @@ class TestStatusBarFieldConfig:
assert "12.4K/200K" in text
assert "🗜️" in text
- def test_field_set_is_cached_per_instance(self):
- cli_obj = _make_cli()
- with patch.object(cli_mod, "CLI_CONFIG", {"display": {"status_bar": {"fields": ["model"]}}}):
- first = cli_obj._get_status_bar_field_set()
- # Cache holds even if config object changes afterwards (per-session semantics).
- with patch.object(cli_mod, "CLI_CONFIG", {"display": {"status_bar": {"fields": ["duration"]}}}):
- second = cli_obj._get_status_bar_field_set()
- assert first == second == frozenset({"model"})
class TestCacheHitRate:
@@ -564,22 +392,6 @@ class TestCacheHitRate:
assert "◎ 76.0%" in text
- def test_cache_hit_rate_shown_in_narrow_terminal(self):
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_000,
- completion_tokens=2_000,
- total_tokens=12_000,
- api_calls=5,
- context_tokens=12_000,
- context_length=200_000,
- cache_read_tokens=5000,
- cache_write_tokens=0,
- )
-
- text = cli_obj._build_status_bar_text(width=60)
-
- assert "◎ 50%" in text
def test_cache_hit_rate_hidden_when_zero(self):
cli_obj = _attach_agent(
@@ -598,37 +410,7 @@ class TestCacheHitRate:
assert "◎" not in text
- def test_cache_hit_rate_hidden_when_no_data(self):
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_000,
- completion_tokens=2_000,
- total_tokens=12_000,
- api_calls=5,
- context_tokens=12_000,
- context_length=200_000,
- )
-
- text = cli_obj._build_status_bar_text(width=120)
-
- assert "◎" not in text
-
- def test_cache_hit_rate_one_decimal(self):
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_000,
- completion_tokens=2_000,
- total_tokens=12_000,
- api_calls=5,
- context_tokens=12_000,
- context_length=200_000,
- cache_read_tokens=7620,
- cache_write_tokens=0,
- )
- text = cli_obj._build_status_bar_text(width=120)
-
- assert "◎ 76.2%" in text
def test_cache_hit_rate_with_anthropic_style_cache(self):
"""Anthropic has both cache_read and cache_write"""
@@ -680,17 +462,6 @@ class TestRollingLatencyVelocity:
assert "\u25f7" not in text
assert "t/s" not in text
- def test_latency_and_tps_respect_field_filter(self):
- cli_obj = _attach_agent(
- _make_cli(),
- prompt_tokens=10_000, completion_tokens=2_000, total_tokens=12_000,
- api_calls=5, context_tokens=12_000, context_length=200_000,
- )
- self._with_history(cli_obj, [2.0], [100])
- with patch.object(cli_mod, "CLI_CONFIG", {"display": {"status_bar": {"fields": ["model", "duration"]}}}):
- text = cli_obj._build_status_bar_text(width=140)
- assert "\u25f7" not in text
- assert "t/s" not in text
def test_negative_latency_guard(self):
cli_obj = _attach_agent(
diff --git a/tests/hermes_cli/test_cli_status_bar_goal.py b/tests/hermes_cli/test_cli_status_bar_goal.py
index e41c454c2b8..1b991985eb4 100644
--- a/tests/hermes_cli/test_cli_status_bar_goal.py
+++ b/tests/hermes_cli/test_cli_status_bar_goal.py
@@ -61,17 +61,5 @@ class TestStatusBarGoalSegment:
assert "⊙ goal 5/20" in text
- def test_active_goal_rendered_in_medium_status_bar(self):
- cli_obj = _attach_goal(_make_cli(), active=True, turns_used=1, max_turns=20)
- text = cli_obj._build_status_bar_text(width=60)
-
- assert "⊙ goal 1/20" in text
-
- def test_active_goal_rendered_in_narrow_status_bar(self):
- cli_obj = _attach_goal(_make_cli(), active=True, turns_used=2, max_turns=20)
-
- text = cli_obj._build_status_bar_text(width=50)
-
- assert "⊙ goal" in text
diff --git a/tests/hermes_cli/test_cli_status_command.py b/tests/hermes_cli/test_cli_status_command.py
index 1feaee104d0..279b40fb742 100644
--- a/tests/hermes_cli/test_cli_status_command.py
+++ b/tests/hermes_cli/test_cli_status_command.py
@@ -5,7 +5,6 @@ from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from cli import HermesCLI
-from hermes_cli.commands import resolve_command
def _make_cli():
@@ -26,17 +25,8 @@ def _make_cli():
return cli_obj
-def test_status_command_is_available_in_cli_registry():
- cmd = resolve_command("status")
- assert cmd is not None
- assert cmd.gateway_only is False
-def test_egress_command_is_available_in_cli_registry():
- cmd = resolve_command("egress")
- assert cmd is not None
- assert cmd.gateway_only is False
- assert "status" in cmd.subcommands
@@ -94,28 +84,6 @@ def test_show_session_status_prints_gateway_style_summary():
assert kwargs.get("markup") is False
-def test_show_session_status_includes_reasoning_approvals_context():
- """C-02: /status surfaces reasoning level, approval mode, and context %."""
- cli_obj = _make_cli()
- cli_obj.agent = SimpleNamespace(session_total_tokens=1000, session_api_calls=2,
- reasoning_config={"enabled": True, "effort": "high"})
- cli_obj.reasoning_config = {"enabled": True, "effort": "high"}
- cli_obj.show_reasoning = True
- cli_obj.session_key = ""
- cli_obj._session_db.get_session.return_value = {"started_at": 1775791440}
- cli_obj._get_status_bar_snapshot = lambda: {
- "context_tokens": 50000, "context_length": 200000, "context_percent": 25,
- }
-
- with patch("hermes_constants.display_hermes_home", return_value="~/.hermes"), \
- patch("tools.approval_context._get_approval_mode", return_value="manual"), \
- patch("tools.approval.is_approval_bypass_active_for_session", return_value=False):
- cli_obj._show_session_status()
-
- printed = "\n".join(str(call.args[0]) for call in cli_obj.console.print.call_args_list)
- assert "Reasoning: high (display: on)" in printed
- assert "Approvals: manual" in printed
- assert "Context: 75% left · 50,000 / 200,000 tokens used" in printed
def test_profile_command_reports_custom_root_profile(monkeypatch, tmp_path, capsys):
diff --git a/tests/hermes_cli/test_cli_steer_busy_path.py b/tests/hermes_cli/test_cli_steer_busy_path.py
index 071c741fbef..96e8ba6cd6f 100644
--- a/tests/hermes_cli/test_cli_steer_busy_path.py
+++ b/tests/hermes_cli/test_cli_steer_busy_path.py
@@ -76,25 +76,8 @@ class TestSteerInlineDetector:
cli._agent_running = True
assert cli._should_handle_steer_command_inline("/steer focus on error handling") is True
- def test_ignores_steer_when_agent_idle(self):
- """Idle-path /steer should fall through to the normal process_loop
- dispatch so the queue-style fallback message is emitted."""
- cli = _make_cli()
- cli._agent_running = False
- assert cli._should_handle_steer_command_inline("/steer do something") is False
- def test_ignores_non_slash_input(self):
- cli = _make_cli()
- cli._agent_running = True
- assert cli._should_handle_steer_command_inline("steer without slash") is False
- assert cli._should_handle_steer_command_inline("") is False
- def test_ignores_other_slash_commands(self):
- cli = _make_cli()
- cli._agent_running = True
- assert cli._should_handle_steer_command_inline("/queue hello") is False
- assert cli._should_handle_steer_command_inline("/stop") is False
- assert cli._should_handle_steer_command_inline("/help") is False
def test_ignores_steer_with_attached_images(self):
"""Image payloads take the normal path; steer doesn't accept images."""
diff --git a/tests/hermes_cli/test_cli_terminal_response_sanitizer.py b/tests/hermes_cli/test_cli_terminal_response_sanitizer.py
index eb8c66c9cbb..d52c026ce80 100644
--- a/tests/hermes_cli/test_cli_terminal_response_sanitizer.py
+++ b/tests/hermes_cli/test_cli_terminal_response_sanitizer.py
@@ -16,10 +16,6 @@ def _strip_leaked_terminal_responses(text: str) -> str:
class TestStripLeakedTerminalResponses:
- def test_strips_canonical_dsr_response(self):
- # Reports from issue #14692
- text = "\x1b[53;1R"
- assert _strip_leaked_terminal_responses(text) == ""
def test_strips_multiple_dsr_responses(self):
@@ -31,9 +27,6 @@ class TestStripLeakedTerminalResponses:
- def test_strips_sgr_mouse_report_esc_form(self):
- text = "abc\x1b[<65;1;49Mdef"
- assert _strip_leaked_terminal_responses(text) == "abcdef"
diff --git a/tests/hermes_cli/test_cli_tools_command.py b/tests/hermes_cli/test_cli_tools_command.py
index 8363f5b838c..f67de37cdaa 100644
--- a/tests/hermes_cli/test_cli_tools_command.py
+++ b/tests/hermes_cli/test_cli_tools_command.py
@@ -17,13 +17,6 @@ def _make_cli(enabled_toolsets=None):
# ── /tools (no subcommand) ──────────────────────────────────────────────────
-class TestToolsSlashNoSubcommand:
-
- def test_bare_tools_shows_tool_list(self):
- cli_obj = _make_cli()
- with patch.object(cli_obj, "show_tools") as mock_show:
- cli_obj._handle_tools_command("/tools")
- mock_show.assert_called_once()
@@ -62,17 +55,6 @@ class TestToolsSlashDisableWithReset:
assert "web" not in cli_obj.enabled_toolsets
- def test_disable_always_resets_session(self):
- """Even without a confirmation prompt, disable always resets the session."""
- cli_obj = _make_cli(["web", "memory"])
- with patch("hermes_cli.tools_config.load_config",
- return_value={"platform_toolsets": {"cli": ["web", "memory"]}}), \
- patch("hermes_cli.tools_config.save_config"), \
- patch("hermes_cli.tools_config._get_platform_tools", return_value={"memory"}), \
- patch("hermes_cli.config.load_config", return_value={}), \
- patch.object(cli_obj, "new_session") as mock_reset:
- cli_obj._handle_tools_command("/tools disable web")
- mock_reset.assert_called_once()
@@ -94,8 +76,3 @@ class TestToolsSlashEnableWithReset:
mock_reset.assert_called_once()
assert "web" in cli_obj.enabled_toolsets
- def test_enable_missing_name_prints_usage(self, capsys):
- cli_obj = _make_cli()
- cli_obj._handle_tools_command("/tools enable")
- out = capsys.readouterr().out
- assert "Usage" in out
diff --git a/tests/hermes_cli/test_cli_user_message_preview.py b/tests/hermes_cli/test_cli_user_message_preview.py
index b3829587d06..9af38020d9a 100644
--- a/tests/hermes_cli/test_cli_user_message_preview.py
+++ b/tests/hermes_cli/test_cli_user_message_preview.py
@@ -79,12 +79,3 @@ class TestSubmittedUserMessagePreview:
assert "line6" not in rendered
assert "(+4 more lines)" in rendered
- def test_invalid_first_lines_value_falls_back_to_one(self):
- cli = _make_cli({"first_lines": 0, "last_lines": 2})
-
- rendered = cli._format_submitted_user_message_preview("line1\nline2\nline3\nline4")
-
- assert "line1" in rendered
- assert "line3" in rendered
- assert "line4" in rendered
- assert "(+1 more line)" in rendered
diff --git a/tests/hermes_cli/test_cli_yolo_resume_persistence.py b/tests/hermes_cli/test_cli_yolo_resume_persistence.py
index 82b62d7e83f..a5f9d99c860 100644
--- a/tests/hermes_cli/test_cli_yolo_resume_persistence.py
+++ b/tests/hermes_cli/test_cli_yolo_resume_persistence.py
@@ -19,7 +19,7 @@ The fix persists a ``yolo_mode`` flag inside the session row's
import json
from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
@@ -153,23 +153,6 @@ class TestRestoreSessionYolo:
class TestToggleYoloPersists:
- def test_toggle_writes_flag_through_session_db(self):
- db = MagicMock()
- stand_in = SimpleNamespace(session_id=SESSION_ID, _session_db=db)
- # Bind the real persist helper so the toggle's getattr finds it.
- stand_in._persist_session_yolo = (
- lambda key, enabled: HermesCLI._persist_session_yolo(
- stand_in, key, enabled
- )
- )
-
- with patch("cli._cprint"):
- HermesCLI._toggle_yolo(stand_in) # ON
- db.set_session_yolo.assert_called_once_with(SESSION_ID, True)
-
- with patch("cli._cprint"):
- HermesCLI._toggle_yolo(stand_in) # OFF
- db.set_session_yolo.assert_called_with(SESSION_ID, False)
def test_toggle_survives_missing_session_db(self):
stand_in = SimpleNamespace(session_id=SESSION_ID, _session_db=None)
@@ -182,12 +165,6 @@ class TestToggleYoloPersists:
HermesCLI._toggle_yolo(stand_in) # must not raise
assert approval_module.is_session_yolo_enabled(SESSION_ID) is True
- def test_toggle_still_works_without_persist_helper(self):
- # Back-compat with the minimal stand-in used by older tests.
- stand_in = SimpleNamespace(session_id=SESSION_ID)
- with patch("cli._cprint"):
- HermesCLI._toggle_yolo(stand_in)
- assert approval_module.is_session_yolo_enabled(SESSION_ID) is True
class TestEndToEndPersistAndRestore:
diff --git a/tests/hermes_cli/test_cli_yolo_toggle.py b/tests/hermes_cli/test_cli_yolo_toggle.py
index 4d2ca5146b2..a8a395095ea 100644
--- a/tests/hermes_cli/test_cli_yolo_toggle.py
+++ b/tests/hermes_cli/test_cli_yolo_toggle.py
@@ -23,7 +23,6 @@ file's path layout — ``HermesCLI.__init__`` imports a lot of optional
state we don't need here.
"""
-import os
from types import SimpleNamespace
from unittest.mock import patch
@@ -74,15 +73,6 @@ class TestToggleYoloIsSessionScoped:
can run.
"""
- def test_toggle_yolo_enables_session_bypass(self):
- stand_in = _make_stand_in()
-
- assert approval_module.is_session_yolo_enabled(SESSION_KEY) is False
-
- with patch("cli._cprint"):
- HermesCLI._toggle_yolo(stand_in)
-
- assert approval_module.is_session_yolo_enabled(SESSION_KEY) is True
def test_toggle_yolo_disables_session_bypass_on_second_call(self):
stand_in = _make_stand_in()
@@ -98,7 +88,7 @@ class TestToggleYoloIsSessionScoped:
"""``/yolo`` toggled in one session must not bypass approvals in
another session — mirrors the gateway-side invariant."""
cli_a = _make_stand_in(session_id="session-yolo-a")
- cli_b = _make_stand_in(session_id="session-yolo-b")
+ _make_stand_in(session_id="session-yolo-b")
try:
with patch("cli._cprint"):
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index daa13a895f2..2921234a1ae 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -101,18 +101,6 @@ class TestCmdUpdateNpmLockfileCache:
- def test_record_npm_lockfile_hash(self, tmp_path, monkeypatch):
- from hermes_cli import main as hm
-
- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)
- (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}')
-
- update_cmd._record_npm_lockfile_hash(tmp_path)
-
- assert (
- self._cache_file(tmp_path, tmp_path).read_text()
- == update_cmd._npm_manifests_digest()
- )
def test_package_json_only_edit_defeats_skip(self, tmp_path, monkeypatch):
"""Reviewer scenario (#61580): dev edits package.json WITHOUT running
@@ -189,18 +177,8 @@ class TestCmdUpdateTermuxUvBootstrap:
uv_bin = update_cmd._ensure_uv_for_termux(["/termux/python", "-m", "pip"])
assert uv_bin is None
- assert mock_run.call_count == 1
- assert mock_run.call_args.args[0] == [
- "/termux/python",
- "-m",
- "pip",
- "install",
- "uv",
- "--only-binary",
- ":all:",
- ]
- assert mock_run.call_args.kwargs["cwd"] == PROJECT_ROOT
- assert mock_run.call_args.kwargs["check"] is False
+ argv = mock_run.call_args.args[0]
+ assert argv[argv.index("--only-binary") + 1] == ":all:"
@patch("subprocess.run")
def test_termux_reuses_existing_path_uv_without_pip(self, mock_run, monkeypatch):
@@ -241,7 +219,7 @@ class TestUpdateManagedPythonEnvIsolation:
"VIRTUAL_ENV": r"C:\Some\Other\venv",
"PYTHONPATH": r"C:\Some\site-packages",
}
- env = managed_python_env()
+ env = managed_python_env(base_env=poisoned)
# Third-party UV_PYTHON_INSTALL_DIR must not survive into the env.
assert env.get("UV_PYTHON_INSTALL_DIR", "") != r"C:\WorkBuddy\python"
@@ -254,23 +232,7 @@ class TestUpdateManagedPythonEnvIsolation:
assert env.get("UV_NO_MANAGED_PYTHON") is None
assert env.get("VIRTUAL_ENV") is None
assert env.get("PYTHONPATH") is None
- # Sanity: the poisoned values did exist on input (guards the test itself).
- assert poisoned["UV_PYTHON_INSTALL_DIR"].startswith("C:\\WorkBuddy")
-
- def test_update_uv_env_points_venv_and_runtime_store(self):
- """The update's final uv_env must carry VIRTUAL_ENV=this venv while the
- managed store path is still the UV_PYTHON_INSTALL_DIR."""
- from hermes_cli import main as hm
- from hermes_cli.managed_uv import managed_python_env
-
- uv_env = managed_python_env()
- uv_env["VIRTUAL_ENV"] = str(PROJECT_ROOT / "venv")
- assert uv_env["VIRTUAL_ENV"] == str(PROJECT_ROOT / "venv")
- # Managed store stays the install-scoped runtime dir, not a third-party one.
- assert ".hermes-runtime" in uv_env.get("UV_PYTHON_INSTALL_DIR", "")
- assert uv_env.get("UV_MANAGED_PYTHON") == "1"
- assert uv_env.get("UV_NO_CONFIG") == "1"
class TestRepairCurrentCheckoutRuntimeRepair:
@@ -373,35 +335,6 @@ class TestRepairCurrentCheckoutRuntimeRepair:
assert calls == ["memory"]
assert restored[-1][0] == "tools"
- def test_venv_repair_path_refreshes_memory_provider(self, monkeypatch, tmp_path):
- """The unhealthy-venv repair path heals memory-provider bridge packages too
- (parity with pull/ZIP, #113741). Drives _repair_venv_on_current_checkout."""
- from hermes_cli import main as hm
-
- calls: list = []
- monkeypatch.setattr(hm, "_abort_dependency_sync_if_self_locked", lambda *_a, **k: None)
- monkeypatch.setattr(update_cmd, "_write_update_incomplete_marker", lambda: None)
- monkeypatch.setattr(update_cmd, "_venv_core_imports_healthy", lambda: (True, "ok"))
- monkeypatch.setattr(update_cmd, "project_venv_dir", lambda _root: tmp_path / "venv")
- monkeypatch.setattr(
- update_cmd, "venv_python_path", lambda _d, **k: tmp_path / "venv" / "bin" / "python")
- monkeypatch.setattr(update_cmd, "_pip_install_prefix", lambda _uv: (["uv", "pip"], {}))
- monkeypatch.setattr(
- hm, "_install_python_dependencies_with_optional_fallback", lambda *_a, **k: None)
- monkeypatch.setattr(hm, "_refresh_active_lazy_features", lambda *a, **k: True)
- monkeypatch.setattr(hm, "_restore_active_tool_dependencies", lambda *a, **k: None)
- monkeypatch.setattr(
- hm, "_refresh_active_memory_provider_dependencies", lambda: calls.append("memory"))
- monkeypatch.setattr(hm, "_clear_update_incomplete_marker", lambda: None)
- monkeypatch.setattr(hm, "_is_windows", lambda: False)
- monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", lambda **k: "uv")
-
- assert update_cmd._repair_venv_on_current_checkout(
- assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None,
- had_desktop_app_before_update=False, active_lazy_features=[],
- active_tool_dependencies=[], _windows_gateway_resume=None,
- )
- assert calls == ["memory"]
class TestCmdUpdateBranchFallback:
"""cmd_update falls back to main when current branch has no remote counterpart."""
@@ -479,7 +412,6 @@ class TestCmdUpdateBranchFallback:
add_remote.assert_not_called()
mark_skip.assert_not_called()
captured = capsys.readouterr()
- assert "Skipping upstream setup (non-interactive run)." in captured.out
assert "official repo not checked" in captured.out
assert "Already up to date!" not in captured.out
@@ -766,41 +698,6 @@ class TestCmdUpdateMigrationPrompt:
assert "display.personality=none (one-time reset)" in out
assert "Disabled suspicious MCP server 'evil'" in out
- def test_new_options_are_listed_by_name_before_prompt(
- self, mock_args, capsys
- ):
- """New env/config keys are printed by name so the user can decide."""
- env_items = [
- {"name": "FOO_API_KEY", "description": "Foo service API key"},
- ]
- cfg_items = [
- {"key": "display.new_widget", "description": "New config option: display.new_widget"},
- ]
- with patch("shutil.which", return_value=None), patch(
- "subprocess.run"
- ) as mock_run, patch("builtins.input", return_value="n"), patch(
- "hermes_cli.config.get_missing_env_vars", return_value=env_items
- ), patch(
- "hermes_cli.config.get_missing_config_fields", return_value=cfg_items
- ), patch(
- "hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 24)
- ), patch(
- "hermes_cli.update_cmd._run_migrate_config_fresh",
- return_value={"env_added": [], "config_added": [], "warnings": []},
- ), patch("hermes_cli.main.sys") as mock_sys:
- mock_sys.stdin.isatty.return_value = True
- mock_sys.stdout.isatty.return_value = True
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- cmd_update(mock_args)
-
- out = capsys.readouterr().out
- # Names, not just counts.
- assert "FOO_API_KEY" in out
- assert "Foo service API key" in out
- assert "display.new_widget" in out
class TestCmdUpdateProfileSkillSync:
@@ -848,34 +745,6 @@ class TestCmdUpdateProfileSkillSync:
f"All profiles must be synced; got: {synced_paths}"
)
- @patch("shutil.which", return_value=None)
- @patch("subprocess.run")
- def test_single_profile_default_is_synced(
- self, mock_run, _mock_which, mock_args, capsys
- ):
- from pathlib import Path
-
- mock_run.side_effect = _make_run_side_effect(
- branch="main", verify_ok=True, commit_count="1"
- )
-
- default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes"))
- synced_paths = []
-
- def fake_seed(path, quiet=False):
- synced_paths.append(path)
- return {"copied": [], "updated": [], "user_modified": []}
-
- empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []}
-
- with (
- patch("hermes_cli.profiles.list_profiles", return_value=[default_p]),
- patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),
- patch("tools.skills_sync.sync_skills", return_value=empty_sync),
- ):
- cmd_update(mock_args)
-
- assert default_p.path in synced_paths
class TestCmdUpdateBranchFlag:
@@ -1258,107 +1127,6 @@ class TestNodeRuntimeNpmResolution:
env=ANY,
)
- def test_git_failure_zip_fallback_rebuilds_missing_desktop(self, tmp_path, monkeypatch):
- """The Windows ZIP fallback keeps Desktop intact when replacing ``apps/``.
-
- Contract updated for the #70337/#87331 release-dir graft: the built
- desktop app (release/win-unpacked/Hermes.exe) is preserved THROUGH
- the swap — previously this test pinned the old repair shape (exe
- deleted by the swap, then rebuilt from scratch). The rebuild hook
- still runs (mocked _desktop_build_needed=True), but it now finds
- the packaged exe alive rather than missing.
- """
- import zipfile
-
- from hermes_cli import main as hm
- from hermes_cli import update_cmd
-
- project_root = tmp_path / "hermes-agent"
- (project_root / ".git").mkdir(parents=True)
- desktop_dir = project_root / "apps" / "desktop"
- packaged_exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"
- packaged_exe.parent.mkdir(parents=True)
- packaged_exe.write_bytes(b"desktop")
-
- def write_source_zip(_url, destination):
- with zipfile.ZipFile(destination, "w") as archive:
- archive.writestr("hermes-agent-main/apps/desktop/package.json", "{}")
-
- def fail_git_fetch(command, **_kwargs):
- if "fetch" in command:
- raise subprocess.CalledProcessError(1, command)
- return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
-
- desktop_builds = []
-
- def rebuild_desktop(*_args, **_kwargs):
- desktop_builds.append(not packaged_exe.exists())
- return subprocess.CompletedProcess([], 0, stdout="", stderr="")
-
- monkeypatch.setattr(hm, "PROJECT_ROOT", project_root)
- monkeypatch.setattr(hm, "_is_windows", lambda: True)
- monkeypatch.setattr(hm, "_run_pre_update_backup", lambda _args: None)
- monkeypatch.setattr(hm, "_pause_windows_gateways_for_update", lambda: None)
- monkeypatch.setattr(hm, "_get_origin_url", lambda *_args: "")
- monkeypatch.setattr(
- hm,
- "_desktop_packaged_executable",
- lambda _desktop_dir: packaged_exe if packaged_exe.exists() else None,
- )
- monkeypatch.setattr(hm, "_desktop_dist_exists", lambda _desktop_dir: False)
- monkeypatch.setattr(hm, "_resolve_node_runtime_npm", lambda: "npm.cmd")
- monkeypatch.setattr(hm, "_desktop_build_needed", lambda *_args, **_kwargs: True)
- monkeypatch.setattr(hm, "_run_logged_subprocess", rebuild_desktop)
- monkeypatch.setattr(hm, "_clear_bytecode_cache", lambda *_args: 0)
- monkeypatch.setattr(hm, "_record_bytecode_fingerprint", lambda: None)
- monkeypatch.setattr(hm, "_refresh_bootstrap_cache_scripts", lambda _branch: None)
- monkeypatch.setattr(
- hm, "_install_python_dependencies_with_optional_fallback", lambda *_args, **_kwargs: None
- )
- monkeypatch.setattr(hm, "_refresh_active_memory_provider_dependencies", lambda: None)
- monkeypatch.setattr(hm, "_build_web_ui", lambda *_args: None)
- monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *_args: None)
- monkeypatch.setattr(update_cmd, "_normalize_managed_eol", lambda *_args: None)
- monkeypatch.setattr(
- update_cmd,
- "_validate_critical_modules_import",
- lambda *_args: (True, None, None),
- )
- monkeypatch.setattr(update_cmd, "_update_node_dependencies", lambda: [])
- monkeypatch.setattr(update_cmd, "_print_curator_first_run_notice", lambda: None)
- monkeypatch.setattr(update_cmd, "_print_curator_recent_run_notice", lambda: None)
- monkeypatch.setattr(update_cmd, "_finish_dashboard_update_cleanup", lambda _failures: None)
- monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: tmp_path / "hermes-home")
-
- with (
- patch("hermes_cli.config.load_config", return_value={}),
- patch("subprocess.run", side_effect=fail_git_fetch),
- patch("urllib.request.urlretrieve", side_effect=write_source_zip),
- patch("hermes_cli.managed_uv.ensure_uv", return_value="uv"),
- patch("hermes_cli.managed_uv.update_managed_uv"),
- patch(
- "tools.skills_sync.sync_skills",
- return_value={
- "copied": [],
- "updated": [],
- "user_modified": [],
- "cleaned": [],
- "relocated": [],
- },
- ),
- patch("hermes_cli.model_catalog.seed_cache_from_checkout", return_value=False),
- ):
- update_cmd._cmd_update_impl(
- SimpleNamespace(yes=True, force=True, force_venv=True, branch=None),
- gateway_mode=False,
- )
-
- # Release-dir graft (#70337): the packaged exe SURVIVES the swap, so
- # the rebuild hook observed it present (False), and the bytes are the
- # original build — never deleted, never rebuilt from nothing.
- assert desktop_builds == [False]
- assert packaged_exe.exists()
- assert packaged_exe.read_bytes() == b"desktop"
class TestUpdateNodeDependencies:
@@ -1478,26 +1246,6 @@ class TestUpdateNodeDependencies:
assert "--include-workspace-root" in joined
assert "desktop" not in joined
- @patch("subprocess.Popen")
- @patch("shutil.which", return_value="/usr/bin/npm")
- def test_install_preserves_standard_flags(self, _which, mock_popen, tmp_path, monkeypatch):
- """--no-fund, --no-audit, --progress=false must survive."""
- from hermes_cli import main as hm
-
- (tmp_path / "package.json").write_text("{}")
- (tmp_path / "package-lock.json").write_text("{}")
- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)
- popen_calls = []
- mock_popen.side_effect = self._make_popen(popen_calls)
-
- update_cmd._update_node_dependencies()
-
- calls = self._popen_npm_calls(popen_calls)
- assert len(calls) == 1
- joined = " ".join(str(a) for a in calls[0])
- for flag in ("--no-fund", "--no-audit", "--progress=false"):
- assert flag in joined, f"{flag} missing from npm call; actual: {calls[0]}"
@patch("subprocess.run")
@patch("shutil.which", return_value="/usr/bin/npm")
@@ -1516,23 +1264,6 @@ class TestUpdateNodeDependencies:
"npm must not run when _npm_lockfile_changed reports no change"
)
- @patch("subprocess.Popen")
- @patch("shutil.which", return_value="/usr/bin/npm")
- def test_runs_install_when_lockfile_changed(self, _which, mock_popen, tmp_path, monkeypatch):
- """When _npm_lockfile_changed reports a change, npm must run."""
- from hermes_cli import main as hm
-
- (tmp_path / "package.json").write_text("{}")
- (tmp_path / "package-lock.json").write_text("{}")
- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)
- popen_calls = []
- mock_popen.side_effect = self._make_popen(popen_calls)
-
- update_cmd._update_node_dependencies()
-
- calls = self._popen_npm_calls(popen_calls)
- assert len(calls) == 1, f"expected npm to run when lockfile changed; got: {calls}"
@patch("subprocess.Popen")
@patch("shutil.which", return_value="/usr/bin/npm")
@@ -1556,27 +1287,6 @@ class TestUpdateNodeDependencies:
assert not recorded, "lockfile hash must not be recorded when npm install fails"
- @patch("subprocess.Popen")
- @patch("shutil.which", return_value="/usr/bin/npm")
- def test_warms_npx_agent_browser_cache_regardless_of_install_result(
- self, _which, mock_popen, tmp_path, monkeypatch
- ):
- """The npx warm-up must fire even when the workspace install fails —
- it's independent of ui-tui/web dependency state (#43564)."""
- from hermes_cli import main as hm
-
- (tmp_path / "package.json").write_text("{}")
- (tmp_path / "package-lock.json").write_text("{}")
- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)
- mock_popen.side_effect = self._make_popen([], returncode=1, stderr_lines=["npm ERR!\n"])
-
- with patch(
- "tools.browser_tool_install.warm_agent_browser_npx_cache", return_value=True
- ) as mock_warm:
- update_cmd._update_node_dependencies()
-
- mock_warm.assert_called_once()
@patch("subprocess.run")
@patch("shutil.which", return_value=None)
@@ -1629,96 +1339,7 @@ class TestUpdateNodeDependencies:
class TestGitTrampolineSelfHeal:
- """Proactive Git-for-Windows trampoline self-heal (#87876).
-
- A broken bin\\git.exe / cmd\\git.exe shim (~46KB) refuses every git call
- with a "BUG (fork bomb)" guard instead of re-execing the real git-core
- binary. _ensure_non_trampoline_git detects this up front and swaps in a
- real git binary when one can be located, so the normal git update path
- survives instead of degrading to the ZIP fallback.
- """
-
- @staticmethod
- def _fake_run_healthy(command, **_kwargs):
- return subprocess.CompletedProcess(
- command, 0, stdout="git version 2.50.0.windows.1\n", stderr=""
- )
-
- @staticmethod
- def _fake_run_trampoline(command, **_kwargs):
- return subprocess.CompletedProcess(
- command,
- 1,
- stdout="",
- stderr="BUG (fork bomb): tried to spawn itself, check your PATH\n",
- )
-
- def test_healthy_git_command_unchanged(self):
- from hermes_cli import update_cmd
-
- git_cmd = ["git", "-c", "windows.appendAtomically=false"]
- with (
- patch("sys.platform", "win32"),
- patch(
- "hermes_cli.update_cmd.subprocess.run",
- side_effect=self._fake_run_healthy,
- ),
- patch("hermes_cli.update_cmd._locate_real_git") as locate,
- ):
- result = update_cmd._ensure_non_trampoline_git(git_cmd)
- assert result == git_cmd
- locate.assert_not_called()
-
- def test_trampoline_swaps_to_real_git(self, capsys):
- from pathlib import Path
-
- from hermes_cli import update_cmd
-
- git_cmd = ["git", "-c", "windows.appendAtomically=false"]
- real = Path(r"C:\Program Files\Git\mingw64\libexec\git-core\git.exe")
- with (
- patch("sys.platform", "win32"),
- patch(
- "hermes_cli.update_cmd.subprocess.run",
- side_effect=self._fake_run_trampoline,
- ),
- patch(
- "hermes_cli.update_cmd._locate_real_git", return_value=real
- ),
- ):
- result = update_cmd._ensure_non_trampoline_git(git_cmd)
- assert result == [str(real), "-c", "windows.appendAtomically=false"]
- out = capsys.readouterr().out
- assert "switching to real git" in out
-
- def test_trampoline_no_real_git_keeps_command(self, capsys):
- from hermes_cli import update_cmd
-
- git_cmd = ["git", "-c", "windows.appendAtomically=false"]
- with (
- patch("sys.platform", "win32"),
- patch(
- "hermes_cli.update_cmd.subprocess.run",
- side_effect=self._fake_run_trampoline,
- ),
- patch("hermes_cli.update_cmd._locate_real_git", return_value=None),
- ):
- result = update_cmd._ensure_non_trampoline_git(git_cmd)
- assert result == git_cmd
- out = capsys.readouterr().out
- assert "ZIP path" in out
-
- def test_off_windows_noop(self):
- from hermes_cli import update_cmd
-
- git_cmd = ["git"]
- with (
- patch("sys.platform", "linux"),
- patch("hermes_cli.update_cmd.subprocess.run") as run,
- ):
- result = update_cmd._ensure_non_trampoline_git(git_cmd)
- assert result == git_cmd
- run.assert_not_called()
+ """PortableGit candidate lookup for the Git-for-Windows trampoline self-heal (#87876)."""
def test_portable_git_candidates_check_shared_root_first(self, tmp_path, monkeypatch):
# Profile-scoped layout: HERMES_HOME = <root>/profiles/foo, but the
diff --git a/tests/hermes_cli/test_cmd_update_docker.py b/tests/hermes_cli/test_cmd_update_docker.py
index cde65bebbff..df7d8a59f2c 100644
--- a/tests/hermes_cli/test_cmd_update_docker.py
+++ b/tests/hermes_cli/test_cmd_update_docker.py
@@ -22,7 +22,6 @@ from unittest.mock import patch
import pytest
from hermes_cli.main import cmd_update
-from hermes_cli.update_cmd import _cmd_update_check
# ---------- cmd_update (apply path) ----------
@@ -66,27 +65,3 @@ def test_cmd_update_in_docker_prints_guidance_and_exits(
# ---------- format_docker_update_message — content lock ----------
-def test_format_docker_update_message_contents():
- """Lock in the high-value content of the Docker update message.
-
- These are the bits a user actually needs to act on; if any of them
- disappear in a copy edit, the message has lost its value. Specific
- wording around them is free to evolve (we don't assert full text).
- """
- from hermes_cli.config import format_docker_update_message
-
- msg = format_docker_update_message()
-
- # Primary command — the entire reason this message exists.
- assert "docker pull nousresearch/hermes-agent:latest" in msg
-
- # The four key concepts the message must cover:
- assert "restart" in msg.lower(), "must explain that a restart is required"
- assert "--version" in msg, "must show how to verify the new version"
- assert ":latest" in msg, "must mention tag pinning caveat"
- assert "HERMES_HOME" in msg or "/opt/data" in msg, (
- "must address config persistence across upgrades"
- )
-
- # Acknowledges that forks exist (build-your-own-image escape hatch).
- assert "fork" in msg.lower() or "Dockerfile" in msg
diff --git a/tests/hermes_cli/test_code_skew.py b/tests/hermes_cli/test_code_skew.py
index 2bde4b56349..26dc799ba5d 100644
--- a/tests/hermes_cli/test_code_skew.py
+++ b/tests/hermes_cli/test_code_skew.py
@@ -44,22 +44,13 @@ class TestDetectCodeSkew:
class TestShort:
- def test_shortens_long_sha(self):
- assert code_skew._short("git:refs/heads/main:abcdef0123456789") == "abcdef0123"
def test_keeps_unresolved_marker(self):
assert code_skew._short("git:refs/heads/main:unresolved") == "unresolved"
- def test_passes_short_sha_through_untruncated(self):
- assert code_skew._short("git:HEAD:abc1234") == "abc1234"
class TestModelSwitchSkewGuard:
- def test_guard_returns_none_without_skew(self, monkeypatch):
- from gateway import slash_commands_model as slash_commands
-
- monkeypatch.setattr(code_skew, "detect_code_skew", lambda: None)
- assert slash_commands._model_switch_skew_guard() is None
def test_guard_message_names_revs_and_restart(self, monkeypatch):
from gateway import slash_commands_model as slash_commands
@@ -75,14 +66,8 @@ class TestModelSwitchSkewGuard:
class TestDashboardCodeSkewGuard:
"""Dashboard mirror of the gateway's model-switch skew guard (#86207)."""
- def test_dashboard_guard_returns_none_without_skew(self, monkeypatch):
- from hermes_cli import web_server
-
- monkeypatch.setattr(code_skew, "detect_code_skew", lambda: None)
- assert _web_server_config._dashboard_code_skew_guard() is None
def test_dashboard_guard_message_names_revs_and_restart(self, monkeypatch):
- from hermes_cli import web_server
monkeypatch.delenv("HERMES_SERVE_HEADLESS", raising=False)
monkeypatch.setattr(code_skew, "detect_code_skew", lambda: ("abc1234567", "def4567890"))
@@ -95,7 +80,6 @@ class TestDashboardCodeSkewGuard:
assert "systemctl" not in msg
def test_serve_guard_message_points_at_desktop_backend(self, monkeypatch):
- from hermes_cli import web_server
monkeypatch.setenv("HERMES_SERVE_HEADLESS", "1")
monkeypatch.setattr(code_skew, "detect_code_skew", lambda: ("abc1234567", "def4567890"))
@@ -118,7 +102,6 @@ class TestModelOptionsSkewGuard:
def test_stale_dashboard_returns_503_and_skips_payload_build(self, monkeypatch):
from fastapi import HTTPException
- from hermes_cli import web_server
monkeypatch.setattr(code_skew, "detect_code_skew", lambda: ("abc1234567", "def4567890"))
@@ -137,7 +120,6 @@ class TestModelOptionsSkewGuard:
assert payload_calls == []
def test_fresh_dashboard_builds_payload_unchanged(self, monkeypatch):
- from hermes_cli import web_server
monkeypatch.setattr(code_skew, "detect_code_skew", lambda: None)
diff --git a/tests/hermes_cli/test_codex_models.py b/tests/hermes_cli/test_codex_models.py
index 7af4137eb66..67a7fc25b8e 100644
--- a/tests/hermes_cli/test_codex_models.py
+++ b/tests/hermes_cli/test_codex_models.py
@@ -2,8 +2,6 @@ import json
from unittest.mock import patch
from hermes_cli.codex_models import (
- DEFAULT_CODEX_MODELS,
- _FORWARD_COMPAT_TEMPLATE_MODELS,
get_codex_model_ids,
)
@@ -15,24 +13,6 @@ CHATGPT_REJECTED_CODEX_PRO_SLUGS = {
}
-def test_curated_codex_fallback_excludes_chatgpt_rejected_pro_slugs(monkeypatch):
- """OAuth fallback retains real models but never synthesizes rejected ones."""
- retained_models = {"gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"}
- template_models = {model for model, _fallbacks in _FORWARD_COMPAT_TEMPLATE_MODELS}
-
- assert retained_models.issubset(DEFAULT_CODEX_MODELS)
- assert retained_models.issubset(template_models)
- assert CHATGPT_REJECTED_CODEX_PRO_SLUGS.isdisjoint(DEFAULT_CODEX_MODELS)
- assert CHATGPT_REJECTED_CODEX_PRO_SLUGS.isdisjoint(template_models)
-
- monkeypatch.setattr(
- "hermes_cli.codex_models._fetch_models_from_api",
- lambda access_token: ["gpt-5.5"],
- )
- model_ids = get_codex_model_ids(access_token="codex-access-token")
-
- assert retained_models.issubset(model_ids)
- assert CHATGPT_REJECTED_CODEX_PRO_SLUGS.isdisjoint(model_ids)
def test_picker_synthesizes_900k_variants_for_verified_slugs():
@@ -66,27 +46,8 @@ def test_picker_never_synthesizes_900k_for_pro_or_unknown_slugs():
-def test_retired_gpt_5_3_codex_is_not_offered_offline():
- """The ChatGPT Codex backend retired ``gpt-5.3-codex`` (HTTP 400 "not supported when using
- Codex with a ChatGPT account", #52492). Neither the curated offline fallback nor any
- forward-compat template may surface it — only live discovery may, if the backend re-enables it.
- Same precedent as the gpt-5.2-codex / gpt-5.1-codex-* removal (e8955f222ce)."""
- from hermes_cli.codex_models import _FORWARD_COMPAT_TEMPLATE_MODELS, DEFAULT_CODEX_MODELS
-
- assert "gpt-5.3-codex" not in DEFAULT_CODEX_MODELS
- for newer, templates in _FORWARD_COMPAT_TEMPLATE_MODELS:
- assert newer != "gpt-5.3-codex"
- assert "gpt-5.3-codex" not in templates
- # Spark is still a real Codex-OAuth slug and must keep surfacing via a live template.
- assert "gpt-5.3-codex-spark" in DEFAULT_CODEX_MODELS
-def test_setup_wizard_codex_import_resolves():
- """Regression test for #712: setup.py must import the correct function name."""
- # This mirrors the exact import used in hermes_cli/setup.py line 873.
- # A prior bug had 'get_codex_models' (wrong) instead of 'get_codex_model_ids'.
- from hermes_cli.codex_models import get_codex_model_ids as setup_import
- assert callable(setup_import)
@@ -194,9 +155,6 @@ def test_model_command_prompts_to_reuse_or_reauthenticate_codex_session(monkeypa
_model_flow_openai_codex({}, current_model="gpt-5.4")
- out = capsys.readouterr().out
- assert "Use existing credentials" in out
- assert "Reauthenticate (new OAuth login)" in out
assert captured["login_calls"] == 1
assert captured["force_new_login"] is True
diff --git a/tests/hermes_cli/test_codex_runtime_plugin_migration.py b/tests/hermes_cli/test_codex_runtime_plugin_migration.py
index 42d3e131ed2..38982f949fe 100644
--- a/tests/hermes_cli/test_codex_runtime_plugin_migration.py
+++ b/tests/hermes_cli/test_codex_runtime_plugin_migration.py
@@ -2,16 +2,12 @@
from __future__ import annotations
-import argparse
-import pytest
from hermes_cli.codex_runtime_plugin_migration import (
MIGRATION_MARKER,
MIGRATION_END_MARKER,
_build_hermes_tools_mcp_entry,
- _format_toml_value,
- _looks_like_test_tempdir,
_strip_existing_managed_block,
_strip_unmanaged_plugin_tables,
_translate_one_server,
@@ -37,9 +33,6 @@ class TestTranslateOneServer:
assert skipped == []
- def test_enabled_true_omitted(self):
- cfg, _ = _translate_one_server("x", {"command": "y", "enabled": True})
- assert "enabled" not in cfg # codex defaults to true
def test_unknown_keys_warned(self):
@@ -104,9 +97,6 @@ class TestTomlValueFormatter:
class TestRenderToml:
- def test_empty_servers_emits_placeholder(self):
- out = render_codex_toml_section({})
- assert "no MCP servers" in out
def test_servers_sorted_alphabetically(self):
out = render_codex_toml_section({
@@ -273,14 +263,6 @@ class TestMigrate:
- def test_summary_reports_migration_count(self, tmp_path):
- report = migrate({
- "mcp_servers": {"a": {"command": "x"}, "b": {"command": "y"}}
- }, codex_home=tmp_path, expose_hermes_tools=False)
- summary = report.summary()
- assert "Migrated 2 MCP server(s)" in summary
- assert "- a" in summary
- assert "- b" in summary
# ---- Bug B: duplicate [plugins.X] tables ----
@@ -470,19 +452,6 @@ class TestSameNameUserMcpTable:
assert parsed["mcp_servers"]["gbrain"]["command"] == "existing-gbrain"
assert parsed["mcp_servers"]["other"]["command"] == "o"
- def test_unloadable_existing_config_explains_plugin_rerun(self, tmp_path, monkeypatch):
- """Repairing a pre-broken config.toml: codex cannot load it, so plugin/list fails on this
- run. The report must say plugins need a re-run instead of a bare discovery error."""
- from hermes_cli import codex_runtime_plugin_migration as crpm
-
- target = tmp_path / "config.toml"
- target.write_text('[mcp_servers.gbrain]\ncommand = "a"\n[mcp_servers.gbrain]\ncommand = "b"\n',
- encoding="utf-8")
- monkeypatch.setattr(crpm, "_query_codex_plugins",
- lambda codex_home=None, timeout=8.0, **_kw: ([], "plugin/list query failed"))
- report = migrate({}, codex_home=tmp_path, discover_plugins=True, expose_hermes_tools=False)
- assert "re-run `hermes codex-runtime migrate` to migrate plugins" in (report.plugin_query_error or "")
- assert "existing config.toml was unloadable" in report.summary()
def test_cli_migrate_dry_run_json_reports_without_writing(self, tmp_path, monkeypatch, capsys):
"""`hermes codex-runtime migrate --dry-run --json` is the supported automation seam:
diff --git a/tests/hermes_cli/test_codex_runtime_switch.py b/tests/hermes_cli/test_codex_runtime_switch.py
index ce5b9efccd0..a77d92efac0 100644
--- a/tests/hermes_cli/test_codex_runtime_switch.py
+++ b/tests/hermes_cli/test_codex_runtime_switch.py
@@ -110,8 +110,6 @@ class TestApply:
assert r.success
assert mig.called, "migration must run on reapply, not just first enable"
# Re-apply should signal "already set" but still announce migration ran
- assert "already set" in r.message
- assert "re-applying migration" in r.message
# Migration output still surfaces
assert "Migrated 1 MCP server" in r.message
assert "filesystem" in r.message
@@ -156,8 +154,6 @@ class TestApply:
assert "filesystem" in r.message
# Permissions default surfaces
assert "Default sandbox: :workspace" in r.message
- # Hermes tool callback announcement
- assert "via MCP" in r.message
def test_disable_does_not_trigger_migration(self):
"""Switching back to auto must not write to ~/.codex/."""
diff --git a/tests/hermes_cli/test_command_palette.py b/tests/hermes_cli/test_command_palette.py
index fa0ca9aa840..8ea113f2077 100644
--- a/tests/hermes_cli/test_command_palette.py
+++ b/tests/hermes_cli/test_command_palette.py
@@ -3,7 +3,6 @@
from types import SimpleNamespace
from cli import HermesCLI
-from hermes_cli.commands import HELP_SESSION_SUBGROUPS
def _bare_cli():
@@ -11,14 +10,6 @@ def _bare_cli():
return cli
-class TestHelpSubgroups:
- def test_session_subgroups_defined(self):
- # The oversized Session category is split into readable sub-headers.
- assert "Context" in HELP_SESSION_SUBGROUPS
- assert "Background & Automation" in HELP_SESSION_SUBGROUPS
- # Representative members land in the right buckets.
- assert "compress" in HELP_SESSION_SUBGROUPS["Context"]
- assert "goal" in HELP_SESSION_SUBGROUPS["Background & Automation"]
class TestCommandPaletteFilter:
diff --git a/tests/hermes_cli/test_commands.py b/tests/hermes_cli/test_commands.py
index 0beae730175..1fa8dc10b1f 100644
--- a/tests/hermes_cli/test_commands.py
+++ b/tests/hermes_cli/test_commands.py
@@ -3,7 +3,7 @@
from prompt_toolkit.completion import CompleteEvent
from prompt_toolkit.document import Document
-from hermes_cli.commands import COMMAND_REGISTRY, COMMANDS, COMMANDS_BY_CATEGORY, CommandDef, GATEWAY_KNOWN_COMMANDS, SUBCOMMANDS, command_desktop_meta, gateway_help_lines, infer_argument_mode, resolve_command
+from hermes_cli.commands import COMMAND_REGISTRY, COMMANDS_BY_CATEGORY, CommandDef, GATEWAY_KNOWN_COMMANDS, gateway_help_lines, infer_argument_mode, resolve_command
from hermes_cli.commands_completion import SlashCommandAutoSuggest, SlashCommandCompleter
from hermes_cli.commands_platforms import _CMD_NAME_LIMIT, _SLACK_RESERVED_COMMANDS, _SLACK_VIA_HERMES_ONLY, _clamp_command_names, _sanitize_telegram_name, slack_app_manifest, slack_native_slashes, slack_subcommand_map, telegram_bot_commands, telegram_menu_commands
@@ -24,14 +24,6 @@ def _completions(completer: SlashCommandCompleter, text: str):
class TestCommandRegistry:
- def test_save_command_supports_formats(self):
- cmd = resolve_command("save")
- assert cmd is not None
- assert cmd.name == "save"
- # /save is a cross-platform session export: json (default), md, html
- assert not cmd.cli_only
- for token in ("json", "md", "html"):
- assert token in (cmd.args_hint or "")
def test_no_duplicate_canonical_names(self):
names = [cmd.name for cmd in COMMAND_REGISTRY]
@@ -49,24 +41,6 @@ class TestCommandRegistry:
assert resolve_command(alias).name == cmd.name or alias == cmd.name, \
f"Alias '{alias}' of '{cmd.name}' shadows canonical '{target.name}'"
- def test_desktop_meta_lives_on_the_command_def(self):
- review = resolve_command("review")
- assert review is not None
- assert review.argument_mode is None
- assert infer_argument_mode(review) == "text"
- assert command_desktop_meta(review) == {"argument_mode": "text", "desktop": None}
-
- clear = resolve_command("clear")
- assert clear is not None
- assert clear.desktop == "terminal"
-
- model = resolve_command("model")
- assert model is not None
- assert model.desktop == "hidden"
-
- goal = resolve_command("goal")
- assert goal is not None
- assert goal.argument_mode == "mixed"
def test_argument_mode_infers_text_from_any_args_hint(self):
assert infer_argument_mode(CommandDef("demo", "Demo", "Session", args_hint="<prompt>")) == "text"
@@ -78,24 +52,6 @@ class TestCommandRegistry:
# resolve_command tests
# ---------------------------------------------------------------------------
-class TestResolveCommand:
-
-
- def test_topic_is_gateway_command(self):
- topic = resolve_command("topic")
- assert topic is not None
- assert topic.name == "topic"
- assert "topic" in GATEWAY_KNOWN_COMMANDS
-
- def test_context_command_registered_with_ctx_alias(self):
- ctx = resolve_command("context")
- assert ctx is not None
- assert ctx.name == "context"
- assert resolve_command("ctx").name == "context"
- assert "all" in (ctx.subcommands or ())
- # Available on both CLI and gateway surfaces
- assert not ctx.cli_only and not ctx.gateway_only
- assert "context" in GATEWAY_KNOWN_COMMANDS
# ---------------------------------------------------------------------------
@@ -105,13 +61,6 @@ class TestResolveCommand:
class TestDerivedDicts:
- def test_commands_dict_includes_aliases(self):
- assert "/bg" in COMMANDS
- assert "/reset" in COMMANDS
- assert "/q" in COMMANDS
- assert "/exit" in COMMANDS
- assert "/reload_mcp" in COMMANDS
- assert "/gateway" in COMMANDS
def test_commands_by_category_covers_all_categories(self):
registry_categories = {cmd.category for cmd in COMMAND_REGISTRY if not cmd.gateway_only}
@@ -132,8 +81,6 @@ class TestGatewayKnownCommands:
f"config-gated command '{cmd.name}' should be in GATEWAY_KNOWN_COMMANDS"
- def test_is_frozenset(self):
- assert isinstance(GATEWAY_KNOWN_COMMANDS, frozenset)
class TestGatewayHelpLines:
@@ -149,23 +96,9 @@ class TestGatewayHelpLines:
assert not re.search(pattern, joined), \
f"cli_only command /{cmd.name} should not be in gateway help"
- def test_bg_and_btw_are_separate_commands(self):
- lines = gateway_help_lines()
- joined = "\n".join(lines)
- assert "`/bg" in joined
- assert "`/btw" in joined
- # The retired /background canonical name must be gone.
- bg_line = [l for l in lines if "/background" in l]
- assert not bg_line
class TestTelegramBotCommands:
- def test_returns_list_of_tuples(self):
- cmds = telegram_bot_commands()
- assert len(cmds) > 10
- for name, desc in cmds:
- assert isinstance(name, str)
- assert isinstance(desc, str)
def test_no_hyphens_in_command_names(self):
"""Telegram does not support hyphens in command names."""
@@ -190,22 +123,9 @@ class TestTelegramBotCommands:
include_plugins=False)
- def test_includes_builtin_commands_with_required_args(self):
- """Built-in arg-taking commands (e.g. /queue, /steer, /bg, /btw)
- are now included because their handlers return usage text when
- invoked without arguments — issue #24312."""
- names = {name for name, _ in telegram_bot_commands()}
- assert "bg" in names
- assert "btw" in names
- assert "queue" in names
- assert "steer" in names
class TestSlackSubcommandMap:
- def test_returns_dict(self):
- mapping = slack_subcommand_map()
- assert isinstance(mapping, dict)
- assert len(mapping) > 10
def test_values_are_slash_prefixed(self):
for key, val in slack_subcommand_map().items():
@@ -279,12 +199,6 @@ class TestSlackAppManifest:
# HTML-escapes args — we want the raw text)
assert "should_escape" in entry
- def test_btw_is_in_manifest(self):
- """Regression: /btw must be a native Slack slash, not just a
- /hermes subcommand."""
- m = slack_app_manifest()
- commands = [c["command"] for c in m["features"]["slash_commands"]]
- assert "/btw" in commands
# ---------------------------------------------------------------------------
@@ -295,9 +209,6 @@ class TestGatewayConfigGate:
"""Tests for the gateway_config_gate mechanism on CommandDef."""
- def test_verbose_in_gateway_known_commands(self):
- """Config-gated commands are always recognized by the gateway."""
- assert "verbose" in GATEWAY_KNOWN_COMMANDS
def test_config_gate_excluded_from_help_when_off(self, tmp_path, monkeypatch):
"""When the config gate is falsy, the command should not appear in help."""
@@ -395,18 +306,6 @@ class TestStackedSkillCompletion:
# ── SUBCOMMANDS extraction ──────────────────────────────────────────────
-class TestSubcommands:
- def test_explicit_subcommands_extracted(self):
- """Commands with explicit subcommands on CommandDef are extracted."""
- assert "/skills" in SUBCOMMANDS
- assert "install" in SUBCOMMANDS["/skills"]
-
-
- def test_commands_without_subcommands_not_in_dict(self):
- """Plain commands should not appear in SUBCOMMANDS."""
- assert "/help" not in SUBCOMMANDS
- assert "/quit" not in SUBCOMMANDS
- assert "/clear" not in SUBCOMMANDS
# ── Subcommand tab completion ───────────────────────────────────────────
diff --git a/tests/hermes_cli/test_commands_execute.py b/tests/hermes_cli/test_commands_execute.py
index 23b3ce02cfb..2ece9057872 100644
--- a/tests/hermes_cli/test_commands_execute.py
+++ b/tests/hermes_cli/test_commands_execute.py
@@ -1,48 +1,16 @@
-"""Invariant tests for registry-owned slash execution (CommandDef.execute).
+"""Invariant for registry-owned slash execution (CommandDef.execute).
-Every ``CommandDef`` with ``execute`` set must:
- * name a key that exists in :data:`hermes_cli.slash_exec.EXECUTORS`, and
- * produce IDENTICAL core text across surfaces for a fixed context — the
- executor may only vary on ``args``/``options``, never on ``surface``.
+Every ``CommandDef`` with ``execute`` set must name a key that exists in
+:data:`hermes_cli.slash_exec.EXECUTORS`; otherwise the command silently falls
+through to "unknown command" on every surface.
"""
-import pytest
-
-from hermes_cli.commands import COMMAND_REGISTRY, resolve_command
-from hermes_cli.slash_exec import (
- EXECUTORS,
- CommandContext,
- CommandReply,
- execute_command,
- resolve_executor,
- run_execute,
-)
-
-MIGRATED = [cmd for cmd in COMMAND_REGISTRY if cmd.execute]
-
-SURFACES = ("cli", "gateway", "tui")
-
-
-def test_some_commands_are_migrated():
- names = {cmd.name for cmd in MIGRATED}
- # The thin-slice set — extend as more commands migrate.
- assert {"version", "egress", "profile", "bundles", "help", "commands"} <= names
-
-
-
-
-def test_unmigrated_commands_have_no_executor():
- for cmd in COMMAND_REGISTRY:
- if not cmd.execute:
- assert resolve_executor(cmd) is None
- assert run_execute(cmd, CommandContext()) is None
-
-
-
-
-
-
-
-
+from hermes_cli.commands import COMMAND_REGISTRY
+from hermes_cli.slash_exec import resolve_executor
+def test_every_execute_key_resolves_to_an_executor():
+ migrated = [cmd for cmd in COMMAND_REGISTRY if cmd.execute]
+ assert migrated
+ unresolved = [cmd.name for cmd in migrated if resolve_executor(cmd) is None]
+ assert not unresolved, f"CommandDef.execute names no EXECUTORS entry: {unresolved}"
diff --git a/tests/hermes_cli/test_compat_manifest_targets.py b/tests/hermes_cli/test_compat_manifest_targets.py
index d181493f367..b63bed8970d 100644
--- a/tests/hermes_cli/test_compat_manifest_targets.py
+++ b/tests/hermes_cli/test_compat_manifest_targets.py
@@ -12,7 +12,6 @@ import importlib
import importlib.util
import json
import pkgutil
-import sqlite3
import sys
from pathlib import Path
@@ -102,4 +101,3 @@ def test_kanban_db_connect_opens_a_kanban_board(tmp_path, monkeypatch):
conn.close()
assert "tasks" in tables, tables
assert not (tmp_path / "projects.db").exists()
- assert isinstance(sqlite3.connect(db), sqlite3.Connection)
diff --git a/tests/hermes_cli/test_completer_config_reads.py b/tests/hermes_cli/test_completer_config_reads.py
index 5634eff355b..b7a3fc46323 100644
--- a/tests/hermes_cli/test_completer_config_reads.py
+++ b/tests/hermes_cli/test_completer_config_reads.py
@@ -1,15 +1,5 @@
-"""Measured-work pins for the slash-completer config reads.
-
-The /tools and /personality completers run on every keystroke while the
-user types those commands (complete_while_typing). They used to re-read +
-re-parse the full config on every keypress: load_config()'s defensive
-deepcopy (~345us tax) in _tools_completions, and load_cli_config()'s full
-YAML parse + defaults deep-merge (~110us) in _personality_completions.
-These pins hold the per-keystroke cost down:
-- _tools_completions uses the read-only loader (no deepcopy).
-- _personality_completions memoises the personalities source keyed on the
- config file's mtime, so the parse+merge runs once per config state.
-"""
+"""The /personality completer memoises the parsed config per keystroke, but a
+config edit on disk must show up in the next completion (never a stale list)."""
from __future__ import annotations
@@ -17,123 +7,38 @@ import os
from unittest.mock import patch
import pytest
+import yaml
import hermes_cli.commands_completion as commands_mod
-def _reset_personalities_memo():
- commands_mod._personalities_memo = None
-
-
@pytest.fixture(autouse=True)
def _reset_memo():
- _reset_personalities_memo()
+ commands_mod._personalities_memo = None
yield
- _reset_personalities_memo()
-
-
-class TestToolsCompletionsReadonlyConfig:
- def test_uses_readonly_loader(self):
- """_tools_completions must not pay the defensive deepcopy.
-
- The completer only reads the config (toolset enable state + MCP
- server names). Using load_config_readonly() skips the ~345us
- deepcopy that load_config() applies on every cache hit — a
- per-keystroke cost while completing /tools enable|disable.
- """
- calls = {"deepcopy": 0, "readonly": 0}
-
- def counting_deepcopy(*a, **k):
- calls["deepcopy"] += 1
- return {}
-
- def counting_readonly(*a, **k):
- calls["readonly"] += 1
- return {}
-
- # The completer imports the loader inside the function, so patch the
- # source module. Portable-MCP lookup is stubbed because it triggers
- # one-time plugin discovery (which legitimately calls load_config
- # during process init) — this test asserts on the completer's own
- # per-keystroke reads, not discovery's one-off startup reads.
- with patch("hermes_cli.config.load_config", counting_deepcopy), \
- patch("hermes_cli.config.load_config_readonly", counting_readonly), \
- patch("hermes_cli.plugins.get_portable_mcp_server_names_nowait", lambda: set()), \
- patch("hermes_cli.tools_config._get_plugin_toolset_keys", lambda: set()), \
- patch("hermes_cli.tools_config._homeassistant_credentials_present", lambda: False), \
- patch("hermes_cli.tools_config._xai_credentials_present", lambda: False):
- list(commands_mod.SlashCommandCompleter._tools_completions("enable ", "enable "))
-
- assert calls["readonly"] == 1, "completer should use the readonly loader"
- assert calls["deepcopy"] == 0, (
- "completer must not call the deepcopy loader on a read-only path"
- )
+ commands_mod._personalities_memo = None
class TestPersonalityCompletionsMemo:
- def test_load_cli_config_called_once_per_config_state(self, monkeypatch):
- """The /personality completer parses the config once per state.
-
- load_cli_config() does a full YAML parse + deep merge of the
- built-in defaults; the completer runs on every keystroke. The
- mtime-keyed memo keeps that parse to once per config change.
- """
- calls = {"n": 0}
-
- def counting_load_cli_config():
- calls["n"] += 1
- return {
- "agent": {
- "personalities": {
- "helpful": "You are helpful.",
- "concise": "You are concise.",
- }
- }
- }
-
- monkeypatch.setattr(commands_mod, "_personalities_memo", None)
- with patch("cli.load_cli_config", counting_load_cli_config):
- # First call: cache miss -> one parse.
- list(commands_mod.SlashCommandCompleter._personality_completions("hel", "hel"))
- assert calls["n"] == 1, "first call should parse once"
-
- # Subsequent keystrokes: cache hit -> no re-parse.
- for _ in range(10):
- list(commands_mod.SlashCommandCompleter._personality_completions("hel", "hel"))
- assert calls["n"] == 1, (
- "repeated keystrokes must reuse the memoised personalities, "
- f"got {calls['n']} parses"
- )
-
- def test_mtime_change_reparses(self, monkeypatch, tmp_path):
- """A config file change on disk invalidates the memo."""
- from pathlib import Path
-
+ def test_config_edit_on_disk_refreshes_completions(self, tmp_path):
cfg_path = tmp_path / "config.yaml"
- cfg_path.write_text(
- "agent:\n personalities:\n helpful: \"v1\"\n",
- encoding="utf-8",
- )
- # Pin an explicit mtime so the change below is a guaranteed mtime_ns
- # bump regardless of filesystem timestamp granularity.
+ cfg_path.write_text("agent:\n personalities:\n zzfirst: v1\n", encoding="utf-8")
+ # Pin mtimes so the edit below is a guaranteed signature change
+ # regardless of filesystem timestamp granularity.
os.utime(cfg_path, (1_700_000_000, 1_700_000_000))
- calls = {"n": 0}
-
- def counting_load_cli_config():
- calls["n"] += 1
- return {"agent": {"personalities": {"helpful": "v1"}}}
+ def load_cli_config_from_disk():
+ return yaml.safe_load(cfg_path.read_text(encoding="utf-8"))
- def fake_config_path():
- return cfg_path
+ def names():
+ return {c.text for c in commands_mod.SlashCommandCompleter._personality_completions("zz", "zz")}
- monkeypatch.setattr(commands_mod, "_personalities_memo", None)
- with patch("cli.load_cli_config", counting_load_cli_config), \
- patch("hermes_cli.config.get_config_path", fake_config_path):
- list(commands_mod.SlashCommandCompleter._personality_completions("h", "h"))
- assert calls["n"] == 1
+ with patch("cli.load_cli_config", load_cli_config_from_disk), \
+ patch("hermes_cli.config.get_config_path", lambda: cfg_path):
+ assert "zzfirst" in names()
- # Bump the file mtime -> memo invalidates -> re-parse once.
+ cfg_path.write_text("agent:\n personalities:\n zzsecond: v2\n", encoding="utf-8")
os.utime(cfg_path, (1_800_000_000, 1_800_000_000))
- list(commands_mod.SlashCommandCompleter._personality_completions("h", "h"))
- assert calls["n"] == 2, "config mtime change should re-parse once"
+ after = names()
+ assert "zzsecond" in after
+ assert "zzfirst" not in after
diff --git a/tests/hermes_cli/test_completion.py b/tests/hermes_cli/test_completion.py
index 19cf758fd26..a847e81f463 100644
--- a/tests/hermes_cli/test_completion.py
+++ b/tests/hermes_cli/test_completion.py
@@ -2,14 +2,10 @@
import argparse
import os
-import re
-import shutil
import subprocess
import tempfile
-import pytest
-
-from hermes_cli.completion import _walk, generate_bash, generate_zsh, generate_fish
+from hermes_cli.completion import _walk, generate_bash, generate_fish
# ---------------------------------------------------------------------------
@@ -98,54 +94,13 @@ class TestGenerateBash:
# ---------------------------------------------------------------------------
-# 3. Zsh output
-# ---------------------------------------------------------------------------
-
-class TestGenerateZsh:
-
-
- def test_preserves_valid_zsh_arguments_alias_syntax(self):
- out = generate_zsh(_make_parser())
- assert "'(-)'{-h,--help}'[Show help and exit]'" in out
- assert "'(-)'{-V,--version}'[Show version and exit]'" in out
- assert "'(-)'{-p,--profile}'[Profile name]:profile:_hermes_profiles'" in out
- assert "'(-h --help){-h,--help}[Show help and exit]'" not in out
- assert '"(-h --help)"{-h,--help}"[Show help and exit]"' not in out
-
- def test_valid_zsh_syntax(self):
- if not shutil.which("zsh"):
- pytest.skip("zsh not installed")
- out = generate_zsh(_make_parser())
- with tempfile.NamedTemporaryFile(mode="w", suffix=".zsh", delete=False) as f:
- f.write(out)
- path = f.name
- try:
- result = subprocess.run(["zsh", "-n", path], capture_output=True, text=True)
- assert result.returncode == 0, result.stderr
- finally:
- os.unlink(path)
-
-
-# ---------------------------------------------------------------------------
-# 4. Fish output
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# 5. Subcommand drift prevention
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# 6. Profile completion (regression prevention)
+# 3. Profile completion (regression prevention)
# ---------------------------------------------------------------------------
class TestProfileCompletion:
"""Ensure profile name completion is present in all shell outputs."""
-
-
def test_bash_profile_actions_complete_profile_names(self):
"""After 'hermes profile use', complete with profile names."""
out = generate_bash(_make_parser())
diff --git a/tests/hermes_cli/test_composer_placeholder.py b/tests/hermes_cli/test_composer_placeholder.py
deleted file mode 100644
index d2d62a3c8e5..00000000000
--- a/tests/hermes_cli/test_composer_placeholder.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""Test for rotating task-oriented composer placeholders (C-09)."""
-
-from hermes_cli.tips import COMPOSER_PLACEHOLDERS, get_random_composer_placeholder
-
-
-def test_composer_placeholders_nonempty():
- assert COMPOSER_PLACEHOLDERS
- assert all(isinstance(p, str) and p.strip() for p in COMPOSER_PLACEHOLDERS)
-
-
-def test_get_random_composer_placeholder_returns_a_member():
- for _ in range(20):
- assert get_random_composer_placeholder() in COMPOSER_PLACEHOLDERS
diff --git a/tests/hermes_cli/test_compress_flags.py b/tests/hermes_cli/test_compress_flags.py
index 5247160f83c..aacfe23a5dd 100644
--- a/tests/hermes_cli/test_compress_flags.py
+++ b/tests/hermes_cli/test_compress_flags.py
@@ -6,7 +6,7 @@ resolution in the command registry. The CLI and gateway surfaces both
route through these helpers, so the flag semantics are pinned here once.
"""
-from hermes_cli.commands import COMMANDS, resolve_command
+from hermes_cli.commands import resolve_command
from hermes_cli.partial_compress import (
DEFAULT_KEEP_LAST,
extract_compress_flags,
@@ -33,32 +33,15 @@ def test_compact_resolves_to_compress():
assert "compact" in cmd.aliases
-
-
-def test_compact_listed_in_flat_commands():
- assert "/compact" in COMMANDS
- assert "alias for /compress" in COMMANDS["/compact"]
-
-
-
-
# ── extract_compress_flags ────────────────────────────────────────────
-
-
-
-
def test_dry_run_is_preview():
for form in ("--dry-run", "--dryrun", "--DRY-RUN"):
_, preview, _ = extract_compress_flags(form)
assert preview is True, form
-
-
-
-
def test_flags_coexist_with_focus_topic():
rest, preview, _ = extract_compress_flags("database schema --dry-run")
assert rest == "database schema"
@@ -67,10 +50,6 @@ def test_flags_coexist_with_focus_topic():
assert partial is False and focus == "database schema"
-
-
-
-
# ── summarize_compress_preview ────────────────────────────────────────
@@ -81,10 +60,6 @@ def test_preview_full_compress_counts():
assert report["tail_count"] == 0
assert report["total"] == 10
assert report["partial"] is False
- joined = "\n".join(report["lines"])
- assert "no changes made" in joined.lower()
- assert "10 of 10" in joined
- assert "1,234" in joined
def test_preview_partial_boundary_counts():
@@ -94,12 +69,6 @@ def test_preview_partial_boundary_counts():
assert report["head_count"] == 6
assert report["tail_count"] == 4
assert report["partial"] is True
- joined = "\n".join(report["lines"])
- assert "last 2 exchange" in joined
-
-
-
-
def test_preview_is_side_effect_free():
diff --git a/tests/hermes_cli/test_compress_focus.py b/tests/hermes_cli/test_compress_focus.py
deleted file mode 100644
index 3f4883f79f3..00000000000
--- a/tests/hermes_cli/test_compress_focus.py
+++ /dev/null
@@ -1,118 +0,0 @@
-"""Tests for /compress <focus> — guided compression with focus topic.
-
-Inspired by Claude Code's /compact <focus> feature.
-"""
-
-from unittest.mock import MagicMock, patch
-
-from tests.hermes_cli.test_cli_init import _make_cli
-
-
-def _make_history() -> list[dict[str, str]]:
- return [
- {"role": "user", "content": "one"},
- {"role": "assistant", "content": "two"},
- {"role": "user", "content": "three"},
- {"role": "assistant", "content": "four"},
- ]
-
-
-def test_focus_topic_extracted_and_passed(capsys):
- """Focus topic is extracted from the command and passed to _compress_context."""
- shell = _make_cli()
- history = _make_history()
- compressed = [history[0], history[-1]]
- shell.conversation_history = history
- shell.agent = MagicMock()
- shell.agent.compression_enabled = True
- shell.agent._cached_system_prompt = ""
- shell.agent._compress_context.return_value = (compressed, "")
-
- def _estimate(messages):
- if messages is history:
- return 100
- return 50
-
- with patch("agent.model_metadata.estimate_messages_tokens_rough", side_effect=_estimate):
- shell._manual_compress("/compress database schema")
-
- output = capsys.readouterr().out
- assert 'focus: "database schema"' in output
-
- # Verify focus_topic was passed through
- shell.agent._compress_context.assert_called_once()
- call_kwargs = shell.agent._compress_context.call_args
- assert call_kwargs.kwargs.get("focus_topic") == "database schema"
-
-
-def test_no_focus_topic_when_bare_command(capsys):
- """When no focus topic is provided, None is passed."""
- shell = _make_cli()
- history = _make_history()
- shell.conversation_history = history
- shell.agent = MagicMock()
- shell.agent.compression_enabled = True
- shell.agent._cached_system_prompt = ""
- shell.agent._compress_context.return_value = (list(history), "")
-
- with patch("agent.model_metadata.estimate_messages_tokens_rough", return_value=100):
- shell._manual_compress("/compress")
-
- shell.agent._compress_context.assert_called_once()
- call_kwargs = shell.agent._compress_context.call_args
- assert call_kwargs.kwargs.get("focus_topic") is None
-
-
-def test_empty_focus_after_command_treated_as_none(capsys):
- """Trailing whitespace after /compress does not produce a focus topic."""
- shell = _make_cli()
- history = _make_history()
- shell.conversation_history = history
- shell.agent = MagicMock()
- shell.agent.compression_enabled = True
- shell.agent._cached_system_prompt = ""
- shell.agent._compress_context.return_value = (list(history), "")
-
- with patch("agent.model_metadata.estimate_messages_tokens_rough", return_value=100):
- shell._manual_compress("/compress ")
-
- shell.agent._compress_context.assert_called_once()
- call_kwargs = shell.agent._compress_context.call_args
- assert call_kwargs.kwargs.get("focus_topic") is None
-
-
-def test_focus_topic_printed_in_compression_banner(capsys):
- """The focus topic shows in the compression progress banner."""
- shell = _make_cli()
- history = _make_history()
- compressed = [history[0], history[-1]]
- shell.conversation_history = history
- shell.agent = MagicMock()
- shell.agent.compression_enabled = True
- shell.agent._cached_system_prompt = ""
- shell.agent._compress_context.return_value = (compressed, "")
-
- with patch("agent.model_metadata.estimate_messages_tokens_rough", return_value=100):
- shell._manual_compress("/compress API endpoints")
-
- output = capsys.readouterr().out
- assert 'focus: "API endpoints"' in output
-
-
-def test_no_focus_prints_standard_banner(capsys):
- """Without focus, the standard banner (no focus: line) is printed."""
- shell = _make_cli()
- history = _make_history()
- compressed = [history[0], history[-1]]
- shell.conversation_history = history
- shell.agent = MagicMock()
- shell.agent.compression_enabled = True
- shell.agent._cached_system_prompt = ""
- shell.agent._compress_context.return_value = (compressed, "")
-
- with patch("agent.model_metadata.estimate_messages_tokens_rough", return_value=100):
- shell._manual_compress("/compress")
-
- output = capsys.readouterr().out
- assert "focus:" not in output
- assert "Compressing" in output
diff --git a/tests/hermes_cli/test_compress_here.py b/tests/hermes_cli/test_compress_here.py
index febc7d4d1e9..afa8d37c053 100644
--- a/tests/hermes_cli/test_compress_here.py
+++ b/tests/hermes_cli/test_compress_here.py
@@ -29,28 +29,6 @@ def _wire_agent(shell, compressed_head):
shell.agent._compression_skipped_due_to_lock = False
-def test_compress_here_compresses_head_only(capsys):
- """/compress here 2 passes only the head to _compress_context."""
- shell = _make_cli()
- history = _make_history()
- shell.conversation_history = history
- # Pretend compression collapses the head into a single summary message.
- summary = [{"role": "user", "content": "[summary of earlier turns]"}]
- _wire_agent(shell, summary)
-
- with patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100):
- shell._manual_compress("/compress here 2")
-
- # _compress_context should have been called with the HEAD only
- # (everything before the last 2 user-starts = first 4 messages).
- shell.agent._compress_context.assert_called_once()
- call = shell.agent._compress_context.call_args
- passed_head = call.args[0]
- assert passed_head == history[:4]
- # focus_topic must be None in partial mode (modes are exclusive).
- assert call.kwargs.get("focus_topic") is None
-
-
def test_compress_here_reappends_verbatim_tail(capsys):
"""The most recent exchanges are preserved verbatim after the summary."""
shell = _make_cli()
@@ -64,57 +42,11 @@ def test_compress_here_reappends_verbatim_tail(capsys):
with patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100):
shell._manual_compress("/compress here 2")
+ # Only the head (everything before the last 2 user-starts) is summarized.
+ assert shell.agent._compress_context.call_args.args[0] == history[:4]
# Result = compressed head + verbatim tail (last 2 exchanges).
assert shell.conversation_history == summary + history[4:]
- # Tail boundary keeps role alternation valid (tail starts on user).
- assert history[4]["role"] == "user"
# No consecutive same-role user/assistant messages anywhere.
roles = [m["role"] for m in shell.conversation_history
if m["role"] in ("user", "assistant")]
assert all(roles[i] != roles[i + 1] for i in range(len(roles) - 1))
-
-
-def test_compress_here_banner_mentions_summarizing_up_to_here(capsys):
- shell = _make_cli()
- history = _make_history()
- shell.conversation_history = history
- _wire_agent(shell, [{"role": "user", "content": "[summary]"}])
-
- with patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100):
- shell._manual_compress("/compress here")
-
- out = capsys.readouterr().out
- assert "Summarizing up to here" in out
- assert "verbatim" in out
-
-
-def test_bare_compress_still_full(capsys):
- """/compress with no args compresses the whole history (full mode)."""
- shell = _make_cli()
- history = _make_history()
- shell.conversation_history = history
- _wire_agent(shell, list(history))
-
- with patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100):
- shell._manual_compress("/compress")
-
- call = shell.agent._compress_context.call_args
- # Full mode passes the entire history as the head.
- assert call.args[0] == history
- out = capsys.readouterr().out
- assert "Summarizing up to here" not in out
-
-
-def test_focus_still_works(capsys):
- """/compress <focus> keeps the existing focus behavior."""
- shell = _make_cli()
- history = _make_history()
- shell.conversation_history = history
- _wire_agent(shell, list(history))
-
- with patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100):
- shell._manual_compress("/compress database schema")
-
- call = shell.agent._compress_context.call_args
- assert call.args[0] == history
- assert call.kwargs.get("focus_topic") == "database schema"
diff --git a/tests/hermes_cli/test_compress_type_ahead.py b/tests/hermes_cli/test_compress_type_ahead.py
deleted file mode 100644
index 33fc502ead4..00000000000
--- a/tests/hermes_cli/test_compress_type_ahead.py
+++ /dev/null
@@ -1,149 +0,0 @@
-"""Type-ahead queue-drain proof for /compress (issue #61042, PR #68284).
-
-PR #68284 made the classic prompt_toolkit CLI keep the composer editable
-while ``/compress`` runs (``_busy_command(..., blocks_input=False)``), with
-the docstring claim that "the queued input is processed against the
-compacted history after the command completes."
-
-These tests pin that claim end-to-end for the classic CLI:
-
-1. ``test_type_ahead_queued_during_compress_becomes_next_prompt`` — runs
- ``_manual_compress`` on a worker thread (matching the real topology:
- slash commands execute on ``process_loop``, which is blocked inside
- ``process_command`` for the duration), submits a type-ahead payload into
- ``_pending_input`` mid-compression (what ``handle_enter``'s idle branch
- does — ``_agent_running`` is False while a slash command runs), and
- asserts that after compression commits the compacted history the queued
- text is still the next item ``process_loop`` will drain. Nothing inside
- the compression path may consume or drop it.
-
-2. ``test_handle_enter_never_gates_on_command_running`` — structural
- invariant: ``handle_enter`` must not consult ``_command_running`` /
- ``_command_blocks_input``. The composer's read-only state is enforced
- solely by the TextArea's ``read_only=Condition(_command_blocks_input)``;
- if a future edit added an early-return in ``handle_enter`` while a
- command runs, type-ahead submissions would be silently dropped and the
- drain contract above would break without any other test noticing.
-
-The Ink TUI (ui-tui) needs no equivalent fix: its ``/compress`` is an async
-``session.compress`` RPC and the composer is never made read-only while it
-runs; the gateway already resolves the concurrent-mutation race via the
-``history_version`` guard in ``_compress_session_history``.
-"""
-
-from __future__ import annotations
-
-import ast
-import queue as queue_mod
-import threading
-from pathlib import Path
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from tests.hermes_cli.test_cli_init import _make_cli
-
-
-def _make_history() -> list[dict[str, str]]:
- return [
- {"role": "user", "content": "one"},
- {"role": "assistant", "content": "two"},
- {"role": "user", "content": "three"},
- {"role": "assistant", "content": "four"},
- ]
-
-
-def test_type_ahead_queued_during_compress_becomes_next_prompt():
- """Text queued while /compress runs survives compaction and is the next prompt."""
- shell = _make_cli()
- history = _make_history()
- compressed = [
- {"role": "user", "content": "[summary]"},
- history[-1],
- ]
- shell.conversation_history = history
- shell.agent = MagicMock()
- shell.agent.compression_enabled = True
- shell.agent._cached_system_prompt = ""
- shell.agent.tools = None
- shell.agent.session_id = shell.session_id
-
- compress_started = threading.Event()
- release_compress = threading.Event()
- mid_compress = {}
-
- def _compress(*_args, **_kwargs):
- compress_started.set()
- # Hold the "compression in flight" window open until the test has
- # simulated the user's type-ahead submission.
- assert release_compress.wait(timeout=10), "test deadlock: never released"
- return (list(compressed), "")
-
- shell.agent._compress_context.side_effect = _compress
-
- with patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100):
- worker = threading.Thread(target=shell._manual_compress, daemon=True)
- worker.start()
- assert compress_started.wait(timeout=10), "compression never started"
-
- # Mid-compression: composer stays editable (spinner up, input open).
- mid_compress["running"] = shell._command_running
- mid_compress["blocks_input"] = shell._command_blocks_input
-
- # The user types a follow-up and presses Enter. handle_enter's normal
- # routing puts it on _pending_input (agent idle — slash commands run
- # on process_loop, not the agent). process_loop is blocked inside
- # process_command → _manual_compress, so the payload must sit queued.
- shell._pending_input.put("follow-up prompt drafted during compaction")
-
- release_compress.set()
- worker.join(timeout=10)
-
- assert not worker.is_alive(), "_manual_compress did not finish"
- assert mid_compress == {"running": True, "blocks_input": False}
-
- # Compaction committed the compressed transcript...
- assert shell.conversation_history == compressed
- # ...and busy state was fully unwound so the next turn renders normally.
- assert shell._command_running is False
- assert shell._command_blocks_input is False
-
- # The queued type-ahead is exactly the next item process_loop drains —
- # i.e. it becomes the next prompt, processed against the compacted
- # history. Compression must not consume, reorder, or drop it.
- assert (
- shell._pending_input.get_nowait()
- == "follow-up prompt drafted during compaction"
- )
- with pytest.raises(queue_mod.Empty):
- shell._pending_input.get_nowait()
-
-
-def test_handle_enter_never_gates_on_command_running():
- """handle_enter must not consult the busy-command flags (drop-proof routing).
-
- Enter-key routing while a slash command runs must keep flowing into
- ``_pending_input``; read-only enforcement belongs exclusively to the
- TextArea's ``read_only=Condition(...)``. A ``_command_running`` /
- ``_command_blocks_input`` check inside ``handle_enter`` would let a
- future edit silently drop type-ahead submissions during /compress.
- """
- cli_path = Path(__file__).resolve().parents[2] / "hermes_cli" / "cli_tui_mixin.py"
- tree = ast.parse(cli_path.read_text(encoding="utf-8"))
-
- handlers = ("_tui_handle_enter", "_tui_enter_inline_command", "_tui_enter_overlay",
- "_tui_enter_clarify_freetext", "_tui_enter_clarify_choice", "_tui_enter_while_busy")
- targets = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name in handlers]
- assert {n.name for n in targets} == set(handlers), "Enter handlers not found in cli_tui_mixin.py"
-
- offenders = [
- node.attr
- for target in targets
- for node in ast.walk(target)
- if isinstance(node, ast.Attribute)
- and node.attr in {"_command_running", "_command_blocks_input"}
- ]
- assert not offenders, (
- "handle_enter references busy-command state — Enter routing while a "
- f"slash command runs risks dropping type-ahead input: {offenders}"
- )
diff --git a/tests/hermes_cli/test_computer_use_cli.py b/tests/hermes_cli/test_computer_use_cli.py
index ba85b452992..8dee9b37bc5 100644
--- a/tests/hermes_cli/test_computer_use_cli.py
+++ b/tests/hermes_cli/test_computer_use_cli.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import subprocess
import sys
from importlib import import_module
from unittest.mock import Mock
@@ -12,15 +11,6 @@ import pytest
from tools.computer_use import cua_backend_driver
-def _run(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "hermes_cli.main", "computer-use", *args],
- capture_output=True,
- text=True,
- timeout=30,
- )
-
-
def _invoke(monkeypatch: pytest.MonkeyPatch, *args: str) -> int:
"""Run the in-process CLI and normalize its process-style exit status."""
cli_main = import_module("hermes_cli.main")
@@ -33,23 +23,6 @@ def _invoke(monkeypatch: pytest.MonkeyPatch, *args: str) -> int:
return 0
-def test_computer_use_help_omits_browser_approve() -> None:
- result = _run("--help")
-
- assert result.returncode == 0
- assert "browser-approve" not in result.stdout
- assert "doctor" in result.stdout
- assert "permissions" in result.stdout
-
-
-def test_computer_use_rejects_removed_browser_approve_command() -> None:
- result = _run("browser-approve", "--pid", "123")
-
- assert result.returncode == 2
- assert "'browser-approve' is not a `hermes computer-use` command" in result.stderr
- assert "choose from" not in result.stderr
-
-
def test_computer_use_status_returns_zero_for_compatible_driver(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.py
index 78cc50f985c..e29b63521e4 100644
--- a/tests/hermes_cli/test_config.py
+++ b/tests/hermes_cli/test_config.py
@@ -16,7 +16,6 @@ from hermes_cli.config import (
get_hermes_home,
ensure_hermes_home,
get_compatible_custom_providers,
- _explicit_config_paths,
_normalize_max_turns_config,
is_provider_enabled,
load_config,
@@ -30,7 +29,6 @@ from hermes_cli.config import (
sanitize_env_file,
set_config_value,
unset_config_value,
- write_platform_config_field,
_sanitize_env_lines,
)
@@ -672,34 +670,11 @@ class TestSanitizeEnvLines:
class TestOptionalEnvVarsRegistry:
"""Verify that key env vars are registered in OPTIONAL_ENV_VARS."""
- def test_keenable_api_key_registered(self):
- """KEENABLE_API_KEY is listed in OPTIONAL_ENV_VARS."""
- from hermes_cli.config import OPTIONAL_ENV_VARS
- assert "KEENABLE_API_KEY" in OPTIONAL_ENV_VARS
- def test_keenable_api_key_has_url(self):
- """KEENABLE_API_KEY has a URL."""
- from hermes_cli.config import OPTIONAL_ENV_VARS
- assert OPTIONAL_ENV_VARS["KEENABLE_API_KEY"]["url"] == "https://keenable.ai"
- def test_tavily_api_key_registered(self):
- """TAVILY_API_KEY is listed in OPTIONAL_ENV_VARS."""
- from hermes_cli.config import OPTIONAL_ENV_VARS
- assert "TAVILY_API_KEY" in OPTIONAL_ENV_VARS
- def test_tavily_api_key_has_url(self):
- """TAVILY_API_KEY has a URL."""
- from hermes_cli.config import OPTIONAL_ENV_VARS
- assert OPTIONAL_ENV_VARS["TAVILY_API_KEY"]["url"] == "https://app.tavily.com/home"
- def test_tavily_in_env_vars_by_version(self):
- """TAVILY_API_KEY is listed in ENV_VARS_BY_VERSION."""
- from hermes_cli.config import ENV_VARS_BY_VERSION
- all_vars = []
- for vars_list in ENV_VARS_BY_VERSION.values():
- all_vars.extend(vars_list)
- assert "TAVILY_API_KEY" in all_vars
def test_max_iterations_not_offered_as_env_var(self):
"""HERMES_MAX_ITERATIONS must NOT be in OPTIONAL_ENV_VARS (issue #17534).
@@ -714,38 +689,6 @@ class TestOptionalEnvVarsRegistry:
assert "HERMES_MAX_ITERATIONS" not in OPTIONAL_ENV_VARS
-class TestMemoryProviderEnvVarsRegistry:
- """Every memory provider that reads an API key from the environment must
- have that key catalogued in OPTIONAL_ENV_VARS so the dashboard Keys page
- and `hermes setup` surface it (previously only Honcho was listed, leaving
- Hindsight/Supermemory/Mem0/RetainDB/ByteRover/OpenViking invisible).
-
- This is a behavior contract, not a snapshot: it asserts each provider's
- primary credential key is present, tool-categorised, and password-masked —
- not a frozen count of entries.
- """
-
- # provider primary-credential env key -> the tool-call name it powers.
- MEMORY_PROVIDER_KEYS = {
- "HONCHO_API_KEY": "honcho_context",
- "HINDSIGHT_API_KEY": "hindsight_recall",
- "SUPERMEMORY_API_KEY": "supermemory_search",
- "MEM0_API_KEY": "mem0_search",
- "RETAINDB_API_KEY": "retaindb_search",
- "BRV_API_KEY": "brv_query",
- "OPENVIKING_API_KEY": "viking_search",
- }
-
- def test_memory_provider_keys_are_catalogued(self):
- from hermes_cli.config import OPTIONAL_ENV_VARS
- missing = [k for k in self.MEMORY_PROVIDER_KEYS if k not in OPTIONAL_ENV_VARS]
- assert not missing, f"memory provider keys missing from OPTIONAL_ENV_VARS: {missing}"
-
-
- def test_memory_provider_keys_advertise_their_tool(self):
- from hermes_cli.config import OPTIONAL_ENV_VARS
- for key, tool in self.MEMORY_PROVIDER_KEYS.items():
- assert tool in OPTIONAL_ENV_VARS[key].get("tools", []), key
class TestConfigMigrationSecretPrompts:
@@ -1243,8 +1186,6 @@ class TestCustomProviderCompatibility:
class TestInterimAssistantMessageConfig:
"""Test the explicit gateway interim-message config gate."""
- def test_default_config_enables_interim_assistant_messages(self):
- assert DEFAULT_CONFIG["display"]["interim_assistant_messages"] is True
def test_migrate_to_v15_supplies_interim_message_gate_at_read_time(
self, tmp_path, capsys
@@ -1276,15 +1217,6 @@ class TestInterimAssistantMessageConfig:
assert "Added display.interim_assistant_messages" not in capsys.readouterr().out
-class TestCliRefreshIntervalConfig:
- """Test the CLI refresh_interval config default (#45592 / #48309)."""
-
- def test_default_config_enables_cli_refresh_interval(self):
- """cli_refresh_interval defaults to 1.0 so the idle status-bar
- clock keeps ticking and the bottom chrome stays alive during
- idle (#45592). Users on emulators where the periodic redraw
- fights auto-scroll can set it to 0 (#48309)."""
- assert DEFAULT_CONFIG["display"]["cli_refresh_interval"] == 1.0
class TestDiscordChannelPromptsConfig:
@@ -1667,7 +1599,7 @@ feishu:
def test_persist_migration_writes_full_read_raw_config(self, tmp_path):
- from hermes_cli.config import _persist_migration, read_raw_config
+ from hermes_cli.config import _persist_migration
body = """_config_version: 30
model:
@@ -1791,8 +1723,6 @@ class TestBackgroundNotificationsConciseMigration:
# Unset users inherit the new default at read time; no write needed.
assert "display" not in raw or "background_process_notifications" not in raw.get("display", {})
- def test_default_config_is_concise(self):
- assert DEFAULT_CONFIG["display"]["background_process_notifications"] == "concise"
class TestConfigNormalizationDoesNotOverwriteUserValues:
@@ -1834,9 +1764,6 @@ class TestCodexAppServerAutoConfig:
def _write(self, tmp_path, body):
(tmp_path / "config.yaml").write_text(body, encoding="utf-8")
- def test_default_config_has_native_mode(self):
- assert DEFAULT_CONFIG["compression"]["codex_app_server_auto"] == "native"
- assert DEFAULT_CONFIG["compression"]["codex_gpt55_autoraise"] is True
def test_preserves_existing_codex_app_server_auto_value(self, tmp_path):
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
@@ -1989,8 +1916,6 @@ def test_gateway_multiplex_keys_are_recognized_config_keys():
key' although gateway/config.py reads it; the key (and profile_routes) live in DEFAULT_CONFIG."""
from hermes_cli.config import _validate_config_key
from hermes_cli.config_defaults import DEFAULT_CONFIG
- assert DEFAULT_CONFIG["gateway"]["multiplex_profiles"] is True
- assert DEFAULT_CONFIG["gateway"]["auto_multiplex_migration"] is True
assert "auto_migrate" not in DEFAULT_CONFIG["gateway"]
assert _validate_config_key("gateway.multiplex_profiles") == (True, None)
assert _validate_config_key("gateway.profile_routes") == (True, None)
@@ -2021,10 +1946,6 @@ def test_lsp_root_policy_keys_are_recognized_and_off_by_default():
"""``lsp.warmup_timeout`` / ``broken_retry_seconds`` / ``exclude_roots`` (#116446) must be settable via
``hermes config set`` and must default to today's behaviour (no grace, lifetime broken set, no exclusion)."""
from hermes_cli.config import _validate_config_key
- from hermes_cli.config_defaults import DEFAULT_CONFIG
- assert DEFAULT_CONFIG["lsp"]["warmup_timeout"] == 0.0
- assert DEFAULT_CONFIG["lsp"]["broken_retry_seconds"] == 0.0
- assert DEFAULT_CONFIG["lsp"]["exclude_roots"] == []
for key in ("lsp.warmup_timeout", "lsp.broken_retry_seconds", "lsp.exclude_roots"):
assert _validate_config_key(key) == (True, None)
diff --git a/tests/hermes_cli/test_config_dotted_key_names.py b/tests/hermes_cli/test_config_dotted_key_names.py
index 968e92147b9..da3fb91de14 100644
--- a/tests/hermes_cli/test_config_dotted_key_names.py
+++ b/tests/hermes_cli/test_config_dotted_key_names.py
@@ -29,8 +29,6 @@ import yaml
from hermes_cli.config import (
_MISSING,
_get_nested,
- _greedy_literal_match,
- _phantom_sibling,
_set_nested,
_unset_nested,
config_command,
@@ -74,22 +72,6 @@ PROVIDER_CONFIG = {
# Unit level: helpers
# ---------------------------------------------------------------------------
-class TestGreedyLiteralMatch:
- def test_longest_match_wins(self):
- d = {"grok-4.6": 1, "grok-4": 2}
- assert _greedy_literal_match(d, ["grok-4", "6"]) == ("grok-4.6", 2)
-
- def test_single_segment_fallback(self):
- assert _greedy_literal_match({"a": 1}, ["a", "b"]) == ("a", 1)
-
- def test_no_match(self):
- assert _greedy_literal_match({"a": 1}, ["x", "y"]) is None
-
- def test_phantom_sibling_detection(self):
- assert _phantom_sibling({"grok-4.6": {}}, "grok-4") == "grok-4.6"
- assert _phantom_sibling({"grok-4.6": {}}, "other") is None
- assert _phantom_sibling({"plain": {}}, "plain") is None
-
# ---------------------------------------------------------------------------
# #84064 — provider model keys with dots: set / get / unset all address the
@@ -342,18 +324,3 @@ class TestBackwardCompatibility:
cfg = {"custom_providers": [{"name": "p1"}]}
_set_nested(cfg, "custom_providers.0.name", "p2")
assert cfg["custom_providers"][0]["name"] == "p2"
-
- def test_deep_creation_without_siblings_unchanged(self, _isolated_hermes_home):
- set_config_value("agent.max_turns", "50")
- saved = _read_config(_isolated_hermes_home)
- assert saved["agent"]["max_turns"] == 50
-
- def test_greedy_never_beats_exact_nested_structure(self):
- """A literal dotted key never shadows the plain-split path when the
- plain path ALSO fully exists — longest literal match only consumes
- segments when the literal dotted key is present; nested dicts still
- resolve segment-by-segment."""
- cfg = {"a": {"b": {"c": 1}}}
- assert _get_nested(cfg, "a.b.c") == 1
- _set_nested(cfg, "a.b.c", 2)
- assert cfg == {"a": {"b": {"c": 2}}}
diff --git a/tests/hermes_cli/test_config_effective.py b/tests/hermes_cli/test_config_effective.py
index 6ddb4fc0b52..f5218e16f9f 100644
--- a/tests/hermes_cli/test_config_effective.py
+++ b/tests/hermes_cli/test_config_effective.py
@@ -59,7 +59,6 @@ def test_effective_is_user_plus_managed_plus_env_with_no_defaults(homes):
root ``provider`` migrated under ``model``, and no DEFAULT_CONFIG key introduced (a missing
key stays missing). Per-message gateway reads (and the system prompt built from them) are
pinned by this shape, not by re-running the implementation's primitives."""
- from hermes_cli.config import DEFAULT_CONFIG
from hermes_cli.config_effective import load_user_config_effective
home, managed = homes
@@ -77,7 +76,6 @@ def test_effective_is_user_plus_managed_plus_env_with_no_defaults(homes):
},
"display": {"skin": "managed-skin"},
}
- assert "agent" in DEFAULT_CONFIG # would be present if defaults had been merged
def test_broken_yaml_serves_last_good_and_fail_closed_raises(homes):
diff --git a/tests/hermes_cli/test_config_env_expansion.py b/tests/hermes_cli/test_config_env_expansion.py
index 6571015245a..e7af43c8658 100644
--- a/tests/hermes_cli/test_config_env_expansion.py
+++ b/tests/hermes_cli/test_config_env_expansion.py
@@ -1,16 +1,9 @@
"""Tests for ${ENV_VAR} substitution in config.yaml values."""
-import pytest
from hermes_cli.config import _expand_env_vars, load_config
class TestExpandEnvVars:
- def test_simple_substitution(self):
- with pytest.MonkeyPatch().context() as mp:
- mp.setenv("MY_KEY", "secret123")
- assert _expand_env_vars("${MY_KEY}") == "secret123"
-
-
def test_non_string_values_untouched(self):
@@ -20,8 +13,6 @@ class TestExpandEnvVars:
assert _expand_env_vars(None) is None
-
-
class TestLoadConfigExpansion:
def test_load_config_expands_env_vars(self, tmp_path, monkeypatch):
config_yaml = (
diff --git a/tests/hermes_cli/test_config_guard_surfaces.py b/tests/hermes_cli/test_config_guard_surfaces.py
index bc596b7f62c..c07e36d77de 100644
--- a/tests/hermes_cli/test_config_guard_surfaces.py
+++ b/tests/hermes_cli/test_config_guard_surfaces.py
@@ -75,20 +75,6 @@ class TestCronRunJobGuard:
assert "config.yaml" in error
assert final_response == ""
- def test_run_job_escape_hatch(self, monkeypatch, tmp_path):
- from cron.scheduler import run_job
-
- _write_corrupt_config(tmp_path)
- monkeypatch.setenv("HERMES_IGNORE_USER_CONFIG", "1")
-
- # With the escape hatch active the guard must not trip. The job then
- # proceeds into normal execution; a missing provider/model in the
- # empty temp HERMES_HOME may fail later, but never with the guard's
- # refusal message.
- success, output_doc, final_response, error = run_job(
- self._job(no_agent=True, script="true", deliver="none")
- )
- assert "Hermes stopped because your settings file" not in (error or "")
def test_run_job_no_agent_exempt(self, tmp_path):
from cron.scheduler import run_job
@@ -124,32 +110,3 @@ class TestServeGuard:
assert exc_info.value.code == 2
assert "Hermes stopped because your settings file" in capsys.readouterr().err
- def test_serve_escape_hatch_passes_guard(self, tmp_path, monkeypatch):
- """--ignore-user-config lets serve get past the corrupt-config guard."""
- from argparse import Namespace
-
- from hermes_cli import main as main_mod
-
- _write_corrupt_config(tmp_path)
- args = Namespace(
- headless_backend=True,
- ignore_user_config=True,
- ssh_session_token_file=None,
- ssh_owner_nonce=None,
- status=False,
- stop=False,
- )
-
- # Stop execution right after the guard: the next thing cmd_dashboard
- # touches on the headless path is the nonce regex via `re`.
- sentinel = RuntimeError("passed-guard")
-
- class _ReStop:
- def fullmatch(self, *a, **k):
- raise sentinel
-
- monkeypatch.setattr(main_mod, "re", _ReStop())
- args.ssh_owner_nonce = "0123456789abcdef"
-
- with pytest.raises(RuntimeError, match="passed-guard"):
- main_mod.cmd_dashboard(args)
diff --git a/tests/hermes_cli/test_config_lkg_backup.py b/tests/hermes_cli/test_config_lkg_backup.py
index 732e7e5c16f..34dfdd52f2d 100644
--- a/tests/hermes_cli/test_config_lkg_backup.py
+++ b/tests/hermes_cli/test_config_lkg_backup.py
@@ -39,12 +39,11 @@ def test_fresh_process_recovers_last_good_config_and_leaves_broken_file_alone(tm
assert first["approvals"]["deny"] == ["curl*evil*"]
config_path.write_text(BROKEN, encoding="utf-8")
- recovered, stderr = _fresh_load(tmp_path)
+ recovered, _ = _fresh_load(tmp_path)
assert recovered["approvals"]["deny"] == ["curl*evil*"]
assert recovered["model"]["default"] == "test/secure"
assert recovered["custom_providers"][0]["api_key"] == "expanded-secret"
- assert "last good settings" in stderr
assert config_path.read_text(encoding="utf-8") == BROKEN
diff --git a/tests/hermes_cli/test_config_platform_env_routing.py b/tests/hermes_cli/test_config_platform_env_routing.py
index 59705e7bdd4..744b02dca9b 100644
--- a/tests/hermes_cli/test_config_platform_env_routing.py
+++ b/tests/hermes_cli/test_config_platform_env_routing.py
@@ -76,7 +76,7 @@ def test_unregistered_upper_snake_name_routes_to_env_by_shape(tmp_path, monkeypa
cfg.set_config_value("TELEGRAM_GROUP_ALLOWED_USERS", "222,333")
cfg.set_config_value("HERMES_TIMEZONE", "Europe/Berlin")
cfg.set_config_value("my_custom_flag", "hello")
- out = capsys.readouterr().out
+ capsys.readouterr()
env_text = (tmp_path / ".env").read_text(encoding="utf-8")
assert "TELEGRAM_GROUP_ALLOWED_USERS=222,333" in env_text and "HERMES_TIMEZONE=Europe/Berlin" in env_text
@@ -106,7 +106,5 @@ def test_env_writer_denylist_guards_upper_snake_names_and_unknown_names_get_a_no
assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {"model": {"default": "test/model"}}
cfg.set_config_value("SOME_PLUGIN_ONLY_KNOB", "xyz")
- out = capsys.readouterr().out
- assert "✓ Set SOME_PLUGIN_ONLY_KNOB in" in out
assert "SOME_PLUGIN_ONLY_KNOB=xyz" in (tmp_path / ".env").read_text(encoding="utf-8")
assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {"model": {"default": "test/model"}}
diff --git a/tests/hermes_cli/test_config_read_guard.py b/tests/hermes_cli/test_config_read_guard.py
deleted file mode 100644
index d47ca1068ec..00000000000
--- a/tests/hermes_cli/test_config_read_guard.py
+++ /dev/null
@@ -1,132 +0,0 @@
-"""Lint guard: no new raw yaml.safe_load(config.yaml) reads outside owner modules.
-
-The drift class this kills: scattered ``yaml.safe_load`` reads of the user's
-``config.yaml`` silently miss the managed-scope overlay, ``${ENV_VAR}``
-expansion, profile-aware pathing, and root-model normalization. Each new
-config feature has historically required an N-site sweep (incident chain:
-9cbcc0c9c8 → 732293cf87 → b0e47a98f9 → 1928aa0443).
-
-Canonical owners:
-
- * ``hermes_cli/config.py`` — ``load_config()`` / ``load_config_readonly()``
- (merged + managed + env-expanded), ``read_raw_config()`` and
- ``read_user_config_raw()`` (the ONLY legal raw primitives: write-back
- round-trips + raw-file diagnostics).
- * ``gateway/config.py`` — the gateway's ``load_gateway_config`` owner.
- * ``gateway/run.py`` — ``_load_gateway_config()``'s monkeypatched-home
- fallback path (delegates to ``read_raw_config`` when paths agree).
-
-Everything else must import one of those. If this test fails on your new
-code, use ``load_config()``/``load_config_readonly()`` for behavioral reads,
-or ``read_user_config_raw()`` for write-back round-trips — do not add your
-file to the allowlist without a reason of the same class.
-"""
-
-from __future__ import annotations
-
-import os
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent
-
-# Files where a yaml.safe_load near a config.yaml reference is legal.
-# Keep this list SHORT and justified:
-ALLOWLIST = {
- # Canonical loader owners.
- "hermes_cli/config.py",
- "gateway/config.py",
- # load_gateway_config()'s config.yaml phase lives here (extracted from
- # gateway/config.py); same owner, same managed-overlay contract.
- "gateway/config_loader.py",
- # _load_gateway_config()'s fallback path for tests that monkeypatch
- # gateway.run._hermes_home (delegates to read_raw_config otherwise).
- "gateway/run.py",
- # Reads the MANAGED-scope config.yaml (/etc/hermes/...), not the user's —
- # it IS the overlay source; the canonical loaders call into it.
- "hermes_cli/managed_scope.py",
- # Parse-health probe: intentionally answers "does the raw file parse?".
- "gateway/readiness.py",
-}
-
-# Directories that never count (tests may build fixture configs freely).
-EXCLUDED_DIR_PARTS = {
- "tests", ".venv", ".git", ".worktrees", "node_modules", "website",
- "docs", "scripts", "examples", "apps",
- # Compiled bytecode is not source. Sibling test processes also create
- # and delete these directories while this scan walks the tree.
- "__pycache__",
-}
-
-# A safe_load within this many lines of a config.yaml reference is treated
-# as a raw user-config read.
-PROXIMITY = 6
-
-SAFE_LOAD_RE = re.compile(r"\bsafe_load\s*\(")
-CONFIG_YAML_RE = re.compile(r"""["']config\.yaml["']""")
-
-
-def _iter_source_files():
- # This uses os.walk with a pruned dirnames, and not rglob. rglob descends
- # into every directory and filters after that, so it calls scandir() on
- # __pycache__ trees that this guard never inspects. Sibling test processes
- # create and delete those entries during the run.
- #
- # A directory that disappears in the middle of a walk raises
- # FileNotFoundError out of rglob. The test then fails for a reason that it
- # does not assert.
- #
- # The prune skips those trees. The onerror callback ignores a directory
- # that disappears anyway.
- for dirpath, dirnames, filenames in os.walk(REPO_ROOT, onerror=lambda _e: None):
- dirnames[:] = [d for d in dirnames if d not in EXCLUDED_DIR_PARTS]
- for name in filenames:
- if not name.endswith(".py"):
- continue
- path = Path(dirpath) / name
- rel = path.relative_to(REPO_ROOT)
- if any(part in EXCLUDED_DIR_PARTS for part in rel.parts):
- continue
- yield rel, path
-
-
-def test_no_raw_config_yaml_reads_outside_owner_modules():
- offenders: list[str] = []
- for rel, path in _iter_source_files():
- rel_str = str(rel).replace("\\", "/")
- if rel_str in ALLOWLIST:
- continue
- try:
- lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
- except OSError:
- continue
- cfg_lines = [i for i, ln in enumerate(lines) if CONFIG_YAML_RE.search(ln)]
- if not cfg_lines:
- continue
- for i, ln in enumerate(lines):
- if not SAFE_LOAD_RE.search(ln):
- continue
- # Comment/docstring mentions don't count.
- stripped = ln.strip()
- if stripped.startswith("#"):
- continue
- if any(abs(i - j) <= PROXIMITY for j in cfg_lines):
- offenders.append(f"{rel_str}:{i + 1}: {stripped}")
-
- assert not offenders, (
- "Raw yaml.safe_load of config.yaml outside allowlisted owner modules.\n"
- "Behavioral reads must use hermes_cli.config.load_config()/"
- "load_config_readonly() (or gateway _load_gateway_config); write-back "
- "round-trips and raw-file diagnostics must use "
- "hermes_cli.config.read_user_config_raw().\nOffenders:\n "
- + "\n ".join(offenders)
- )
-
-
-def test_read_user_config_raw_exists_and_documented():
- """The shared raw primitive must exist and carry its legality docstring."""
- from hermes_cli.config import read_user_config_raw
-
- doc = read_user_config_raw.__doc__ or ""
- assert "ONLY legal for write-back round-trips and raw-file diagnostics" in doc
- assert "load_config()" in doc
diff --git a/tests/hermes_cli/test_config_rmw_lock.py b/tests/hermes_cli/test_config_rmw_lock.py
index ede2b1b6b6c..bd2cb19ff4e 100644
--- a/tests/hermes_cli/test_config_rmw_lock.py
+++ b/tests/hermes_cli/test_config_rmw_lock.py
@@ -15,7 +15,6 @@ Both tests force exactly that interleaving and assert both writes land.
from __future__ import annotations
import threading
-import time
import pytest
import yaml
@@ -38,7 +37,7 @@ def client(monkeypatch, _isolate_hermes_home):
return client
-def _race_second_writer_into_first_writers_save(monkeypatch, first, second, timeout: float = 5.0):
+def _race_second_writer_into_first_writers_save(monkeypatch, first, second, timeout: float = 1.5):
"""Deterministic lost-write interleaving: ``first`` runs until it reaches ``save_config``,
then ``second`` is started and ``first`` waits (up to ``timeout``) for ``second`` to
``load_config`` before saving. Unlocked, ``second`` loads the stale document and its save
diff --git a/tests/hermes_cli/test_config_set_platforms_redirect.py b/tests/hermes_cli/test_config_set_platforms_redirect.py
index 803a70e58ff..718d2d0ca0d 100644
--- a/tests/hermes_cli/test_config_set_platforms_redirect.py
+++ b/tests/hermes_cli/test_config_set_platforms_redirect.py
@@ -62,19 +62,7 @@ class TestPerPlatformDisplayRedirect:
# Connection key untouched
assert result["platforms"]["telegram"]["token"] == "secret-bot-token"
- def test_show_reasoning_redirects(self, hermes_home, monkeypatch):
- _set(monkeypatch, hermes_home, "platforms.telegram.show_reasoning", "false")
- result = yaml.safe_load((hermes_home / "config.yaml").read_text())
- assert result["display"]["platforms"]["telegram"]["show_reasoning"] is False
-
- def test_tool_progress_redirects(self, hermes_home, monkeypatch):
- # ``off`` is coerced to False by the bool-aware coercion in
- # set_config_value; gateway/display_config._normalise turns False back
- # into the canonical "off" string at read time, so the persisted value
- # is the bool.
- _set(monkeypatch, hermes_home, "platforms.discord.tool_progress", "off")
- result = yaml.safe_load((hermes_home / "config.yaml").read_text())
- assert result["display"]["platforms"]["discord"]["tool_progress"] is False
+
def test_connection_key_not_redirected(self, hermes_home, monkeypatch):
"""A real connection key (token) stays in top-level platforms.<name>."""
@@ -132,11 +120,6 @@ class TestRedirectSiblingSurfaces:
unset_config_value("platforms.telegram.streaming")
assert exc.value.code == 1
- def test_set_prints_redirect_note(self, hermes_home, monkeypatch, capsys):
- _set(monkeypatch, hermes_home, "platforms.telegram.streaming", "false")
- out = capsys.readouterr().out
- assert "saved as display.platforms.telegram.streaming" in out
- assert "Set display.platforms.telegram.streaming = False" in out
def test_redirect_helper_only_touches_known_display_keys(self):
from gateway.display_config import OVERRIDEABLE_KEYS
diff --git a/tests/hermes_cli/test_config_validation.py b/tests/hermes_cli/test_config_validation.py
index cabf72cd8d6..9721afc153c 100644
--- a/tests/hermes_cli/test_config_validation.py
+++ b/tests/hermes_cli/test_config_validation.py
@@ -4,11 +4,7 @@
import pytest
from hermes_cli.config import (
- DEFAULT_CONFIG,
- _EXTRA_KNOWN_ROOT_KEYS,
- _KNOWN_ROOT_KEYS,
validate_config_structure,
- ConfigIssue,
)
@@ -86,24 +82,9 @@ class TestMissingModelSection:
assert not any("no 'model' section" in i.message for i in issues)
-class TestConfigIssueDataclass:
- """ConfigIssue should be a proper dataclass."""
-
- def test_fields(self):
- issue = ConfigIssue(severity="error", message="test msg", hint="test hint")
- assert issue.severity == "error"
- assert issue.message == "test msg"
- assert issue.hint == "test hint"
-
- def test_equality(self):
- a = ConfigIssue("error", "msg", "hint")
- b = ConfigIssue("error", "msg", "hint")
- assert a == b
class TestVoiceSubmitModeValidation:
- def test_default_is_direct(self):
- assert DEFAULT_CONFIG["voice"]["submit_mode"] == "direct"
def test_direct_and_draft_are_valid(self):
for mode in ("direct", "draft"):
@@ -174,11 +155,6 @@ class TestUnknownTopLevelKeys:
"""
- def test_known_root_keys_derived_from_default_config(self):
- """_KNOWN_ROOT_KEYS must be DEFAULT_CONFIG.keys() plus extras — single source of truth."""
- assert set(DEFAULT_CONFIG.keys()).issubset(_KNOWN_ROOT_KEYS)
- assert _EXTRA_KNOWN_ROOT_KEYS.issubset(_KNOWN_ROOT_KEYS)
- assert _KNOWN_ROOT_KEYS == frozenset(DEFAULT_CONFIG.keys()) | _EXTRA_KNOWN_ROOT_KEYS
def test_provider_like_unknown_root_keeps_misplaced_message(self):
"""Preserve existing base_url/api_key root-level guidance."""
diff --git a/tests/hermes_cli/test_config_yaml_comment_preservation.py b/tests/hermes_cli/test_config_yaml_comment_preservation.py
index fa27441423f..e4d65aadc55 100644
--- a/tests/hermes_cli/test_config_yaml_comment_preservation.py
+++ b/tests/hermes_cli/test_config_yaml_comment_preservation.py
@@ -7,7 +7,6 @@ landed. A new writer that reaches for PyYAML instead of ``atomic_config_write``
"""
import os
-import subprocess
import sys
from pathlib import Path
from unittest.mock import patch
@@ -127,11 +126,6 @@ class TestEveryWriterPreservesComments:
class TestStaticGuard:
- def test_repo_has_no_stray_config_writers(self):
- proc = subprocess.run(
- [sys.executable, str(REPO / "scripts" / "check_config_yaml_writers.py")],
- capture_output=True, text=True, cwd=REPO, timeout=120)
- assert proc.returncode == 0, proc.stderr
def test_guard_flags_pyyaml_dump_of_config_path(self, tmp_path):
sys.path.insert(0, str(REPO / "scripts"))
diff --git a/tests/hermes_cli/test_console_engine.py b/tests/hermes_cli/test_console_engine.py
index f33210b8ea8..0aefdb57e57 100644
--- a/tests/hermes_cli/test_console_engine.py
+++ b/tests/hermes_cli/test_console_engine.py
@@ -2,245 +2,12 @@ from __future__ import annotations
import io
import sys
-from pathlib import Path
import pytest
from hermes_cli.console_engine import HermesConsoleEngine, run_console_repl
-EXPECTED_CONSOLE_COMMANDS = {
- ("status",),
- ("doctor",),
- ("logs",),
- ("version",),
- ("dump",),
- ("debug", "share"),
- ("debug", "delete"),
- ("prompt-size",),
- ("insights",),
- ("security", "audit"),
- ("portal", "info"),
- ("portal", "tools"),
- ("backup",),
- ("import",),
- ("send",),
- ("config", "show"),
- ("config", "path"),
- ("config", "env-path"),
- ("config", "check"),
- ("config", "migrate"),
- ("config", "set"),
- ("sessions", "list"),
- ("sessions", "stats"),
- ("sessions", "export"),
- ("sessions", "rename"),
- ("sessions", "optimize"),
- ("sessions", "repair"),
- ("cron", "list"),
- ("cron", "status"),
- ("cron", "create"),
- ("cron", "edit"),
- ("cron", "pause"),
- ("cron", "resume"),
- ("cron", "run"),
- ("cron", "remove"),
- ("cron", "tick"),
- ("profile",),
- ("profile", "list"),
- ("profile", "show"),
- ("profile", "info"),
- ("profile", "create"),
- ("profile", "use"),
- ("profile", "describe"),
- ("profile", "rename"),
- ("profile", "delete"),
- ("profile", "export"),
- ("profile", "import"),
- ("profile", "install"),
- ("profile", "update"),
- ("tools", "list"),
- ("tools", "enable"),
- ("tools", "disable"),
- ("tools", "post-setup"),
- ("plugins", "list"),
- ("plugins", "enable"),
- ("plugins", "disable"),
- ("plugins", "install"),
- ("plugins", "update"),
- ("plugins", "remove"),
- ("skills", "browse"),
- ("skills", "search"),
- ("skills", "inspect"),
- ("skills", "list"),
- ("skills", "check"),
- ("skills", "list-modified"),
- ("skills", "diff"),
- ("skills", "install"),
- ("skills", "update"),
- ("skills", "audit"),
- ("skills", "uninstall"),
- ("skills", "reset"),
- ("skills", "opt-in"),
- ("skills", "opt-out"),
- ("skills", "repair-official"),
- ("skills", "snapshot", "export"),
- ("skills", "snapshot", "import"),
- ("skills", "tap", "list"),
- ("skills", "tap", "add"),
- ("skills", "tap", "remove"),
- ("mcp", "list"),
- ("mcp", "catalog"),
- ("mcp", "test"),
- ("mcp", "add"),
- ("mcp", "remove"),
- ("mcp", "install"),
- ("mcp", "login"),
- ("mcp", "reauth"),
- ("mcp", "configure"),
- ("mcp", "picker"),
- ("memory", "status"),
- ("memory", "off"),
- ("memory", "reset"),
- ("auth", "list"),
- ("auth", "status"),
- ("auth", "reset"),
- ("auth", "add"),
- ("auth", "remove"),
- ("auth", "logout"),
- ("auth", "spotify", "status"),
- ("auth", "spotify", "login"),
- ("auth", "spotify", "logout"),
- ("pairing", "list"),
- ("pairing", "approve"),
- ("pairing", "revoke"),
- ("pairing", "clear-pending"),
- ("webhook", "list"),
- ("webhook", "subscribe"),
- ("webhook", "remove"),
- ("webhook", "test"),
- ("hooks", "list"),
- ("hooks", "test"),
- ("hooks", "doctor"),
- ("hooks", "revoke"),
- ("slack", "manifest"),
- ("project", "list"),
- ("project", "show"),
- ("project", "create"),
- ("project", "add-folder"),
- ("project", "remove-folder"),
- ("project", "rename"),
- ("project", "set-primary"),
- ("project", "use"),
- ("project", "archive"),
- ("project", "restore"),
- ("project", "bind-board"),
- ("kanban", "init"),
- ("kanban", "boards", "list"),
- ("kanban", "boards", "create"),
- ("kanban", "boards", "rm"),
- ("kanban", "boards", "switch"),
- ("kanban", "boards", "current"),
- ("kanban", "boards", "rename"),
- ("kanban", "boards", "set-workdir"),
- ("kanban", "create"),
- ("kanban", "list"),
- ("kanban", "show"),
- ("kanban", "assign"),
- ("kanban", "reclaim"),
- ("kanban", "reassign"),
- ("kanban", "diagnose"),
- ("kanban", "link"),
- ("kanban", "unlink"),
- ("kanban", "claim"),
- ("kanban", "comment"),
- ("kanban", "complete"),
- ("kanban", "edit"),
- ("kanban", "block"),
- ("kanban", "schedule"),
- ("kanban", "unblock"),
- ("kanban", "promote"),
- ("kanban", "archive"),
- ("kanban", "stats"),
- ("kanban", "runs"),
- ("kanban", "heartbeat"),
- ("kanban", "assignments"),
- ("kanban", "context"),
- ("bundles", "list"),
- ("bundles", "show"),
- ("bundles", "create"),
- ("bundles", "delete"),
- ("bundles", "reload"),
- ("checkpoints", "status"),
- ("checkpoints", "list"),
- ("checkpoints", "prune"),
- ("checkpoints", "clear"),
- ("checkpoints", "clear-legacy"),
- ("curator", "status"),
- ("curator", "run"),
- ("curator", "pause"),
- ("curator", "resume"),
- ("curator", "pin"),
- ("curator", "unpin"),
- ("curator", "restore"),
- ("curator", "list-archived"),
- ("curator", "archive"),
- ("curator", "prune"),
- ("curator", "backup"),
- ("curator", "rollback"),
- ("pets", "list"),
- ("pets", "install"),
- ("pets", "select"),
- ("pets", "show"),
- ("pets", "off"),
- ("pets", "scale"),
- ("pets", "remove"),
- ("pets", "doctor"),
-}
-
-
-MUTATING_CONFIRMATION_SMOKE_COMMANDS = [
- "config set console.test true",
- "config migrate",
- "sessions rename abc123 new title",
- "sessions optimize",
- "cron create 'every 1h' 'say hello'",
- "cron remove abc123",
- "profile create tester --no-alias --no-skills",
- "profile delete tester",
- "tools disable web",
- "plugins install owner/repo --no-enable",
- "skills install openai/skills/example",
- "mcp add demo --url https://example.com/sse",
- "mcp configure github",
- "mcp picker",
- "backup --quick -o /tmp/hermes-console-test.zip",
- "import /tmp/hermes-console-test.zip",
- "send --to telegram hello",
- "memory reset --target memory",
- "auth remove openrouter 1",
- "pairing approve abc123",
- "webhook subscribe test --prompt hello",
- "hooks test pre_tool_call",
- "project create demo",
- "kanban create 'demo task'",
- "bundles create demo --skill skill-a",
- "checkpoints prune",
- "curator pause",
- "pets install cat",
-]
-
-
-
-
-
-
-
-
-
-
-
-
def test_sessions_optimize_accepts_the_force_override_it_advertises(_isolate_hermes_home):
"""The held-store refusal this command prints points at `sessions optimize --force`; if the
console rejected the flag, the command could only ever refuse whenever a gateway is running."""
@@ -497,13 +264,6 @@ def test_capture_output_surfaces_string_exit_code_as_command_error():
assert "No credential matching" in str(exc_info.value)
-def test_capture_output_preserves_integer_exit_code_message():
- from hermes_cli.console_engine import ConsoleCommandError, _capture_output
-
- with pytest.raises(ConsoleCommandError) as exc_info:
- _capture_output(lambda: sys.exit(3))
-
- assert "status 3" in str(exc_info.value)
def test_execute_handler_string_exit_returns_error_not_crash(_isolate_hermes_home):
@@ -572,29 +332,6 @@ def test_console_checkpoints_prune_does_not_reprompt_for_orphans(
assert prune_calls[0]["orphan_allowlist"] is None
-def test_console_checkpoints_prune_succeeds_without_a_tty(
- _isolate_hermes_home, monkeypatch
-):
- """The dashboard console has no stdin, so an unskipped prompt aborts the command.
-
- `_capture_output` redirects stdout/stderr but never stdin, so `input()` raises
- `EOFError`, `_confirm` returns False, and `cmd_prune` returns 1 — which the
- console surfaces as a failed command for every user with an orphan project.
- """
- prune_calls: list = []
- _patch_checkpoint_manager(monkeypatch, prune_calls)
-
- def _eof_input(_prompt):
- raise EOFError
-
- monkeypatch.setattr("builtins.input", _eof_input)
-
- result = HermesConsoleEngine().execute("checkpoints prune", confirmed=True)
-
- assert result.status == "ok"
- assert "Aborted." not in result.output
- assert len(prune_calls) == 1
- assert prune_calls[0]["orphan_allowlist"] is None
def test_config_set_on_unparseable_yaml_reports_error_not_crash(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_container_aware_cli.py b/tests/hermes_cli/test_container_aware_cli.py
index 49b442cf7fb..033218755c5 100644
--- a/tests/hermes_cli/test_container_aware_cli.py
+++ b/tests/hermes_cli/test_container_aware_cli.py
@@ -5,8 +5,6 @@ writes a .container-mode metadata file. The host CLI detects this and
execs into the container instead of running locally.
"""
import os
-import subprocess
-from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
@@ -52,12 +50,6 @@ def test_get_container_exec_info_returns_metadata(container_env):
assert info["hermes_bin"] == "/data/current-package/bin/hermes"
-
-
-
-
-
-
# =============================================================================
# _exec_in_container
# =============================================================================
@@ -73,16 +65,6 @@ def docker_container_info():
}
-def podman_container_info():
- return {
- "backend": "podman",
- "container_name": "hermes-agent",
- "exec_user": "hermes",
- "hermes_bin": "/data/current-package/bin/hermes",
- }
-
-
def test_exec_in_container_calls_execvp(docker_container_info):
"""Verifies os.execvp is called with correct args: runtime, tty flags,
user, env vars, container name, binary, and CLI args."""
diff --git a/tests/hermes_cli/test_container_boot.py b/tests/hermes_cli/test_container_boot.py
index 1a38672bdbc..d2ae51a3fb6 100644
--- a/tests/hermes_cli/test_container_boot.py
+++ b/tests/hermes_cli/test_container_boot.py
@@ -180,18 +180,6 @@ def test_registered_profile_has_finish_script(tmp_path: Path) -> None:
assert "125" in text
-
-
-
-
-
-
-
-
-
-
-
-
def test_register_service_overwrites_existing_slot(tmp_path: Path) -> None:
"""A second reconciliation pass cleanly replaces an existing
slot (the tmp+rename publication overwrites the previous one)."""
@@ -223,19 +211,11 @@ def test_register_service_overwrites_existing_slot(tmp_path: Path) -> None:
assert (scandir / "gateway-coder" / "down").exists()
-
-
# ---------------------------------------------------------------------------
# Default-profile slot — always registered (PR #30136 review item I1)
# ---------------------------------------------------------------------------
-
-
-
-
-
-
def test_profiles_default_subdir_is_skipped_with_warning(
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
@@ -268,14 +248,9 @@ def test_profiles_default_subdir_is_skipped_with_warning(
# ---------------------------------------------------------------------------
-
-
-
-
def test_main_skips_reconcile_in_dashboard_container_s6v3(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
- capsys: pytest.CaptureFixture[str],
) -> None:
"""The dashboard skip must fire under the s6-overlay v3 argv shape.
@@ -317,22 +292,6 @@ def test_main_skips_reconcile_in_dashboard_container_s6v3(
assert rc == 0
assert not (scandir / "gateway-worker").exists()
assert not (scandir / "gateway-default").exists()
- assert "skipping (dashboard container" in capsys.readouterr().out
-
-
-
-
-# ---------------------------------------------------------------------------
-# prior_exit annotation (NS-608 — unclean-shutdown forensics)
-# ---------------------------------------------------------------------------
-
-
-def _write_lifecycle_sentinel(profile_dir: Path, payload: dict) -> None:
- state_dir = profile_dir / "state"
- state_dir.mkdir(parents=True, exist_ok=True)
- (state_dir / "gateway.lifecycle.json").write_text(json.dumps(payload))
-
-
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_context_cache_switch_guard.py b/tests/hermes_cli/test_context_cache_switch_guard.py
index 2dc9598a4b4..672b875b12d 100644
--- a/tests/hermes_cli/test_context_cache_switch_guard.py
+++ b/tests/hermes_cli/test_context_cache_switch_guard.py
@@ -35,7 +35,6 @@ class TestContextCacheGuard:
warning = _guard("new/model", SelectionContext(context_tokens=tokens, current_model="old/model"))
assert warning is not None
assert warning.kind == "context_cache"
- assert "uncached" in warning.message
assert f"{tokens:,}" in warning.message
def test_same_model_reselect_stays_silent(self):
diff --git a/tests/hermes_cli/test_context_policy.py b/tests/hermes_cli/test_context_policy.py
index 46eeef8c5ba..f1b9105c405 100644
--- a/tests/hermes_cli/test_context_policy.py
+++ b/tests/hermes_cli/test_context_policy.py
@@ -13,7 +13,6 @@ import pytest
from hermes_cli.local_runtime.context_policy import (
FLOOR,
SPEED_FLOOR_TOK_S,
- GrowthDecision,
WindowDecision,
growth_decision,
initial_window,
@@ -28,7 +27,6 @@ from hermes_cli.local_runtime.estimator import (
ModelProfile,
PhysicsRefusal,
ctx_bytes,
- kv_dtype_factor,
physics_check,
)
@@ -103,61 +101,15 @@ def test_swa_layers_capped_at_window():
assert big / small < 0.6 * 8
-def test_q8_factor_is_exactly_34_over_64():
- assert kv_dtype_factor(True) == pytest.approx(34 / 64)
- assert kv_dtype_factor(False) == 1.0
-
-
def test_non_fa_fallback_doubles_ctx_cost():
p = dense()
assert ctx_bytes(p, FLOOR, flash_attention=False) == pytest.approx(
ctx_bytes(p, FLOOR, flash_attention=True) * 64 / 34, rel=0.001)
-def test_hybrid_vs_dense_100x_class_spread():
- """The whole reason for the per-layer walk: equal-size models, ~100x
- per-token spread between classic dense and a mostly-recurrent hybrid."""
- d = dense(layers=64, per_token_f16=8192) # 256 KiB/tok class
- h = hybrid(full_layers=4, recurrent_layers=60, per_token_f16=8192)
- window = 256 * KIB
- dense_cost = ctx_bytes(d, window)
- hybrid_cost = ctx_bytes(h, window)
- assert dense_cost / hybrid_cost > 10
-
-
# ── measured-constant spot checks (real models, tolerance bands) ──
-def test_measured_dense_4b_per_token():
- """Qwen3-4B: 36 layers x 8 kv-heads x (128+128) x 2B = 144 KiB/tok f16."""
- p = ModelProfile(name="qwen3-4b", weights_bytes=0, embd_table_bytes=0,
- n_ctx_train=262144,
- layers=[(LayerKind.FULL, 8 * 256 * 2)] * 36)
- per_token_bytes = ctx_bytes(p, 32 * KIB, flash_attention=False) / (32 * KIB)
- assert per_token_bytes == pytest.approx(144 * KIB, rel=0.02)
-
-
-def test_measured_gdn_27b_per_token_q8():
- """Qwen3.6-27B: 16 full-attn of 64; measured 34.0 KiB/tok @ q8 (B4).
- Per-layer f16 = 34 KiB * 64/34 / 16 = 4 KiB."""
- per_layer_f16 = 4 * KIB
- kv_only = ModelProfile(name="kv", weights_bytes=0, embd_table_bytes=0,
- n_ctx_train=262144,
- layers=[(LayerKind.FULL, per_layer_f16)] * 16)
- per_token_bytes = ctx_bytes(kv_only, 128 * KIB) / (128 * KIB)
- assert per_token_bytes == pytest.approx(34 * KIB, rel=0.02)
-
-
-def test_measured_nemotron_1m_within_band():
- """1M @ q8 measured 3264 MiB KV (B3): ~3.19 KiB/token TOTAL across the
- 16 full-attn layers -> per-layer f16 ~384 B. Estimator must land in the
- measured band, not the dense-formula 100x miss."""
- p = hybrid(full_layers=16, recurrent_layers=46, per_token_f16=384,
- native=1024 * KIB)
- total = ctx_bytes(p, 1024 * KIB)
- assert 2.5 * GIB < total < 4.0 * GIB
-
-
# ── physics check ────────────────────────────────────────────
@@ -167,7 +119,6 @@ def test_physics_refusal_only_past_vram_plus_ram():
assert ok is None # 60 GiB weights fit in 24+64
refused = physics_check(p, card(24, ram_gib=16), FLOOR)
assert isinstance(refused, PhysicsRefusal)
- assert "smaller quant" in refused.message
def test_physics_check_prices_at_floor_not_native():
@@ -316,7 +267,6 @@ def test_growth_stops_at_native():
def test_speed_floor_flips_default_to_compression():
d = _grow(dense(), card(24), measured_decode_tok_s=SPEED_FLOOR_TOK_S - 2)
assert d.action == "compress-default"
- assert "explicit per-session choice" in d.reason
def test_growth_refits_against_live_budget():
@@ -416,14 +366,6 @@ def test_ub_logits_bytes_prices_the_flag_choice():
assert ub_logits_bytes(0, mtp_capable=True) == 0 # unknown vocab: no charge
-def test_no_refusal_branch_past_physics():
- """Design invariant: anything past the physics check is servable —
- initial_window never refuses on its own."""
- for vram in (4, 6, 8, 12):
- d = initial_window(dense(weights_gib=20), card(vram, ram_gib=64))
- assert isinstance(d, WindowDecision)
-
-
def test_kv_scale_prices_mtp_draft_context():
"""MTP profiles carry kv_scale > 1 (the draft context's KV share,
calibrated from measured server RSS); ctx_bytes must scale with it so
diff --git a/tests/hermes_cli/test_copilot_auth.py b/tests/hermes_cli/test_copilot_auth.py
index a8c20ac6ec4..8fddea124cf 100644
--- a/tests/hermes_cli/test_copilot_auth.py
+++ b/tests/hermes_cli/test_copilot_auth.py
@@ -11,8 +11,6 @@ class TestTokenValidation:
from hermes_cli.copilot_auth import validate_copilot_token
valid, msg = validate_copilot_token("ghp_abcdefghijklmnop1234")
assert valid is False
- assert "Classic Personal Access Tokens" in msg
- assert "ghp_" in msg
@pytest.mark.parametrize("token", ["gho_abcdefghijklmnop1234", "github_pat_abcdefghijklmnop1234", "ghu_abcdefghijklmnop1234"])
def test_supported_token_families_accepted(self, token):
@@ -24,7 +22,6 @@ class TestTokenValidation:
from hermes_cli.copilot_auth import validate_copilot_token
valid, msg = validate_copilot_token("not_a_github_token")
assert valid is False
- assert "Supported token prefixes" in msg
class TestResolveToken:
@@ -41,15 +38,13 @@ class TestResolveToken:
assert source == "GH_TOKEN"
-
-
def test_gh_cli_classic_pat_raises(self, monkeypatch):
from hermes_cli.copilot_auth import resolve_copilot_token
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
with patch("hermes_cli.copilot_auth._try_gh_cli_token", return_value="ghp_classic"):
- with pytest.raises(ValueError, match="Classic Personal Access Tokens"):
+ with pytest.raises(ValueError):
resolve_copilot_token()
def test_invalid_env_var_skips_gh_cli_fallback(self, monkeypatch):
@@ -107,14 +102,6 @@ class TestGhCliTokenCache:
assert probe.call_count == 1
self._reset()
- def test_hit_is_cached(self):
- from hermes_cli import copilot_auth
- self._reset()
- with patch.object(copilot_auth, "_probe_gh_cli_token", return_value="gho_cached") as probe:
- assert copilot_auth._try_gh_cli_token() == "gho_cached"
- assert copilot_auth._try_gh_cli_token() == "gho_cached"
- assert probe.call_count == 1
- self._reset()
def test_ttl_expiry_reprobes(self, monkeypatch):
from hermes_cli import copilot_auth
@@ -128,16 +115,6 @@ class TestGhCliTokenCache:
assert probe.call_count == 2
self._reset()
- def test_invalidate_forces_reprobe(self):
- from hermes_cli import copilot_auth
- self._reset()
- with patch.object(copilot_auth, "_probe_gh_cli_token", return_value=None) as probe:
- copilot_auth._try_gh_cli_token()
- copilot_auth._invalidate_gh_cli_token_cache()
- copilot_auth._try_gh_cli_token()
- assert probe.call_count == 2
- self._reset()
-
class TestRequestHeaders:
"""Copilot API header generation."""
@@ -160,12 +137,6 @@ class TestCopilotDefaultHeaders:
"""The models.py copilot_default_headers uses copilot_auth."""
- def test_agent_turn_explicit(self):
- """Explicitly passing is_agent_turn=True sets x-initiator to 'agent'."""
- from hermes_cli.models import copilot_default_headers
- headers = copilot_default_headers(is_agent_turn=True)
- assert headers["x-initiator"] == "agent"
-
def test_param_passthrough_both_values(self):
"""is_agent_turn param correctly maps to x-initiator for both True and False."""
from hermes_cli.models import copilot_default_headers
@@ -177,23 +148,6 @@ class TestCopilotDefaultHeaders:
)
-class TestApiModeSelection:
- """API mode selection matching opencode's shouldUseCopilotResponsesApi."""
-
- def test_gpt5_uses_responses(self):
- from hermes_cli.models import _should_use_copilot_responses_api
- assert _should_use_copilot_responses_api("gpt-5.4") is True
- assert _should_use_copilot_responses_api("gpt-5.4-mini") is True
- assert _should_use_copilot_responses_api("gpt-5.3-codex") is True
- assert _should_use_copilot_responses_api("gpt-5.2-codex") is True
- assert _should_use_copilot_responses_api("gpt-5.2") is True
- assert _should_use_copilot_responses_api("gpt-5.1-codex-max") is True
-
- def test_gpt5_mini_excluded(self):
- from hermes_cli.models import _should_use_copilot_responses_api
- assert _should_use_copilot_responses_api("gpt-5-mini") is False
-
-
class TestEnvVarOrder:
"""PROVIDER_REGISTRY has correct env var order."""
diff --git a/tests/hermes_cli/test_copilot_runtime_api_mode.py b/tests/hermes_cli/test_copilot_runtime_api_mode.py
index 27c0914a2ba..138e4dff96a 100644
--- a/tests/hermes_cli/test_copilot_runtime_api_mode.py
+++ b/tests/hermes_cli/test_copilot_runtime_api_mode.py
@@ -7,29 +7,6 @@ from types import SimpleNamespace
import pytest
-def test_copilot_runtime_api_mode_uses_target_model_over_stale_config_default(monkeypatch):
- """MoA/fallback slots must derive Copilot api_mode from the slot model.
-
- Repro: user's main/default Copilot model is GPT-5.5 (Responses API), but a
- MoA reference slot is Copilot Claude Opus (Chat Completions). Runtime
- resolution previously looked only at model.default and returned
- codex_responses for the Claude slot, causing Copilot to reject it with
- "model ... does not support Responses API".
- """
- from hermes_cli import runtime_provider as rp
-
- monkeypatch.setattr(
- "hermes_cli.models.copilot_model_api_mode",
- lambda model, api_key=None: "codex_responses" if str(model).startswith("gpt-5") else "chat_completions",
- )
-
- assert rp._copilot_runtime_api_mode(
- {"provider": "copilot", "default": "gpt-5.5"},
- "token",
- target_model="claude-opus-4.8",
- ) == "chat_completions"
-
-
def test_copilot_runtime_api_mode_still_uses_default_without_target(monkeypatch):
from hermes_cli import runtime_provider as rp
diff --git a/tests/hermes_cli/test_copilot_token_exchange.py b/tests/hermes_cli/test_copilot_token_exchange.py
index 3b448f30d53..dc906708073 100644
--- a/tests/hermes_cli/test_copilot_token_exchange.py
+++ b/tests/hermes_cli/test_copilot_token_exchange.py
@@ -52,7 +52,6 @@ class TestExchangeCopilotToken:
assert "GitHubCopilotChat" in req.get_header("User-agent")
-
@patch("urllib.request.urlopen")
def test_raises_on_empty_token(self, mock_urlopen):
from hermes_cli.copilot_auth import exchange_copilot_token
@@ -68,30 +67,6 @@ class TestExchangeCopilotToken:
exchange_copilot_token("gho_test123")
-class TestGetCopilotApiToken:
- """Tests for get_copilot_api_token() — the fallback wrapper."""
-
- @patch("hermes_cli.copilot_auth.exchange_copilot_token")
- def test_returns_exchanged_token(self, mock_exchange):
- from hermes_cli.copilot_auth import get_copilot_api_token
-
- mock_exchange.return_value = ("exchanged_jwt", time.time() + 1800, None)
- api_token, base_url = get_copilot_api_token("gho_raw")
- assert api_token == "exchanged_jwt"
- assert base_url is None
-
-
-class TestTokenFingerprint:
- """Tests for _token_fingerprint()."""
-
- def test_consistent(self):
- from hermes_cli.copilot_auth import _token_fingerprint
-
- fp1 = _token_fingerprint("gho_abc123")
- fp2 = _token_fingerprint("gho_abc123")
- assert fp1 == fp2
-
-
class TestCallerIntegration:
"""Test that callers correctly use token exchange."""
@@ -118,26 +93,6 @@ class TestDeriveBaseUrlFromProxyEp:
assert _derive_base_url_from_proxy_ep(token) == "https://api.enterprise.githubcopilot.com"
-
-
- @patch("urllib.request.urlopen")
- def test_exchange_returns_none_base_url_for_individual(self, mock_urlopen, _clear_jwt_cache):
- """exchange_copilot_token returns None base_url for individual accounts."""
- from hermes_cli.copilot_auth import exchange_copilot_token
-
- token_no_ep = "tid=abc;exp=999;sku=copilot_individual"
- expires_at = time.time() + 1800
- resp_data = json.dumps({"token": token_no_ep, "expires_at": expires_at}).encode()
- mock_resp = MagicMock()
- mock_resp.read.return_value = resp_data
- mock_resp.__enter__ = MagicMock(return_value=mock_resp)
- mock_resp.__exit__ = MagicMock(return_value=False)
- mock_urlopen.return_value = mock_resp
-
- api_token, _, base_url = exchange_copilot_token("gho_test")
- assert base_url is None
-
-
class TestJwtDiskStoreBounds:
"""The on-disk JWT store must go through one bounded read everywhere."""
diff --git a/tests/hermes_cli/test_cpr_local_leak.py b/tests/hermes_cli/test_cpr_local_leak.py
index 3d636e00b58..4259ffbb6e2 100644
--- a/tests/hermes_cli/test_cpr_local_leak.py
+++ b/tests/hermes_cli/test_cpr_local_leak.py
@@ -1,24 +1,13 @@
-"""Local CPR leak reproduction + classic-CLI Application output selection.
-
-* Deterministic local-PTY proof that delayed CPR replies leak as
- ``ESC[row;colR`` / ``^[[row;colR`` when ``enable_cpr=True`` (no SSH).
-* Integration-level assertion that, with no SSH env vars, classic CLI
- output selection wires a CPR-disabled Output into Application on POSIX.
-* Native Windows keeps prompt_toolkit's default output selection.
-"""
+"""Classic-CLI prompt_toolkit output selection: native Windows keeps prompt_toolkit's default
+output unless PROMPT_TOOLKIT_NO_CPR opts in to the CPR-disabled output."""
from __future__ import annotations
-import os
-import select
import sys
-import threading
-import time
import pytest
from cli import (
- _build_cpr_disabled_output,
_select_classic_cli_pt_output,
_terminal_may_leak_cpr,
)
@@ -48,121 +37,3 @@ class TestClassicCliOutputSelection:
assert out is None or out.enable_cpr is False
-def _openpty_or_skip():
- import pty
-
- try:
- return pty.openpty()
- except OSError as exc:
- pytest.skip(f"no PTY devices available: {exc}")
-
-
[email protected](sys.platform == "win32", reason="POSIX PTY harness")
-class TestDelayedCprLocalPtyLeak:
- def test_delayed_cpr_reply_leaks_when_enable_cpr_true(self):
- """Local (no SSH) delayed ESC[6n reply lands as ESC[39;1R on stdin."""
- import tty
-
- from prompt_toolkit.data_structures import Size
- from prompt_toolkit.output.vt100 import Vt100_Output
-
- master, slave = _openpty_or_skip()
- try:
- tty.setraw(slave)
- slave_w = os.fdopen(os.dup(slave), "w", buffering=1)
- stop = threading.Event()
- queries = 0
-
- def terminal() -> None:
- nonlocal queries
- buf = b""
- while not stop.is_set():
- try:
- r, _, _ = select.select([master], [], [], 0.05)
- except OSError:
- break
- if not r:
- continue
- try:
- chunk = os.read(master, 4096)
- except OSError:
- break
- if not chunk:
- break
- buf += chunk
- while True:
- idx = buf.find(b"\x1b[6n")
- if idx < 0:
- buf = buf[-8:] if len(buf) > 8 else buf
- break
- buf = buf[idx + 4 :]
- queries += 1
- time.sleep(0.12)
- try:
- os.write(master, b"\x1b[39;1R")
- except OSError:
- pass
-
- threading.Thread(target=terminal, daemon=True).start()
- out = Vt100_Output(
- slave_w, lambda: Size(rows=40, columns=80), enable_cpr=True
- )
- out.ask_for_cpr()
- out.flush()
- for i in range(4):
- slave_w.write(f"\rgpt-5.6-sol Q {i}\n")
- slave_w.flush()
- time.sleep(0.02)
- time.sleep(0.3)
-
- data = b""
- while True:
- r, _, _ = select.select([slave], [], [], 0.05)
- if not r:
- break
- data += os.read(slave, 4096)
-
- stop.set()
- slave_w.close()
-
- assert queries >= 1
- assert b"\x1b[39;1R" in data
- finally:
- try:
- os.close(slave)
- except OSError:
- pass
- try:
- os.close(master)
- except OSError:
- pass
-
- def test_cpr_disabled_output_sends_no_query(self):
- """Hermes CPR-disabled builder must not emit ESC[6n."""
- master, slave = _openpty_or_skip()
- try:
- slave_w = os.fdopen(slave, "w", buffering=1)
- out = _build_cpr_disabled_output(slave_w)
- assert out is not None
- assert out.enable_cpr is False
-
- seen = b""
-
- def reader() -> None:
- nonlocal seen
- r, _, _ = select.select([master], [], [], 0.25)
- if r:
- seen = os.read(master, 4096)
-
- threading.Thread(target=reader, daemon=True).start()
- slave_w.write("status ok\n")
- slave_w.flush()
- # Do not call ask_for_cpr — renderer skips it when NOT_SUPPORTED.
- time.sleep(0.3)
- slave_w.close()
- assert b"\x1b[6n" not in seen
- finally:
- try:
- os.close(master)
- except OSError:
- pass
diff --git a/tests/hermes_cli/test_credential_lifecycle.py b/tests/hermes_cli/test_credential_lifecycle.py
index 5ea5a9d9521..37bc3279075 100644
--- a/tests/hermes_cli/test_credential_lifecycle.py
+++ b/tests/hermes_cli/test_credential_lifecycle.py
@@ -228,33 +228,6 @@ def test_put_api_env_materializes_credential_pool_entry(hermes_home):
assert matched_runtime[0].auth_type == "api_key"
-def test_put_api_env_writes_auth_json_for_provider(hermes_home):
- """Sentinel for #96058: PUT /api/env must modify auth.json on disk.
-
- The reported symptom was ``stat -c '%y' ~/.hermes/auth.json`` returning
- the same value before and after the Desktop Save. After the fix the file's
- mtime advances because the save materializes the env-seeded pool entry.
- """
- _write_auth(hermes_home, {})
- auth_path = hermes_home / "auth.json"
- assert auth_path.exists()
- mtime_before = auth_path.stat().st_mtime_ns
-
- # Tiny delay so a write is observable even on filesystems with 1s mtime
- # resolution. Use ns precision so this is reliable on every FS.
- import time
- time.sleep(0.05)
-
- resp = client.put(
- "/api/env",
- json={"key": "OPENCODE_GO_API_KEY", "value": OPENCODE_KEY_NEW},
- headers=HEADERS,
- )
- assert resp.status_code == 200, resp.text
-
- assert auth_path.stat().st_mtime_ns > mtime_before, (
- "auth.json was not modified by the Desktop Save — bug #96058"
- )
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_credential_pool_off_loop.py b/tests/hermes_cli/test_credential_pool_off_loop.py
index 5a5ff5b7487..e7ac033402f 100644
--- a/tests/hermes_cli/test_credential_pool_off_loop.py
+++ b/tests/hermes_cli/test_credential_pool_off_loop.py
@@ -9,7 +9,6 @@ so a networkless host froze the whole dashboard backend for 17 minutes.
from __future__ import annotations
-import asyncio
import threading
import time
from unittest.mock import patch
@@ -26,10 +25,6 @@ import hermes_cli.web_routers.ops as _rt_ops
class TestUrlopenBounded:
- def test_returns_response_when_worker_completes(self):
- sentinel = object()
- with patch("urllib.request.urlopen", return_value=sentinel):
- assert copilot_auth._urlopen_bounded("req", 1.0) is sentinel
def test_reraises_worker_exception(self):
with patch("urllib.request.urlopen", side_effect=OSError("boom")):
@@ -180,7 +175,6 @@ class TestExchangeSingleFlight:
@pytest.mark.asyncio
async def test_list_credential_pool_runs_off_event_loop(monkeypatch):
import hermes_cli.auth as auth_mod
- from hermes_cli import web_server
loop_thread = threading.get_ident()
seen = {}
@@ -196,33 +190,3 @@ async def test_list_credential_pool_runs_off_event_loop(monkeypatch):
assert seen["thread"] != loop_thread
-async def test_list_credential_pool_keeps_loop_responsive(monkeypatch):
- """A 200 ms blocking pool read must not freeze a concurrent ticker."""
- import hermes_cli.auth as auth_mod
- from hermes_cli import web_server
-
- def slow_read(*args, **kwargs):
- time.sleep(0.5)
- return {}
-
- monkeypatch.setattr(auth_mod, "read_credential_pool", slow_read)
-
- gaps = []
- stop = asyncio.Event()
-
- async def ticker():
- last = time.perf_counter()
- while not stop.is_set():
- await asyncio.sleep(0.005)
- now = time.perf_counter()
- gaps.append(now - last)
- last = now
-
- t = asyncio.create_task(ticker())
- await _rt_ops.list_credential_pool()
- stop.set()
- await t
- # 0.25 s threshold vs a 0.5 s blocking read: a regression (read on the
- # loop) trips it by 2x, while runner-noise descheduling would need >200 ms.
- assert max(gaps) < 0.25, f"event loop stalled for {max(gaps) * 1000:.0f} ms"
diff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.py
index 7d1973a70bf..8148bc82f99 100644
--- a/tests/hermes_cli/test_cron.py
+++ b/tests/hermes_cli/test_cron.py
@@ -386,38 +386,8 @@ class TestExternalCronProviderStatus:
assert "Scheduler is not ready" not in out
-def test_cron_list_warns_when_gateway_not_running(monkeypatch, capsys):
- monkeypatch.setattr(
- "cron.jobs.list_jobs",
- lambda include_disabled=False: [
- {
- "id": "job-1",
- "name": "Nightly docs",
- "schedule_display": "every day",
- "state": "scheduled",
- "enabled": True,
- "next_run_at": "2026-06-01T00:00:00Z",
- "deliver": ["local"],
- }
- ],
- )
- monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])
- monkeypatch.setattr(cron_cli, "_active_cron_provider_name", lambda: "builtin")
-
- cron_cli.cron_list()
-
- out = capsys.readouterr().out
- assert "Scheduler is not ready" in out
- assert "Nightly docs" in out
-
-
-def test_cron_tick_invokes_scheduler_tick_with_verbose(monkeypatch):
- calls = []
- monkeypatch.setattr("cron.scheduler.tick", lambda verbose=False: calls.append(verbose))
- cron_cli.cron_tick()
- assert calls == [True]
def test_cron_create_failure_returns_nonzero(monkeypatch, capsys):
@@ -593,15 +563,6 @@ class TestSlashCronListLastStatus:
out = self._run_list(tmp_cron_dir, capsys)
assert "Last run: 2026-09-01T07:00:00+00:00 (delivery_failed: telegram: 502 Bad Gateway)" in out
- def test_ok_stays_plain(self, tmp_cron_dir, capsys):
- create_job(prompt="Nightly brief", schedule="every 1h")
- jobs = load_jobs()
- jobs[0]["last_run_at"] = "2026-09-01T07:00:00+00:00"
- jobs[0]["last_status"] = "ok"
- save_jobs(jobs)
-
- out = self._run_list(tmp_cron_dir, capsys)
- assert "(ok)" in out
class TestStatusSurfacesDeadScheduler:
diff --git a/tests/hermes_cli/test_cron_dispatch_visibility.py b/tests/hermes_cli/test_cron_dispatch_visibility.py
index ba2e050bed8..47a4b756d7a 100644
--- a/tests/hermes_cli/test_cron_dispatch_visibility.py
+++ b/tests/hermes_cli/test_cron_dispatch_visibility.py
@@ -141,7 +141,3 @@ class TestDisplayHelpers:
assert _dispatch_display({}) is None
assert _dispatch_display({"scheduled_at": "x"}) is None
- def test_dispatch_display_late_kind(self):
- line = _dispatch_display(_catch_up_stamp(600.0, kind="late"))
- assert "late" in line
- assert "10m" in line
diff --git a/tests/hermes_cli/test_cron_fire_dashboard.py b/tests/hermes_cli/test_cron_fire_dashboard.py
index 9294c9ba587..1895a31ddcc 100644
--- a/tests/hermes_cli/test_cron_fire_dashboard.py
+++ b/tests/hermes_cli/test_cron_fire_dashboard.py
@@ -14,13 +14,11 @@ hosted agents don't expose). It must:
through — 503 when the gateway is unreachable so NAS retries.
"""
-import pytest
from starlette.testclient import TestClient
from hermes_cli import web_server
import hermes_cli.config as _cfg_mod
import hermes_cli.web_server_cron as _web_server_cron
-from hermes_cli.dashboard_auth.public_paths import PUBLIC_API_PATHS
def _client(auth_required: bool):
@@ -47,10 +45,6 @@ def _restore(prev_auth, prev_host):
-def test_fire_path_is_public():
- """Must bypass the dashboard cookie gate so the NAS bearer-JWT callback
- reaches the verifier (the JWT is the real auth)."""
- assert "/api/cron/fire" in PUBLIC_API_PATHS
def test_bad_token_401(monkeypatch):
@@ -135,7 +129,7 @@ def test_valid_fire_forwards_to_gateway(monkeypatch):
monkeypatch.setattr(_web_server_cron, "_fire_cron_job_for_profile",
lambda p, j: executed.append((p, j)))
- client, pa, ph = _client(auth_required=False)
+ client, pa, ph = _client(auth_required=True) # the NAS JWT, not the cookie gate, admits it
try:
resp = client.post("/api/cron/fire",
headers={"Authorization": "Bearer nas-jwt"},
diff --git a/tests/hermes_cli/test_cron_parser_builder.py b/tests/hermes_cli/test_cron_parser_builder.py
index 12b07d3a77a..f78844c86e4 100644
--- a/tests/hermes_cli/test_cron_parser_builder.py
+++ b/tests/hermes_cli/test_cron_parser_builder.py
@@ -23,14 +23,6 @@ def _build():
return parser
-def test_cron_subactions_present():
- parser = _build()
- for action in ("list", "create", "edit", "pause", "resume", "run", "remove", "status", "runs", "doctor", "tick"):
- ns = parser.parse_args(["cron", action] if action in ("list", "status", "runs", "doctor", "tick")
- else ["cron", action, "jobid"] if action in ("pause", "resume", "run", "remove", "edit")
- else ["cron", "create", "30m"])
- assert ns.command == "cron"
- assert ns.cron_command == action
def test_cron_edit_no_agent_tristate():
diff --git a/tests/hermes_cli/test_cron_profile_enumeration_lightweight.py b/tests/hermes_cli/test_cron_profile_enumeration_lightweight.py
deleted file mode 100644
index 6e64002b84a..00000000000
--- a/tests/hermes_cli/test_cron_profile_enumeration_lightweight.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Cron aggregation must not perform full profile metadata scans."""
-
-import tempfile
-import unittest
-from pathlib import Path
-from unittest import mock
-
-from hermes_cli import web_server
-import hermes_cli.web_server_cron as _web_server_cron
-
-
-class CronProfileEnumerationTests(unittest.TestCase):
- def test_uses_lightweight_name_path_enumerator(self):
- with tempfile.TemporaryDirectory() as root:
- homes = [
- ("default", Path(root)),
- ("coder-01", Path(root) / "profiles" / "coder-01"),
- ]
- with (
- mock.patch(
- "hermes_cli.profiles.profiles_to_serve",
- return_value=homes,
- ) as lightweight,
- mock.patch(
- "hermes_cli.profiles.list_profiles",
- side_effect=AssertionError("full profile scan is forbidden"),
- ),
- ):
- result = _web_server_cron._cron_profile_dicts()
-
- lightweight.assert_called_once_with(multiplex=True, include_standalone=True)
- self.assertEqual([item["name"] for item in result], ["default", "coder-01"])
- self.assertTrue(result[0]["is_default"])
- self.assertFalse(result[1]["is_default"])
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/hermes_cli/test_cron_status_profile_isolation.py b/tests/hermes_cli/test_cron_status_profile_isolation.py
index 8895e828182..942c9f88f80 100644
--- a/tests/hermes_cli/test_cron_status_profile_isolation.py
+++ b/tests/hermes_cli/test_cron_status_profile_isolation.py
@@ -22,8 +22,7 @@ ticked» unless the gateway process itself started less than STALE_AFTER ago
from __future__ import annotations
import time
-from unittest.mock import MagicMock, Mock, patch
-from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
import pytest
@@ -38,45 +37,6 @@ def tmp_cron_dir(tmp_path, monkeypatch):
-class TestCronStatusHeartbeatGuard:
- """Ensure `hermes cron status` correctly warns when the heartbeat file is absent.
-
- Issue #98790 (root cause 2): profiles with no `cron/ticker_heartbeat` fall
- through to the "✓ Gateway is running" branch even though ticks won't fire.
- """
-
- def test_no_heartbeat_triggers_yellow_warning(self, monkeypatch, capsys):
- from hermes_cli import cron as cron_mod
-
- with (
- patch("hermes_cli.gateway.find_gateway_pids", return_value={789}),
- patch("cron.jobs.get_ticker_heartbeat_age", return_value=None),
- patch("cron.jobs.get_ticker_success_age", return_value=None),
- patch("cron.jobs.get_ticker_last_error", return_value=None),
- patch("cron.jobs.TICKER_INTERVAL_SECONDS", 60),
- ):
- cron_mod.cron_status()
-
- stdout = capsys.readouterr().out
- assert "⚠ Gateway is running but the cron ticker has not reported a heartbeat" in stdout
- assert "Cron jobs will NOT fire" in stdout
- # Must NOT show the green ✓
- assert "✓ Gateway is running" not in stdout
-
- def test_fresh_heartbeat_shows_green_checkmark(self, monkeypatch, capsys):
- from hermes_cli import cron as cron_mod
-
- with (
- patch("hermes_cli.gateway.find_gateway_pids", return_value={999}),
- patch("cron.jobs.get_ticker_heartbeat_age", return_value=10),
- patch("cron.jobs.get_ticker_success_age", return_value=8),
- patch("cron.jobs.TICKER_INTERVAL_SECONDS", 60),
- ):
- cron_mod.cron_status()
-
- stdout = capsys.readouterr().out
- assert "✓ Gateway is running — cron jobs will fire automatically" in stdout
- assert "⚠" not in stdout
class TestGetServicePidsProfileScope:
@@ -153,33 +113,6 @@ class TestGetServicePidsProfileScope:
class TestCronStatusMissingHeartbeat:
"""Missing ticker heartbeat must be reported honestly, not as healthy."""
- def test_missing_heartbeat_warns_when_gateway_old(self, tmp_cron_dir, capsys, monkeypatch):
- import io
- from contextlib import redirect_stdout
- import hermes_cli.cron as cron_cli
- from cron.jobs import create_job
-
- create_job(prompt="Test", schedule="every 1h")
-
- out = io.StringIO()
- with (
- patch("hermes_cli.cron._active_cron_provider_name", return_value="builtin"),
- patch("hermes_cli.gateway.find_gateway_pids", return_value=[4242]),
- patch("gateway.status.is_gateway_runtime_lock_active", return_value=True),
- patch("gateway.status.get_running_pid", return_value=4242),
- patch("cron.jobs.get_ticker_heartbeat_age", return_value=None),
- patch("cron.jobs.get_ticker_success_age", return_value=None),
- patch("cron.jobs.TICKER_INTERVAL_SECONDS", 60),
- # Gateway started long ago, ticker should have heartbeat by now
- patch("gateway.status._read_pid_record", return_value={"pid": 4242, "start_time": 1}),
- patch("gateway.status._get_process_start_time", return_value=1),
- redirect_stdout(out),
- ):
- cron_cli.cron_status()
-
- text = out.getvalue()
- assert "has not reported a heartbeat" in text or "no heartbeat" in text.lower()
- assert "will fire" not in text.lower() or "will NOT fire" in text
def test_missing_heartbeat_green_when_gateway_just_started(self, tmp_cron_dir, capsys, monkeypatch):
import io
diff --git a/tests/hermes_cli/test_ctrl_enter_newline.py b/tests/hermes_cli/test_ctrl_enter_newline.py
index a7eaef77261..38e1aadb840 100644
--- a/tests/hermes_cli/test_ctrl_enter_newline.py
+++ b/tests/hermes_cli/test_ctrl_enter_newline.py
@@ -24,7 +24,6 @@ from unittest.mock import patch
import pytest
-import sys
class FakeKeyBindings:
@@ -40,16 +39,15 @@ class FakeKeyBindings:
def _bind_submit_keys_for_local_linux(cli_mod, *, multiline_shortcuts_enabled):
- with patch.object(sys, "platform", "linux"):
- with patch.dict(os.environ, {}, clear=True):
- with patch("builtins.open", side_effect=OSError("no /proc")):
- kb = FakeKeyBindings()
- cli_mod._bind_prompt_submit_keys(
- kb,
- lambda _event: None,
- multiline_shortcuts_enabled=multiline_shortcuts_enabled,
- )
- return kb
+ with patch.dict(os.environ, {}, clear=True):
+ with patch("builtins.open", side_effect=OSError("no /proc")):
+ kb = FakeKeyBindings()
+ cli_mod._bind_prompt_submit_keys(
+ kb,
+ lambda _event: None,
+ multiline_shortcuts_enabled=multiline_shortcuts_enabled,
+ )
+ return kb
@pytest.mark.windows_only
@@ -83,16 +81,6 @@ def test_ghostty_tmux_session_preserves_ctrl_j_newline():
assert cli_mod._preserve_ctrl_enter_newline() is True
-def test_cli_multiline_shortcuts_default_on():
- """Hermes should default to the common harness behavior: Ctrl+J newline.
-
- Claude Code documents Ctrl+J as a no-setup newline shortcut, OpenCode's
- default input_newline includes ctrl+j, and Codex exposes Ctrl+J/keymap
- newline behavior. Keep Hermes aligned unless the user opts out.
- """
- import cli as cli_mod
-
- assert cli_mod._cli_multiline_shortcuts_enabled({"display": {}}) is True
def test_cli_multiline_shortcuts_can_be_disabled():
@@ -140,11 +128,6 @@ def test_backslash_enter_continuation_replaces_marker_with_newline():
assert cli_mod._apply_backslash_line_continuation("first line\\ ") == "first line\n"
-def test_iterm_is_allowlisted_for_extended_enter_keys():
- """iTerm2 needs the app to request extended keys before Shift+Enter is distinct."""
- import cli as cli_mod
-
- assert cli_mod._terminal_supports_extended_enter_keys({"TERM_PROGRAM": "iTerm.app"}) is True
def test_unknown_terminal_does_not_enable_extended_enter_keys():
diff --git a/tests/hermes_cli/test_curator_archive_prune.py b/tests/hermes_cli/test_curator_archive_prune.py
index 5f5dcb940c0..0ac5af6ecd3 100644
--- a/tests/hermes_cli/test_curator_archive_prune.py
+++ b/tests/hermes_cli/test_curator_archive_prune.py
@@ -1,14 +1,4 @@
-"""Tests for `hermes curator archive` and `hermes curator prune`.
-
-Covers:
-- archive refuses pinned skills with an `unpin` hint
-- archive returns 0/1 based on archive_skill() success
-- prune filters pinned and already-archived, applies --days threshold
-- prune falls back to created_at when last_activity_at is null
-- prune --dry-run makes no state changes
-- prune --yes skips confirmation
-- prune --days validation
-"""
+"""`hermes curator archive` refuses pinned skills (with an `unpin` hint) and never archives them."""
from __future__ import annotations
@@ -41,51 +31,9 @@ def test_archive_refuses_pinned(monkeypatch, capsys):
assert "hermes curator unpin" in out
-
-
# ─── prune ──────────────────────────────────────────────────────────────────
-def _mk_record(name, *, idle_days=0, pinned=False, state="active", created_idle_days=None):
- import datetime as _dt
- now = _dt.datetime.now(_dt.timezone.utc)
- last_activity = (now - _dt.timedelta(days=idle_days)).isoformat() if idle_days else None
- created_delta = created_idle_days if created_idle_days is not None else idle_days
- created = (now - _dt.timedelta(days=created_delta)).isoformat()
- return {
- "name": name,
- "state": state,
- "pinned": pinned,
- "last_activity_at": last_activity,
- "created_at": created,
- "activity_count": 0 if idle_days == 0 and last_activity is None else 1,
- }
-
-
-
-
-
-
-
-
# ─── argparse wiring ────────────────────────────────────────────────────────
-def test_archive_and_prune_registered():
- import argparse
- import hermes_cli.curator as curator_cli
-
- parser = argparse.ArgumentParser(prog="hermes curator")
- curator_cli.register_cli(parser)
-
- args = parser.parse_args(["archive", "my-skill"])
- assert args.skill == "my-skill"
- assert args.func.__name__ == "_cmd_archive"
-
- args = parser.parse_args(["prune", "--days", "45", "--yes", "--dry-run"])
- assert args.days == 45
- assert args.yes is True
- assert args.dry_run is True
- assert args.func.__name__ == "_cmd_prune"
-
-
diff --git a/tests/hermes_cli/test_curator_pin_unmanaged.py b/tests/hermes_cli/test_curator_pin_unmanaged.py
index d3c4b319502..219000b001a 100644
--- a/tests/hermes_cli/test_curator_pin_unmanaged.py
+++ b/tests/hermes_cli/test_curator_pin_unmanaged.py
@@ -41,49 +41,10 @@ def _stub(monkeypatch, *, managed: bool):
return calls
-def test_pin_unmanaged_records_flag_and_prints_adopt_hint(monkeypatch, capsys):
- import hermes_cli.curator as curator_cli
-
- calls = _stub(monkeypatch, managed=False)
-
- rc = curator_cli._cmd_pin(_ns("legacy-skill"))
-
- # The write still happens — the flag becomes meaningful after adopt.
- assert calls == [("legacy-skill", True)]
- assert rc == 0
- out = capsys.readouterr().out
- assert "unmanaged" in out
- assert "hermes curator adopt legacy-skill" in out
- # The old lie must be gone: the pin does NOT bypass anything here.
- assert "will bypass auto-transitions" not in out
-
-
-def test_pin_managed_keeps_bypass_message(monkeypatch, capsys):
- import hermes_cli.curator as curator_cli
- calls = _stub(monkeypatch, managed=True)
-
- rc = curator_cli._cmd_pin(_ns("agent-skill"))
-
- assert calls == [("agent-skill", True)]
- assert rc == 0
- out = capsys.readouterr().out
- assert "will bypass auto-transitions" in out
- assert "unmanaged" not in out
-
-
-def test_unpin_unmanaged_says_it_was_never_managed(monkeypatch, capsys):
- import hermes_cli.curator as curator_cli
- calls = _stub(monkeypatch, managed=False)
- rc = curator_cli._cmd_unpin(_ns("legacy-skill"))
- assert calls == [("legacy-skill", False)]
- assert rc == 0
- out = capsys.readouterr().out
- assert "unmanaged" in out
- assert "never under auto-transitions" in out
def test_pin_still_refuses_bundled_skills(monkeypatch, capsys):
diff --git a/tests/hermes_cli/test_curator_run.py b/tests/hermes_cli/test_curator_run.py
index f9429ba47ca..627f971dc75 100644
--- a/tests/hermes_cli/test_curator_run.py
+++ b/tests/hermes_cli/test_curator_run.py
@@ -34,19 +34,3 @@ def test_run_defaults_to_synchronous(monkeypatch, capsys):
assert "background" not in capsys.readouterr().out
-def test_dry_run_default_reports_synchronous_wording(monkeypatch, capsys):
- import agent.curator as curator_state
- import hermes_cli.curator as curator_cli
-
- monkeypatch.setattr(curator_state, "is_enabled", lambda: True)
- monkeypatch.setattr(
- curator_state,
- "run_curator_review",
- lambda **kwargs: {"auto_transitions": {}},
- )
-
- assert curator_cli._cmd_run(_args(dry_run=True)) == 0
-
- out = capsys.readouterr().out
- assert "When the report lands" not in out
- assert "Read the report with `hermes curator status`" in out
diff --git a/tests/hermes_cli/test_curator_status.py b/tests/hermes_cli/test_curator_status.py
index e153223e0d9..508f38f24c2 100644
--- a/tests/hermes_cli/test_curator_status.py
+++ b/tests/hermes_cli/test_curator_status.py
@@ -12,13 +12,10 @@ import io
from argparse import Namespace
from contextlib import redirect_stdout
from pathlib import Path
-from types import SimpleNamespace
import pytest
-
-
@pytest.fixture
def curator_status_env(tmp_path, monkeypatch):
"""Isolated HERMES_HOME with real agent-created skills on disk."""
@@ -63,47 +60,11 @@ def curator_status_env(tmp_path, monkeypatch):
}
-def _capture_status(curator_cli) -> str:
- buf = io.StringIO()
- with redirect_stdout(buf):
- rc = curator_cli._cmd_status(Namespace())
- assert rc == 0
- return buf.getvalue()
-
-
-
-
# ---------------------------------------------------------------------------
# Unmanaged blind spot + adopt verb
# ---------------------------------------------------------------------------
-
-
-
-
-
-def test_adopt_subcommand_is_registered():
- """The verb must be reachable through the real argparse tree, not just as a
- callable — a handler nobody can dispatch to is dead code."""
- import argparse
-
- import hermes_cli.curator as curator_cli
-
- parser = argparse.ArgumentParser()
- curator_cli.register_cli(parser)
-
- args = parser.parse_args(["adopt", "--all-unmanaged", "--dry-run"])
- assert args.func is curator_cli._cmd_adopt
- assert args.all_unmanaged is True
- assert args.dry_run is True
- assert args.skill == []
-
- named = parser.parse_args(["adopt", "alpha", "beta"])
- assert named.skill == ["alpha", "beta"]
- assert named.all_unmanaged is False
-
-
def test_list_unmanaged_itemizes_and_explains(curator_status_env):
"""`status` gives the count; this gives the names plus WHY each is
unmanaged, so the user can decide what to adopt."""
diff --git a/tests/hermes_cli/test_curator_usage.py b/tests/hermes_cli/test_curator_usage.py
index 0a41f0515fd..e4f2290ca5d 100644
--- a/tests/hermes_cli/test_curator_usage.py
+++ b/tests/hermes_cli/test_curator_usage.py
@@ -8,7 +8,6 @@ Covers:
from __future__ import annotations
-import json
from types import SimpleNamespace
@@ -60,15 +59,3 @@ def test_usage_empty(monkeypatch, capsys):
assert "no skills found" in capsys.readouterr().out
-def test_usage_command_is_registered():
- """The `usage` subcommand must be wired into the curator argparse tree."""
- import argparse
- import hermes_cli.curator as curator_cli
-
- parser = argparse.ArgumentParser(prog="hermes curator")
- curator_cli.register_cli(parser)
- args = parser.parse_args(["usage", "--sort", "recent", "--provenance", "hub", "--json"])
- assert args.func is curator_cli._cmd_usage
- assert args.sort == "recent"
- assert args.provenance == "hub"
- assert args.json is True
diff --git a/tests/hermes_cli/test_curses_color_compat.py b/tests/hermes_cli/test_curses_color_compat.py
deleted file mode 100644
index ee17eb61f7f..00000000000
--- a/tests/hermes_cli/test_curses_color_compat.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Tests for curses color compatibility on low-color terminals (Docker).
-
-Regression test for #13688: ``hermes plugins`` crashes with
-``curses.error: init_pair() : color number is greater than COLORS-1``
-in Docker containers where curses.COLORS == 8 (only colors 0-7 exist).
-
-The bug was ``curses.init_pair(4, 8, -1)`` using raw color 8 ("bright
-black" / dim gray) which does not exist on 8-color terminals. The fix
-clamps with ``min(8, curses.COLORS - 1)``.
-"""
-import sys
-
-import pytest
-
-# curses (and its _curses C extension) is Unix-only; skip the whole module on Windows.
-if sys.platform == "win32":
- pytest.skip("curses is not available on Windows", allow_module_level=True)
-
-import curses
-import re
-from pathlib import Path
-from unittest.mock import patch, MagicMock
-
-
-# Path to the source files under test
-_SRC_ROOT = Path(__file__).parent.parent.parent / "hermes_cli"
-
-
-class TestInitPairClampingBehavior:
- """Simulate curses color initialization on low-color terminals.
-
- Patches curses.COLORS to 8 (Docker default) and verifies that
- init_pair is never called with a color >= COLORS.
- """
-
- def _collect_init_pair_calls(self, draw_fn, colors_value):
- """Run a curses draw function with a mock stdscr and patched COLORS.
-
- Returns list of (pair_number, fg, bg) tuples from init_pair calls.
- """
- calls = []
- real_init_pair = curses.init_pair
-
- def tracking_init_pair(pair, fg, bg):
- calls.append((pair, fg, bg))
-
- mock_stdscr = MagicMock()
- mock_stdscr.getmaxyx.return_value = (24, 80)
- mock_stdscr.getch.return_value = 27 # ESC to exit
-
- with patch("curses.COLORS", colors_value, create=True), \
- patch("curses.init_pair", side_effect=tracking_init_pair), \
- patch("curses.has_colors", return_value=True), \
- patch("curses.start_color"), \
- patch("curses.use_default_colors"), \
- patch("curses.curs_set"):
- try:
- draw_fn(mock_stdscr)
- except (SystemExit, StopIteration, Exception):
- pass # draw functions loop until keypress
-
- return calls
-
- def test_8_color_terminal_no_color_exceeds_limit(self):
- """On an 8-color terminal (Docker), no init_pair fg color >= 8."""
- # Simulate the color init pattern from plugins_cmd.py
- def _simulated_color_init(stdscr):
- if curses.has_colors():
- curses.start_color()
- curses.use_default_colors()
- curses.init_pair(1, curses.COLOR_GREEN, -1)
- curses.init_pair(2, curses.COLOR_YELLOW, -1)
- curses.init_pair(3, curses.COLOR_CYAN, -1)
- curses.init_pair(4, 8 if curses.COLORS > 8 else curses.COLOR_WHITE, -1)
-
- calls = self._collect_init_pair_calls(_simulated_color_init, 8)
- for pair, fg, bg in calls:
- assert fg < 8, (
- f"init_pair({pair}, {fg}, {bg}) uses color {fg} which "
- f"does not exist on an 8-color terminal (valid: 0-7)"
- )
-
- def test_256_color_terminal_uses_color_8(self):
- """On a 256-color terminal, color 8 (dim gray) should be used."""
- def _simulated_color_init(stdscr):
- if curses.has_colors():
- curses.start_color()
- curses.use_default_colors()
- curses.init_pair(4, 8 if curses.COLORS > 8 else curses.COLOR_WHITE, -1)
-
- calls = self._collect_init_pair_calls(_simulated_color_init, 256)
- assert any(fg == 8 for _, fg, _ in calls), (
- "On 256-color terminals, color 8 (dim gray) should be used"
- )
-
-
-class TestSourceCodeGuardrails:
- """Regression guardrails: raw color 8 must not reappear in source.
-
- These complement the behavioral tests above — they catch regressions
- introduced by copy-paste of the old pattern.
- """
-
- _RAW_COLOR_8_PATTERN = re.compile(r'init_pair\(\d+,\s*8\s*,')
-
-
diff --git a/tests/hermes_cli/test_curses_ui_fuzzy_rank.py b/tests/hermes_cli/test_curses_ui_fuzzy_rank.py
index 6940793ab16..2432dbe8548 100644
--- a/tests/hermes_cli/test_curses_ui_fuzzy_rank.py
+++ b/tests/hermes_cli/test_curses_ui_fuzzy_rank.py
@@ -1,11 +1,8 @@
"""Tests for the ranked fuzzy scorer used by the searchable curses pickers."""
from hermes_cli.curses_ui import (
_SearchState,
- _filter_indices,
_fuzzy_score,
_handle_active_search_key,
- _is_boundary,
- _token_score,
)
@@ -17,25 +14,11 @@ class _FakeCurses:
-def test_scorer_matches_typescript_reference():
- """Score parity with ui-tui/web fuzzy.ts. These exact values are produced
- by the TS fuzzyScoreMulti for the same inputs (verified via a cross-language
- harness); keep the Python port byte-identical so all three surfaces rank
- consistently. If you change the scoring constants, update the TS copies too.
- """
- cases = {
- ("gpt-4o", "g4o"): 15.94,
- ("gpt-4o", "gpt"): 28.94,
- ("claude-sonnet-4", "sonnet"): 33.85,
- ("claude-sonnet-4", "clad snnt"): 30.70,
- ("GptO", "gpto"): 57.96, # camelCase boundary on the original-case 'O'
- }
- for (label, query), expected in cases.items():
- score = _fuzzy_score(label, query)
- assert score is not None
- assert round(score, 2) == expected, f"{label!r}/{query!r}: {score} != {expected}"
-
-
+def test_scorer_ranks_prefix_and_boundary_matches_higher():
+ """Contiguous / word-boundary matches outrank scattered ones; non-subsequences never match."""
+ assert _fuzzy_score("gpt-4o", "gpt") > _fuzzy_score("gpt-4o", "g4o")
+ assert _fuzzy_score("claude-sonnet-4", "sonnet") > _fuzzy_score("claude-sonnet-4", "clad snnt")
+ assert _fuzzy_score("gpt-4o", "zzz") is None
def test_esc_clears_query_and_signals_changed():
diff --git a/tests/hermes_cli/test_custom_provider_context_feedback.py b/tests/hermes_cli/test_custom_provider_context_feedback.py
index 8e2278f57f5..c7f0f15be31 100644
--- a/tests/hermes_cli/test_custom_provider_context_feedback.py
+++ b/tests/hermes_cli/test_custom_provider_context_feedback.py
@@ -14,9 +14,8 @@ from hermes_cli import model_setup_flows_custom as flows
def test_blank_context_length_reports_detection_outcome(capsys, resolved, expect):
from agent.model_metadata import DEFAULT_FALLBACK_CONTEXT
with patch("agent.model_metadata.get_model_context_length",
- return_value=resolved if resolved is not None else DEFAULT_FALLBACK_CONTEXT) as probe:
+ return_value=resolved if resolved is not None else DEFAULT_FALLBACK_CONTEXT):
flows._report_context_length_detection("some-model", "http://localhost:8000/v1", "k")
- probe.assert_called_once_with("some-model", base_url="http://localhost:8000/v1", api_key="k")
assert expect in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_custom_provider_context_length.py b/tests/hermes_cli/test_custom_provider_context_length.py
index 5a34641dcf6..43550045946 100644
--- a/tests/hermes_cli/test_custom_provider_context_length.py
+++ b/tests/hermes_cli/test_custom_provider_context_length.py
@@ -204,18 +204,6 @@ class TestGetModelContextLengthHonorsOverride:
assert ctx == DEFAULT_FALLBACK_CONTEXT
-class TestContextProbeTiers:
- def test_256k_is_top_tier_and_default(self):
- """The stepdown probe starts at 256K and 256K is the new default."""
- from agent.model_metadata import CONTEXT_PROBE_TIERS, DEFAULT_FALLBACK_CONTEXT
-
- assert CONTEXT_PROBE_TIERS[0] == 256_000
- assert DEFAULT_FALLBACK_CONTEXT == 256_000
- # Tiers still descend monotonically
- for a, b in zip(CONTEXT_PROBE_TIERS, CONTEXT_PROBE_TIERS[1:]):
- assert a > b, f"tiers must strictly descend, got {a} then {b}"
- # 128K is still a tier (users relying on it probe-down get there)
- assert 128_000 in CONTEXT_PROBE_TIERS
def test_override_honored_when_caller_passes_no_custom_providers(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_custom_provider_extra_headers.py b/tests/hermes_cli/test_custom_provider_extra_headers.py
index c0e668e0e02..d80f0a4383d 100644
--- a/tests/hermes_cli/test_custom_provider_extra_headers.py
+++ b/tests/hermes_cli/test_custom_provider_extra_headers.py
@@ -55,16 +55,6 @@ def test_normalize_entry_drops_invalid_extra_headers():
assert "extra_headers" not in normalized
-def test_normalize_entry_stringifies_values_and_skips_none():
- normalized = _normalize_custom_provider_entry(
- {
- "name": "my-proxy",
- "base_url": "https://llm.internal.example.com/v1",
- "extra_headers": {"X-Int": 7, "X-None": None},
- }
- )
- assert normalized is not None
- assert normalized["extra_headers"] == {"X-Int": "7"}
def test_get_custom_provider_extra_headers_matches_base_url():
diff --git a/tests/hermes_cli/test_custom_provider_model_switch.py b/tests/hermes_cli/test_custom_provider_model_switch.py
index 43edf559d1b..99b04a50285 100644
--- a/tests/hermes_cli/test_custom_provider_model_switch.py
+++ b/tests/hermes_cli/test_custom_provider_model_switch.py
@@ -151,12 +151,7 @@ class TestCustomProviderModelSwitch:
patch("builtins.print"):
_model_flow_named_custom({}, provider_info)
- mock_fetch.assert_called_once_with(
- "sk-live-example-provider",
- "https://api.example-provider.test/v1",
- headers=None,
- timeout=8.0,
- )
+ assert mock_fetch.call_args.args[0] == "sk-live-example-provider"
config = yaml.safe_load(config_path.read_text()) or {}
assert config["model"]["api_key"] == "${EXAMPLE_PROVIDER_API_KEY}"
assert config["custom_providers"][0]["api_key"] == "${EXAMPLE_PROVIDER_API_KEY}"
diff --git a/tests/hermes_cli/test_cwd_env_respect.py b/tests/hermes_cli/test_cwd_env_respect.py
deleted file mode 100644
index 49f0e603964..00000000000
--- a/tests/hermes_cli/test_cwd_env_respect.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""Tests for CLI/TUI CWD resolution in load_cli_config().
-
-Rules:
-- Local backend CLI/TUI: always os.getcwd(), ignoring config and inherited env.
-- Non-local with placeholder: pop cwd for backend default.
-- Non-local with explicit path: keep as-is.
-"""
-
-
-_CWD_PLACEHOLDERS = (".", "auto", "cwd")
-
-
-def _resolve_cwd(terminal_config: dict, defaults: dict, env: dict):
- """Mirror the CWD resolution logic from cli.py load_cli_config()."""
- effective_backend = terminal_config.get("env_type", "local")
-
- if effective_backend == "local":
- terminal_config["cwd"] = "/fake/getcwd"
- defaults["terminal"]["cwd"] = terminal_config["cwd"]
- elif terminal_config.get("cwd") in _CWD_PLACEHOLDERS:
- terminal_config.pop("cwd", None)
-
- # Bridge: TERMINAL_CWD always exported in CLI, skipped in gateway
- _is_gateway = env.get("_HERMES_GATEWAY") == "1"
- if "cwd" in terminal_config:
- if _is_gateway:
- pass # don't touch env
- else:
- env["TERMINAL_CWD"] = str(terminal_config["cwd"])
-
- return env.get("TERMINAL_CWD", "")
-
-
-class TestLocalBackendCli:
- """Local backend always uses os.getcwd()."""
-
- def test_explicit_config_ignored(self):
- env = {}
- tc = {"cwd": "/explicit/path", "env_type": "local"}
- d = {"terminal": {"cwd": "/explicit/path"}}
- assert _resolve_cwd(tc, d, env) == "/fake/getcwd"
-
- def test_inherited_env_overwritten(self):
- env = {"TERMINAL_CWD": "/parent/hermes"}
- tc = {"cwd": "/home/user", "env_type": "local"}
- d = {"terminal": {"cwd": "/home/user"}}
- assert _resolve_cwd(tc, d, env) == "/fake/getcwd"
-
- def test_placeholder_resolved(self):
- env = {}
- tc = {"cwd": "."}
- d = {"terminal": {"cwd": "."}}
- assert _resolve_cwd(tc, d, env) == "/fake/getcwd"
-
- def test_env_and_no_config_file(self):
- env = {"TERMINAL_CWD": "/stale/value"}
- tc = {"cwd": ".", "env_type": "local"}
- d = {"terminal": {"cwd": "."}}
- assert _resolve_cwd(tc, d, env) == "/fake/getcwd"
-
-
-class TestNonLocalBackends:
- """Non-local backends use config or per-backend defaults."""
-
- def test_placeholder_popped(self):
- env = {}
- tc = {"cwd": ".", "env_type": "docker"}
- d = {"terminal": {"cwd": "."}}
- assert _resolve_cwd(tc, d, env) == ""
-
- def test_explicit_path_kept(self):
- env = {}
- tc = {"cwd": "/srv/app", "env_type": "ssh"}
- d = {"terminal": {"cwd": "/srv/app"}}
- assert _resolve_cwd(tc, d, env) == "/srv/app"
-
- def test_auto_placeholder_popped(self):
- env = {}
- tc = {"cwd": "auto", "env_type": "modal"}
- d = {"terminal": {"cwd": "auto"}}
- assert _resolve_cwd(tc, d, env) == ""
-
-
-class TestGatewayLazyImport:
- """Gateway lazy import of cli.py must not clobber TERMINAL_CWD."""
-
- def test_gateway_cwd_preserved(self):
- env = {"_HERMES_GATEWAY": "1", "TERMINAL_CWD": "/home/user/project"}
- tc = {"cwd": "/home/user", "env_type": "local"}
- d = {"terminal": {"cwd": "/home/user"}}
- result = _resolve_cwd(tc, d, env)
- assert result == "/home/user/project"
-
- def test_cli_overwrites_stale_env(self):
- env = {"TERMINAL_CWD": "/stale/from/dotenv"}
- tc = {"cwd": "/home/user", "env_type": "local"}
- d = {"terminal": {"cwd": "/home/user"}}
- result = _resolve_cwd(tc, d, env)
- assert result == "/fake/getcwd"
diff --git a/tests/hermes_cli/test_dashboard_admin_endpoints.py b/tests/hermes_cli/test_dashboard_admin_endpoints.py
index 88c32414872..8aead9eac04 100644
--- a/tests/hermes_cli/test_dashboard_admin_endpoints.py
+++ b/tests/hermes_cli/test_dashboard_admin_endpoints.py
@@ -142,16 +142,12 @@ class TestMcpEndpoints:
assert error in response.json()["detail"]
-
-
-
class TestCredentialPoolEndpoints:
@pytest.fixture(autouse=True)
def _setup(self, _isolate_hermes_home):
self.client, _ = _client()
-
def test_env_seeded_delete_stays_deleted(self):
"""#55217: DELETE must suppress the source or load_pool() resurrects it.
@@ -213,8 +209,6 @@ class TestCredentialPoolEndpoints:
assert sources == ["env:OPENROUTER_API_KEY", "manual"]
-
-
class TestMemoryEndpoints:
@pytest.fixture(autouse=True)
def _setup(self, _isolate_hermes_home):
@@ -352,7 +346,6 @@ class TestWebhookEndpoints:
assert subs[0]["script"] == "todoist_filter.py"
def test_enable_platform_starts_gateway_restart(self, monkeypatch):
- import hermes_cli.web_server as ws
from hermes_cli.config import load_config
_web_server_gateway._ACTION_PROCS.pop("gateway-restart", None)
@@ -385,7 +378,6 @@ class TestWebhookEndpoints:
def test_enable_platform_reuses_inflight_gateway_restart(self, monkeypatch):
- import hermes_cli.web_server as ws
from hermes_cli.config import load_config
_web_server_gateway._ACTION_PROCS.pop("gateway-restart", None)
@@ -419,7 +411,6 @@ class TestOpsEndpoints:
self.client, _ = _client()
-
def test_hooks_list_reads_config(self):
from hermes_cli.config import load_config, save_config
@@ -468,35 +459,6 @@ class TestOpsEndpoints:
assert not [h for h in hooks2 if h["command"] == "/bin/echo created"]
-
-class TestSystemStatsEndpoint:
- @pytest.fixture(autouse=True)
- def _setup(self, _isolate_hermes_home):
- self.client, _ = _client()
-
- def test_stats_shape(self):
- r = self.client.get("/api/system/stats")
- assert r.status_code == 200
- s = r.json()
- # Identity fields always present (stdlib-sourced).
- for key in ("os", "arch", "hostname", "python_version", "hermes_version"):
- assert key in s and s[key]
- # psutil flag tells the UI whether the richer metrics are populated.
- assert "psutil" in s
-
-
-class TestCuratorEndpoints:
- @pytest.fixture(autouse=True)
- def _setup(self, _isolate_hermes_home):
- self.client, _ = _client()
-
-
-class TestPortalEndpoint:
- @pytest.fixture(autouse=True)
- def _setup(self, _isolate_hermes_home):
- self.client, _ = _client()
-
-
class TestSessionManagementEndpoints:
@pytest.fixture(autouse=True)
def _setup(self, _isolate_hermes_home):
@@ -508,28 +470,6 @@ class TestSessionManagementEndpoints:
db.close()
- def test_stats_source_counts_use_direct_aggregate(self, monkeypatch):
- """Source badges must not materialise rich session rows.
-
- Large stores can have thousands of sessions. The stats endpoint only
- needs grouped counts, so it should call ``session_count_by_source``
- instead of ``list_sessions_rich`` and build preview/last-active rows
- just to count source labels.
- """
- from hermes_state import SessionDB
-
- def fail_list_sessions_rich(self, *args, **kwargs):
- raise AssertionError("stats should use grouped source counts, not list_sessions_rich")
-
- monkeypatch.setattr(SessionDB, "list_sessions_rich", fail_list_sessions_rich)
-
- r = self.client.get("/api/sessions/stats")
- assert r.status_code == 200
- body = r.json()
- assert body["by_source"]["cli"] >= 1
-
-
-
def test_prune_attr_filter_suppresses_default_cutoff(self):
# An attribute filter without an explicit older_than_days matches all
# ages (mirrors the CLI: any filter disables the implicit 90-day
@@ -580,13 +520,6 @@ class TestSessionManagementEndpoints:
db.close()
-
-class TestSkillsHubSearchEndpoint:
- @pytest.fixture(autouse=True)
- def _setup(self, _isolate_hermes_home):
- self.client, _ = _client()
-
-
class _FakeMeta:
"""Minimal SkillMeta stand-in for monkeypatched source search."""
@@ -803,33 +736,6 @@ class TestSkillsHubScanEndpoint:
assert body["findings"][0]["file"] == "SKILL.md"
-class TestWebhookToggleEndpoint:
- @pytest.fixture(autouse=True)
- def _setup(self, _isolate_hermes_home):
- self.client, _ = _client()
- # Enable the webhook platform so a subscription can be created.
- from hermes_cli.config import load_config, save_config
-
- cfg = load_config()
- cfg.setdefault("platforms", {})["webhook"] = {
- "enabled": True,
- "extra": {"host": "0.0.0.0", "port": 8644},
- }
- save_config(cfg)
-
-
-class TestAdminEndpointsAuthGate:
- """Every admin endpoint must sit behind the dashboard session-token gate."""
-
- @pytest.fixture(autouse=True)
- def _setup(self, _isolate_hermes_home):
- from starlette.testclient import TestClient
- from hermes_cli.web_server import app
-
- # No session header → must be rejected.
- self.client = TestClient(app)
-
-
class TestUpdateCheckEndpoint:
"""``GET /api/hermes/update/check`` reports availability without applying.
@@ -843,7 +749,6 @@ class TestUpdateCheckEndpoint:
self.client, _ = _client()
def test_git_install_reports_behind_count(self, monkeypatch):
- import hermes_cli.web_server as ws
monkeypatch.setattr(_cfg_mod, "detect_install_method", lambda *a, **k: "git")
# Stub the shared checker so the contract is deterministic (no network).
@@ -870,9 +775,7 @@ class TestUpdateCheckEndpoint:
assert body["can_apply"] is True
-
def test_managed_runtime_dashboard_is_not_applyable(self, monkeypatch):
- import hermes_cli.web_server as ws
monkeypatch.setattr(_web_server_files, "_dashboard_local_update_managed_externally", lambda: True)
monkeypatch.setattr(
@@ -891,8 +794,6 @@ class TestUpdateCheckEndpoint:
assert "managed outside this dashboard" in body["message"]
-
-
class TestDebugShareEndpoint:
"""POST /api/ops/debug-share returns the paste URLs synchronously so the
dashboard can render them as copyable links (not a backgrounded log tail)."""
@@ -954,7 +855,6 @@ class TestDebugShareEndpoint:
assert r.status_code == 502
-
class TestToolsConfigEndpoints:
"""Provider selection, API-key save, and post-setup spawn for toolsets —
the dashboard surface that replicates the `hermes tools` configurator."""
@@ -964,8 +864,6 @@ class TestToolsConfigEndpoints:
self.client, self.header = _client()
-
-
def test_save_env_writes_key_and_validates_allowlist(self):
from hermes_cli.config import get_env_value
@@ -992,7 +890,6 @@ class TestToolsConfigEndpoints:
assert get_env_value(key) == "test-secret-123"
-
def test_post_setup_unknown_toolset_400(self):
r = self.client.post(
"/api/tools/toolsets/not_a_toolset/post-setup",
@@ -1001,8 +898,6 @@ class TestToolsConfigEndpoints:
assert r.status_code == 400
-
-
# ---------------------------------------------------------------------------
# _spawn_hermes_action env scrubbing (#52470)
# ---------------------------------------------------------------------------
@@ -1173,42 +1068,6 @@ def test_named_profile_action_isolates_parent_env_and_loads_target_env(monkeypat
# Desktop lifespan reaps orphan gateways at serve startup (#77276)
# ---------------------------------------------------------------------------
-def test_desktop_lifespan_reaps_orphan_gateways_on_startup(
- monkeypatch, _isolate_hermes_home
-):
- """Starting a Desktop serve backend should reap orphan gateways left by a
- previous serve session before forking a fresh one (#77276).
-
- Graceful shutdown reaps the managed child, but an abnormal exit reparents
- the old gateway to launchd (PPID=1) where it keeps holding the QQ
- WebSocket. The lifespan calls _reap_unsupervised_gateway_orphans() once at
- startup under HERMES_DESKTOP=1 so the stale orphan is cleared first.
- """
- import hermes_cli.web_server as ws
-
- called = []
-
- def _fake_reap():
- called.append(True)
- return True
-
- monkeypatch.setenv("HERMES_DESKTOP", "1")
- # Keep the lifespan cheap: don't re-import the gateway module or spin up the
- # real cron scheduler thread.
- monkeypatch.setattr(ws, "_warm_gateway_module", lambda: None)
- monkeypatch.setattr(ws, "_start_desktop_cron_ticker", lambda *_args: None)
- # web_server imports the reaper lazily from hermes_cli.gateway, so patch it
- # on that module.
- import hermes_cli.gateway as g
-
- monkeypatch.setattr(g, "_reap_unsupervised_gateway_orphans", _fake_reap)
-
- client, _header = _client()
- with client:
- pass
-
- assert called == [True]
-
def test_desktop_lifespan_terminates_managed_gateway_restart(monkeypatch):
"""A Desktop-owned gateway child must not survive its serve backend."""
diff --git a/tests/hermes_cli/test_dashboard_auth_gate.py b/tests/hermes_cli/test_dashboard_auth_gate.py
index 56f60eb2dab..d339b86342e 100644
--- a/tests/hermes_cli/test_dashboard_auth_gate.py
+++ b/tests/hermes_cli/test_dashboard_auth_gate.py
@@ -20,26 +20,6 @@ from starlette.websockets import WebSocketDisconnect
from hermes_cli import web_server
-def client_loopback():
- # Pin the bound-host state for host_header_middleware so requests with
- # default Host: testclient pass the DNS-rebinding check. TestClient
- # sends Host: testserver by default, but our middleware accepts the
- # loopback aliases when bound_host is loopback.
- prev_host = getattr(web_server.app.state, "bound_host", None)
- prev_port = getattr(web_server.app.state, "bound_port", None)
- web_server.app.state.bound_host = "127.0.0.1"
- web_server.app.state.bound_port = 9119
- client = TestClient(web_server.app, base_url="http://127.0.0.1:9119")
- yield client
- web_server.app.state.bound_host = prev_host
- web_server.app.state.bound_port = prev_port
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# should_require_auth predicate (Task 0.2)
# ---------------------------------------------------------------------------
@@ -64,23 +44,6 @@ def test_should_require_auth_truth_table(host, allow_public, expected):
assert should_require_auth(host, allow_public) is expected
-def test_empty_provider_login_page_shows_supported_auth_paths():
- from hermes_cli.dashboard_auth import clear_providers
- from hermes_cli.dashboard_auth.login_page import render_login_html
-
- clear_providers()
- html = render_login_html()
-
- assert "--insecure" not in html
- assert "username/password provider" in html
- assert "OAuth provider" in html
- assert "127.0.0.1" in html
- assert "SSH tunnel" in html
- assert "Tailscale" in html
- assert (
- 'href="https://hermes-agent.nousresearch.com/docs/'
- 'user-guide/features/web-dashboard#authentication-gated-mode"'
- ) in html
# ---------------------------------------------------------------------------
@@ -93,7 +56,6 @@ def _stub_uvicorn_run(monkeypatch):
returns immediately (rather than blocking on the event loop). Returns the dict
that will capture the keyword args.
"""
- import asyncio
import contextlib
import uvicorn
captured: dict = {"kwargs": {}}
@@ -142,6 +104,8 @@ def _stub_uvicorn_run(monkeypatch):
pass
monkeypatch.setattr(uvicorn, "Config", _FakeConfig)
+ # Nothing binds here: never let a live dashboard on the host's 9119 trip the pre-bind probe.
+ monkeypatch.setattr(web_server, "_port_bind_conflict", lambda *a, **k: False)
monkeypatch.setattr(uvicorn, "Server", lambda config: _FakeServer())
return captured
@@ -468,44 +432,6 @@ def test_desktop_ssh_backend_serves_session_token_requests_despite_public_url(mo
clear_providers()
-def test_loopback_public_url_fail_closed_message_is_actionable(monkeypatch):
- """The refusal must name public_url, print its value, and give both exits.
-
- Upgrade compatibility: an operator with a stale dashboard.public_url and
- no auth provider must not face a mystery-locked dashboard — the error
- text IS the mitigation.
- """
- from hermes_cli.dashboard_auth import clear_providers
-
- monkeypatch.setenv(
- "HERMES_DASHBOARD_PUBLIC_URL",
- "https://dashboard.example.test:9443",
- )
- clear_providers()
- _stub_uvicorn_run(monkeypatch)
- _restore_app_state_after_test(
- monkeypatch,
- "auth_required",
- "bound_host",
- "bound_port",
- "trusted_public_hosts",
- )
-
- with pytest.raises(SystemExit) as exc:
- web_server.start_server(
- host="127.0.0.1", port=9119,
- open_browser=False, allow_public=False,
- )
- msg = str(exc.value)
- # Names the trigger and its value.
- assert "dashboard.public_url" in msg
- assert "https://dashboard.example.test:9443" in msg
- # Exit 1: configure auth.
- assert "basic_auth" in msg
- assert "hermes dashboard register" in msg
- # Exit 2: remove public_url to restore local-only mode.
- assert "remove dashboard.public_url" in msg
- assert "LOCAL-ONLY" in msg
@pytest.mark.parametrize("host,public_url,expected", [