The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py12 (287 removed)
teknium196c9cc9ac6ff
diff --git a/tests/hermes_cli/test_linux_desktop_entry.py b/tests/hermes_cli/test_linux_desktop_entry.pyindex 58857fb08dc..9799417e161 100644--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@ -302,7 +302,6 @@ def test_exec_never_persists_a_bare_interpreter_command():"""The `python -m hermes_cli.main` relaunch context must not write`Exec=<python> desktop` — a command line no DE can run."""- import sysroot = _make_project(tmp_path)wrapper = tmp_path / "installed" / "bin" / "hermes"@@ -614,7 +613,6 @@ def test_known_wrapper_candidates_cover_installer_layouts(candidate. Locking these in protects against silent regressions inthe stripped-PATH probe path."""- import ossentinel_home = "/home/__sentinel_home__"monkeypatch.setenv("HOME", sentinel_home)@@ -704,16 +702,6 @@ def _stub_tools(monkeypatch, available: "set[str]") -> "list[list[str]]":return ran-def test_refresh_runs_kbuildsycoca6_when_present(monkeypatch, tmp_path):- ran = _stub_tools(monkeypatch, {"update-desktop-database", "kbuildsycoca6"})-- tools = lde.refresh_desktop_databases(tmp_path)-- assert tools == ["update-desktop-database", "kbuildsycoca6"]- assert ran == [- ["/usr/bin/update-desktop-database", str(tmp_path)],- ["/usr/bin/kbuildsycoca6", "--noincremental"],- ]def test_refresh_falls_back_to_kbuildsycoca5(monkeypatch, tmp_path):@@ -752,18 +740,6 @@ def test_run_quiet_swallows_missing_binary(tmp_path):assert lde._run_quiet([str(tmp_path / "definitely-not-a-binary")]) is False-def test_exec_arg_quoting_handles_spaces(tmp_path, xdg_home, monkeypatch):- root = _make_project(tmp_path)- spaced = tmp_path / "my apps" / "hermes"- spaced.parent.mkdir()- spaced.write_text("", encoding="utf-8")- monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: str(spaced))- monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])-- entry = lde.install_desktop_entry(root)- exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]-- assert exec_line == f'"{spaced}" desktop'@pytest.mark.skipif(@@ -801,32 +777,6 @@ def test_running_interpreter_resolves_plain_interpreter(monkeypatch):assert Path(out).is_absolute()-def test_can_import_probe_runs_and_caches(tmp_path):- """The probe executes the real interpreter and memoizes the answer.-- Asserts the two things that hold on ANY host: the probe returns a- definite boolean for a real interpreter (not None, not an exception- path), and the per-path cache is populated so the second call pays- no subprocess. Host-dependent capability itself (True vs False) is- deliberately NOT asserted - a CI host with hermes pip-installed- system-wide would legitimately answer True.- """- import time-- real = Path("/usr/bin/python3")- if not real.exists():- pytest.skip("no system python to probe")- lde._probe_cache.pop(str(real), None)- try:- first = lde._can_import_hermes_cli(real)- assert isinstance(first, bool)- assert str(real) in lde._probe_cache- t0 = time.monotonic()- second = lde._can_import_hermes_cli(real)- assert second is first- assert time.monotonic() - t0 < 0.05 # cache hit: no subprocess- finally:- lde._probe_cache.pop(str(real), None)def test_exec_falls_back_to_running_interpreter_when_probe_fails(@@ -1023,7 +973,6 @@ def test_probe_skips_wrapper_with_escaping_python_shebang(The shebang-safety gate skips it; the module fallback wins. Ideacredited to autumn8's #92122 rung-2 check."""- import sys as _sroot = _make_project(tmp_path)repo_script = root / "hermes"diff --git a/tests/hermes_cli/test_linux_sandbox_fixup.py b/tests/hermes_cli/test_linux_sandbox_fixup.pyindex 37d9d9107d0..df0acff9c00 100644--- a/tests/hermes_cli/test_linux_sandbox_fixup.py+++ b/tests/hermes_cli/test_linux_sandbox_fixup.py@@ -13,24 +13,22 @@ from __future__ import annotationsimport statimport subprocess-import sysfrom unittest.mock import patch+import pytest+from hermes_cli import main_desktop+# Linux-only subject: run on the real Linux host instead of faking sys.platform.+pytestmark = pytest.mark.linux_only-class TestDesktopLinuxUsernsSandboxAvailable:- def test_false_on_non_linux(self, monkeypatch):- monkeypatch.setattr(sys, "platform", "darwin")- assert main_desktop._desktop_linux_userns_sandbox_available() is False+class TestDesktopLinuxUsernsSandboxAvailable:def test_false_when_unshare_is_missing(self, monkeypatch):- monkeypatch.setattr(sys, "platform", "linux")with patch.object(main_desktop.shutil, "which", return_value=None):assert main_desktop._desktop_linux_userns_sandbox_available() is Falsedef test_true_when_probe_succeeds(self, monkeypatch):- monkeypatch.setattr(sys, "platform", "linux")with patch.object(main_desktop.shutil, "which", return_value="/usr/bin/unshare"), \patch.object(main_desktop.subprocess, "run") as run:run.return_value.returncode = 0@@ -41,14 +39,12 @@ class TestDesktopLinuxUsernsSandboxAvailable:def test_false_when_probe_fails(self, monkeypatch):"""EPERM from the kernel (userns disabled or AppArmor-restricted)."""- monkeypatch.setattr(sys, "platform", "linux")with patch.object(main_desktop.shutil, "which", return_value="/usr/bin/unshare"), \patch.object(main_desktop.subprocess, "run") as run:run.return_value.returncode = 1assert main_desktop._desktop_linux_userns_sandbox_available() is Falsedef test_false_when_probe_raises(self, monkeypatch):- monkeypatch.setattr(sys, "platform", "linux")with patch.object(main_desktop.shutil, "which", return_value="/usr/bin/unshare"), \patch.object(main_desktop.subprocess,@@ -76,7 +72,6 @@ class TestDesktopLinuxSandboxFixup:This is the .desktop-launch regression: no TTY means sudo cannotprompt, so reaching the sudo path at all kills the launch."""- monkeypatch.setattr(sys, "platform", "linux")exe = self._fake_packaged_app(tmp_path)with patch.object(main_desktop, "_desktop_linux_userns_sandbox_available", return_value=True@@ -87,7 +82,6 @@ class TestDesktopLinuxSandboxFixup:def test_restricted_host_without_sudo_still_fails(self, monkeypatch, tmp_path):"""The pre-existing strict path is preserved when userns is unusable."""- monkeypatch.setattr(sys, "platform", "linux")exe = self._fake_packaged_app(tmp_path)with patch.object(main_desktop, "_desktop_linux_userns_sandbox_available", return_value=False@@ -97,7 +91,6 @@ class TestDesktopLinuxSandboxFixup:def test_root_owned_setuid_helper_short_circuits(self, monkeypatch, tmp_path):"""A correctly configured helper wins before the userns probe runs."""- monkeypatch.setattr(sys, "platform", "linux")exe = self._fake_packaged_app(tmp_path)real_lstat = (exe.parent / "chrome-sandbox").lstat()@@ -128,7 +121,6 @@ class TestDesktopLinuxNeedsDisableSetuidSandbox:return exedef test_true_for_user_owned_helper_when_userns_works(self, monkeypatch, tmp_path):- monkeypatch.setattr(sys, "platform", "linux")exe = self._fake_packaged_app(tmp_path)with patch.object(main_desktop, "_desktop_linux_userns_sandbox_available", return_value=True@@ -136,7 +128,6 @@ class TestDesktopLinuxNeedsDisableSetuidSandbox:assert main_desktop._desktop_linux_needs_disable_setuid_sandbox(exe) is Truedef test_false_for_root_owned_setuid_helper(self, monkeypatch, tmp_path):- monkeypatch.setattr(sys, "platform", "linux")exe = self._fake_packaged_app(tmp_path)real_lstat = (exe.parent / "chrome-sandbox").lstat()@@ -155,7 +146,6 @@ class TestDesktopLinuxNeedsDisableSetuidSandbox:probe.assert_not_called()def test_false_when_helper_missing(self, monkeypatch, tmp_path):- monkeypatch.setattr(sys, "platform", "linux")unpacked = tmp_path / "linux-unpacked"unpacked.mkdir()exe = unpacked / "Hermes"diff --git a/tests/hermes_cli/test_load_progress.py b/tests/hermes_cli/test_load_progress.pyindex ed861c79e5a..c7362dd1001 100644--- a/tests/hermes_cli/test_load_progress.py+++ b/tests/hermes_cli/test_load_progress.py@@ -10,7 +10,6 @@ status route's `loading` field and the chat's load notice."""from __future__ import annotationsimport json-import timeimport hermes_cli.local_runtime.load_progress as lp@@ -123,28 +122,6 @@ def test_load_notice_for_managed_model(tmp_path, monkeypatch):assert _managed_local_load_notice(_Agent(), {"model": "Elsewhere"}) is None-def test_load_notice_matches_desktop_wait_filter():- """The notices must pass the desktop's providerWaitText regex and parse- under parseModelLoadWait's shapes — pinned here as plain string- contracts so the two sides can't drift silently."""- import re-- accept = r"^(?:⏳|⚠|↻|⚙)\s*(?:waiting on|loading|processing prompt|no (?:output|response)|model returned)"-- load = "⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 43% (responses start once the model is loaded)"- assert re.match(accept, load)- m = re.match(r"^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%", load)- assert m and m.group(1) == "Qwen3.6-35B-A3B-UD-Q4_K_M" and m.group(2) == "43"-- prefill = "⚙ processing prompt — 31%"- assert re.match(accept, prefill)- p = re.match(r"^⚙\s*processing prompt(?:\s+—\s+(\d{1,3})%)?", prefill)- assert p and p.group(1) == "31"-- bare = "⚙ processing prompt"- assert re.match(accept, bare)- b = re.match(r"^⚙\s*processing prompt(?:\s+—\s+(\d{1,3})%)?", bare)- assert b and b.group(1) is None# ── prefill progress ─────────────────────────────────────────diff --git a/tests/hermes_cli/test_local_abandoned_requests.py b/tests/hermes_cli/test_local_abandoned_requests.pyindex eea34600367..5e8c99d882d 100644--- a/tests/hermes_cli/test_local_abandoned_requests.py+++ b/tests/hermes_cli/test_local_abandoned_requests.py@@ -20,7 +20,6 @@ Three contracts, one per failure link:from __future__ import annotationsimport json-import subprocessimport typesimport pytest@@ -111,65 +110,8 @@ class _FakeChild:self.killed = True-def test_terminate_tree_terminates_children_too(monkeypatch):- children = [_FakeChild(101), _FakeChild(102)]- class _FakeParentProc:- def __init__(self, pid):- self.pid = pid- def children(self, recursive=False):- assert recursive is True- return children-- import psutil- fake_psutil = types.SimpleNamespace(Process=_FakeParentProc,- TimeoutExpired=psutil.TimeoutExpired, Error=psutil.Error)- monkeypatch.setitem(__import__("sys").modules, "psutil", fake_psutil)-- class _FakeRouter:- pid = 4242- terminated = False-- def terminate(self):- _FakeRouter.terminated = True-- def wait(self, timeout=None):- return 0-- def poll(self):- return None-- LlamaServerSupervisor._terminate_tree(_FakeRouter())- assert _FakeRouter.terminated- assert all(c.terminated for c in children), (- "router children orphaned on stop — each holds GiB of VRAM")---def test_terminate_tree_survives_missing_psutil(monkeypatch):- import builtins-- real_import = builtins.__import__-- def _no_psutil(name, *a, **k):- if name == "psutil":- raise ImportError("nope")- return real_import(name, *a, **k)-- monkeypatch.setattr(builtins, "__import__", _no_psutil)-- class _FakeRouter:- pid = 4242- terminated = False-- def terminate(self):- _FakeRouter.terminated = True-- def wait(self, timeout=None):- return 0-- LlamaServerSupervisor._terminate_tree(_FakeRouter())- assert _FakeRouter.terminated # router still stopped without psutildef test_reap_orphans_kills_only_our_parentless_binaries(tmp_path, monkeypatch):diff --git a/tests/hermes_cli/test_local_recommendation_policy.py b/tests/hermes_cli/test_local_recommendation_policy.pyindex dd039d4328f..7959807070a 100644--- a/tests/hermes_cli/test_local_recommendation_policy.py+++ b/tests/hermes_cli/test_local_recommendation_policy.py@@ -37,7 +37,6 @@ def test_small_discrete_cards_have_no_automatic_recommendation():def test_24gb_discrete_card_recommends_resident_qwen_27b():picked = recommended_entry(_discrete(24))assert picked is not None- assert picked[0].id == "qwen3.8-27b"assert picked[1] == "best-quality-resident"choice = select_variant(picked[0], _discrete(24))assert choice is not None and choice.zero_spilldiff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.pyindex d5580fa62c7..0f65712ec44 100644--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@ -14,7 +14,6 @@ import loggingimport osimport threadingfrom http.server import BaseHTTPRequestHandler, HTTPServer-from pathlib import Pathimport pytest@@ -895,16 +894,6 @@ def test_external_server_on_a_configured_detect_port_is_used(tmp_path, monkeypatassert result.base_url == f"http://127.0.0.1:{port}/v1"-def test_local_runtime_config_defaults_shape():- """Contract: the section exists, is off by default, and carries no- context/VRAM knobs (design: constants, not knobs)."""- from hermes_cli.config_defaults import DEFAULT_CONFIG-- cfg = DEFAULT_CONFIG["local_runtime"]- assert cfg["enabled"] is False- assert isinstance(cfg["tag"], str) and cfg["tag"].startswith("b")- forbidden = [k for k in cfg if "context" in k or "ctx" in k or "vram" in k or "kv" in k]- assert forbidden == [], f"policy constants leaked into config: {forbidden}"# ── bootstrap contracts ──────────────────────────────────────diff --git a/tests/hermes_cli/test_local_runtime_updates.py b/tests/hermes_cli/test_local_runtime_updates.pyindex 8408968775a..3f07bfdb6f3 100644--- a/tests/hermes_cli/test_local_runtime_updates.py+++ b/tests/hermes_cli/test_local_runtime_updates.py@@ -43,24 +43,16 @@ def test_installed_tags_newest_first(hermes_home):assert installed_tags() == ["b10412", "b10290"]-def test_default_tag_flows_from_default_config(hermes_home):- """Unpinned users inherit the Hermes-release default (deep-merge);- the shipped default must be a plausible rolling tag."""- from hermes_cli.config import load_config- from hermes_cli.config_defaults import DEFAULT_CONFIG-- default_tag = DEFAULT_CONFIG["local_runtime"]["tag"]- assert default_tag.startswith("b") and default_tag.lstrip("b").isdigit()- assert load_config()["local_runtime"]["tag"] == default_tag@pytest.mark.parametrize("pin", [None, "b10679", "b10412"])-def test_preferred_b10964_update_offer_respects_explicit_pins(hermes_home, pin):+def test_default_tag_update_offer_respects_explicit_pins(hermes_home, pin):"""Existing unpinned installs get the shipped upgrade; user pins win."""from fastapi.testclient import TestClientfrom hermes_cli import web_serverfrom hermes_cli.config import load_config+ from hermes_cli.config_defaults import DEFAULT_CONFIGruntime = {"enabled": True}if pin is not None:@@ -74,7 +66,7 @@ def test_preferred_b10964_update_offer_respects_explicit_pins(hermes_home, pin):response = client.get("/api/local-models/status")assert response.status_code == 200, response.textstatus = response.json()- expected_tag = pin or "b10964"+ expected_tag = pin or DEFAULT_CONFIG["local_runtime"]["tag"]assert load_config()["local_runtime"]["tag"] == expected_tagassert status["configured_tag"] == expected_tagassert status["tag"] == "b10679" # An offer must not replace the installed engine.diff --git a/tests/hermes_cli/test_login_cli_command.py b/tests/hermes_cli/test_login_cli_command.pyindex 1af19eca7e2..384093a673b 100644--- a/tests/hermes_cli/test_login_cli_command.py+++ b/tests/hermes_cli/test_login_cli_command.py@@ -132,10 +132,6 @@ def test_the_handler_never_calls_input_and_uses_the_short_timeout(monkeypatch):assert seen == [{"timeout_seconds": 8.0}]-def test_the_in_chat_and_terminal_completion_use_their_own_copy():- state = anon_auth.Completed(email="", model="", model_changed=True)- assert "run /model to pick one" in anon_auth.drain_sign_in_copy(iter([state]), chat=True)- assert "run `hermes model` to pick one" in anon_auth.drain_sign_in_copy(iter([state]), chat=False)def test_the_command_resolves_through_the_cli_fallback():@@ -228,33 +224,5 @@ def test_the_live_tui_drain_prints_through_cprint_instead_of_the_captured_consolassert any("Signed in as [email protected]." in line for line in output)-def test_upgrade_guest_keeps_the_terminal_timeout(monkeypatch):- seen = []- monkeypatch.setattr(anon_auth, "render_sign_in_cli", lambda **kwargs: seen.append(kwargs) or 0)- monkeypatch.setattr("hermes_cli.auth_device_flow._is_remote_session", lambda: True)-- assert anon_auth.upgrade_guest(SimpleNamespace(timeout=None, no_browser=False)) == 0- assert seen[0]["timeout_seconds"] == 15.0- assert seen[0]["chat"] is False-def test_the_terminal_renderer_keeps_the_original_line_sequence(monkeypatch, capsys):- monkeypatch.setattr("hermes_cli.auth_device_flow._is_remote_session", lambda: True)- monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter([- anon_auth.Code("https://example.test/sign-in", "CODE-1", 900, 5),- anon_auth.Waiting(),- anon_auth.Completed(email="[email protected]", model="model-1", model_changed=True),- ]))-- assert anon_auth.upgrade_guest(SimpleNamespace(timeout=None, no_browser=False)) == 0- assert capsys.readouterr().out.splitlines() == [- anon_auth.UPGRADE_START,- "",- "To continue:",- " 1. Open: https://example.test/sign-in",- " 2. If prompted, enter code: CODE-1",- f" {anon_auth.UPGRADE_DO_NOT_SHARE}",- anon_auth.UPGRADE_WAITING,- "Signed in as [email protected].",- "Default model is now model-1.",- ]diff --git a/tests/hermes_cli/test_logs.py b/tests/hermes_cli/test_logs.pyindex 2412f87b159..9408c38292f 100644--- a/tests/hermes_cli/test_logs.py+++ b/tests/hermes_cli/test_logs.py@@ -4,7 +4,6 @@ from datetime import datetime, timedeltafrom hermes_cli.logs import (- LOG_FILES,_extract_level,_extract_logger_name,_line_matches_component,@@ -12,7 +11,6 @@ from hermes_cli.logs import (_parse_line_timestamp,_parse_since,_read_last_n_lines,- _read_tail,)@@ -143,9 +141,3 @@ class TestReadTail:# LOG_FILES registry# ----------------------------------------------------------------------------class TestLogFiles:- def test_known_log_files(self):- assert "agent" in LOG_FILES- assert "errors" in LOG_FILES- assert "gateway" in LOG_FILES- assert "gui" in LOG_FILESdiff --git a/tests/hermes_cli/test_loops.py b/tests/hermes_cli/test_loops.pyindex a99f9f6a0be..79366838d9e 100644--- a/tests/hermes_cli/test_loops.py+++ b/tests/hermes_cli/test_loops.py@@ -133,16 +133,6 @@ class TestParseLoopArgs:p = parse_loop_args("2m poll --times zero")assert p["error"] is not None- def test_no_start_now_flag_anymore(self):- from hermes_cli.loops import parse_loop_args-- # Immediate first wakeup is the default now; --start-now was never- # released, so the token is NOT parsed as a flag.- p = parse_loop_args("1h check the deploy status")- assert "start_now" not in p- assert p["interval_seconds"] == 3600- assert p["prompt"] == "check the deploy status"- assert p["error"] is Nonedef test_start_now_word_in_prompt_kept_verbatim(self):from hermes_cli.loops import parse_loop_args@@ -552,18 +542,6 @@ class TestControls:mgr.pause(reason="user-interrupted")assert mgr.state.awaiting_response is False- def test_status_line_shapes(self, hermes_home):- from hermes_cli.loops import LoopManager-- mgr = LoopManager(session_id="c4")- assert "No loop set" in mgr.status_line()- mgr.set("poll the build", interval_seconds=300)- assert "active" in mgr.status_line()- assert "poll the build" in mgr.status_line()- mgr.pause()- assert "paused" in mgr.status_line()- mgr.clear()- assert "No loop set" in mgr.status_line()# ──────────────────────────────────────────────────────────────────────@@ -609,14 +587,6 @@ class TestGoalMixing:class TestDispatchLoopCommand:- def test_create_fixed(self, hermes_home):- from hermes_cli.loops import LoopManager, dispatch_loop_command-- mgr = LoopManager(session_id="d1")- result = dispatch_loop_command(mgr, "5m check the deploy")- assert result["created"] is True- assert "Loop set" in result["output"]- assert "every 5m" in result["output"]def test_create_self_paced(self, hermes_home):from hermes_cli.loops import LoopManager, dispatch_loop_command@@ -662,13 +632,6 @@ class TestDispatchLoopCommand:dispatch_loop_command(mgr, "5m ping", route=route)assert load_loop("d5").route == route- def test_help(self, hermes_home):- from hermes_cli.loops import LoopManager, dispatch_loop_command-- mgr = LoopManager(session_id="d6")- out = dispatch_loop_command(mgr, "help")["output"]- assert "Usage" in out- assert "--times" in outdef test_bad_times_error(self, hermes_home):from hermes_cli.loops import LoopManager, dispatch_loop_command@@ -684,16 +647,6 @@ class TestDispatchLoopCommand:# ──────────────────────────────────────────────────────────────────────-class TestCommandRegistry:- def test_loop_registered_with_proactive_alias(self):- from hermes_cli.commands import resolve_command-- cmd = resolve_command("loop")- assert cmd is not None- assert cmd.name == "loop"- alias = resolve_command("proactive")- assert alias is not None- assert alias.name == "loop"# ──────────────────────────────────────────────────────────────────────diff --git a/tests/hermes_cli/test_macos_fda_guidance.py b/tests/hermes_cli/test_macos_fda_guidance.pydeleted file mode 100644index 4c8b2da1333..00000000000--- a/tests/hermes_cli/test_macos_fda_guidance.py+++ /dev/null@@ -1,99 +0,0 @@-"""macOS Full Disk Access onboarding guidance (issue #52010 follow-up).--One FDA grant silences every per-folder TCC prompt permanently. Doctor-reports the state and prints the one-switch setup; `hermes setup` surfaces-the same tip at onboarding. The probe must never itself trigger a prompt —-it reads the FDA-gated TCC db directory, which returns EPERM (no dialog)-without the grant.-"""--import io-import contextlib--import hermes_cli.doctor as doctor_mod-import pathlib-from hermes_cli.setup_quick import _print_macos_fda_tip-from hermes_cli import doctor_platform---def _capture(fn):- buf = io.StringIO()- with contextlib.redirect_stdout(buf):- fn()- return buf.getvalue()---class TestDoctorFdaCheck:- def test_silent_on_non_macos(self, monkeypatch):- monkeypatch.setattr(doctor_mod.sys, "platform", "linux")- out = _capture(doctor_platform.check_macos_full_disk_access)- assert out == ""-- def test_granted_reports_ok(self, monkeypatch, tmp_path):- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")- tcc = tmp_path / "Library" / "Application Support" / "com.apple.TCC"- tcc.mkdir(parents=True)- monkeypatch.setattr(pathlib.Path, "home", classmethod(lambda cls: tmp_path))- out = _capture(doctor_platform.check_macos_full_disk_access)- assert "Full Disk Access granted" in out- assert "Privacy_AllFiles" not in out-- def test_denied_prints_one_switch_guidance(self, monkeypatch, tmp_path):- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")- tcc = tmp_path / "Library" / "Application Support" / "com.apple.TCC"- tcc.mkdir(parents=True)- monkeypatch.setattr(pathlib.Path, "home", classmethod(lambda cls: tmp_path))-- def _eperm(path):- raise PermissionError(13, "Operation not permitted", str(path))-- monkeypatch.setattr(doctor_mod.os, "listdir", _eperm)- out = _capture(doctor_platform.check_macos_full_disk_access)- assert "Full Disk Access" in out- assert "Privacy_AllFiles" in out- assert "System Settings" in out-- def test_indeterminate_probe_is_silent(self, monkeypatch, tmp_path):- """Missing TCC dir (weird install) must not nag."""- monkeypatch.setattr(doctor_mod.sys, "platform", "darwin")- monkeypatch.setattr(pathlib.Path, "home", classmethod(lambda cls: tmp_path))- # tmp_path has no Library/Application Support/com.apple.TCC →- # FileNotFoundError (an OSError that is not PermissionError).- out = _capture(doctor_platform.check_macos_full_disk_access)- assert out == ""---class TestSetupFdaTip:- def test_silent_on_non_macos(self, monkeypatch):- import hermes_cli.setup as setup_mod-- monkeypatch.setattr(setup_mod.sys, "platform", "linux")- out = _capture(_print_macos_fda_tip)- assert out == ""-- def test_silent_when_already_granted(self, monkeypatch, tmp_path):- import hermes_cli.setup as setup_mod-- monkeypatch.setattr(setup_mod.sys, "platform", "darwin")- tcc = tmp_path / "Library" / "Application Support" / "com.apple.TCC"- tcc.mkdir(parents=True)- monkeypatch.setattr(setup_mod.Path, "home", classmethod(lambda cls: tmp_path))- out = _capture(_print_macos_fda_tip)- assert out == ""-- def test_tip_printed_when_denied(self, monkeypatch, tmp_path):- import hermes_cli.setup as setup_mod-- monkeypatch.setattr(setup_mod.sys, "platform", "darwin")- tcc = tmp_path / "Library" / "Application Support" / "com.apple.TCC"- tcc.mkdir(parents=True)- monkeypatch.setattr(setup_mod.Path, "home", classmethod(lambda cls: tmp_path))-- def _eperm(path):- raise PermissionError(13, "Operation not permitted", str(path))-- monkeypatch.setattr(setup_mod.os, "listdir", _eperm)- out = _capture(_print_macos_fda_tip)- assert "Full Disk Access" in out- assert "Privacy_AllFiles" in out- assert "survives every Hermes update" in outdiff --git a/tests/hermes_cli/test_macos_tcc_anchor.py b/tests/hermes_cli/test_macos_tcc_anchor.pyindex eed1e5ff65f..cbbb90626dd 100644--- a/tests/hermes_cli/test_macos_tcc_anchor.py+++ b/tests/hermes_cli/test_macos_tcc_anchor.py@@ -22,7 +22,6 @@ from pathlib import Pathimport pytest-import hermes_cli.doctor as doctorimport hermes_cli.macos_tcc_anchor as tccfrom hermes_constants import venv_python_pathfrom hermes_cli import doctor_platform@@ -525,32 +524,8 @@ class TestTccAnchorState:class TestDoctorCheck:- def test_missing_warns_without_fix(self, monkeypatch, capsys):- monkeypatch.setattr(- tcc, "tcc_anchor_state", lambda *a, **k: ("missing", "/x/.venv/bin/python")- )- doctor_platform.check_macos_tcc_anchor(should_fix=False)- out = capsys.readouterr().out- assert "macOS TCC anchor missing" in out- def test_fix_installs_anchor(self, monkeypatch, capsys):- monkeypatch.setattr(- tcc, "tcc_anchor_state", lambda *a, **k: ("missing", "/x/.venv/bin/python")- )- monkeypatch.setattr(- tcc, "ensure_tcc_anchor", lambda *a, **k: Path("/x/.venv/bin/python")- )- doctor_platform.check_macos_tcc_anchor(should_fix=True)- out = capsys.readouterr().out- assert "macOS TCC anchor installed" in out- def test_active_reports_ok(self, monkeypatch, capsys):- monkeypatch.setattr(- tcc, "tcc_anchor_state", lambda *a, **k: ("active", "/x/.venv/bin/python")- )- doctor_platform.check_macos_tcc_anchor(should_fix=False)- out = capsys.readouterr().out- assert "macOS TCC anchor active" in outdef test_skip_is_silent_on_non_macos(self, monkeypatch, capsys):monkeypatch.setattr(diff --git a/tests/hermes_cli/test_managed_scope.py b/tests/hermes_cli/test_managed_scope.pyindex c60653c5986..245496794be 100644--- a/tests/hermes_cli/test_managed_scope.py+++ b/tests/hermes_cli/test_managed_scope.py@@ -1,7 +1,6 @@"""Unit tests for hermes_cli.managed_scope (resolver + loaders + key helpers)."""import textwrap-import pytest# ── Directory resolver ───────────────────────────────────────────────────────@@ -49,8 +48,3 @@ def test_load_managed_env_and_is_env_managed(tmp_path, monkeypatch):-def test_managed_dir_env_scrubbed_by_default():- """conftest must scrub HERMES_MANAGED_DIR so a dev-shell value can't leak in."""- import os-- assert "HERMES_MANAGED_DIR" not in os.environdiff --git a/tests/hermes_cli/test_managed_uv.py b/tests/hermes_cli/test_managed_uv.pyindex 4e1d09563f0..c65867f2708 100644--- a/tests/hermes_cli/test_managed_uv.py+++ b/tests/hermes_cli/test_managed_uv.py@@ -91,72 +91,6 @@ class TestManagedUvPath:assert managed_uv_path() == tmp_path / "bin" / "uv"-class TestMacOSManagedPythonSigning:- def test_signs_with_stable_identifier_and_verifies(self, tmp_path, monkeypatch):- import hermes_cli.managed_uv as managed_uv-- python = tmp_path / "generation" / "bin" / "python3.11"- python.parent.mkdir(parents=True)- python.touch()- calls = []-- def fake_run(cmd, **kwargs):- calls.append((cmd, kwargs))- return SimpleNamespace(returncode=0, stdout="", stderr="")-- monkeypatch.setattr(managed_uv.platform, "system", lambda: "Darwin")- monkeypatch.setattr(managed_uv.shutil, "which", lambda name: "/usr/bin/codesign")- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)-- assert managed_uv._macos_sign_managed_python(python) is True- assert calls[0][0] == [- "/usr/bin/codesign",- "--force",- "--deep",- "--sign",- "-",- "--timestamp=none",- "--identifier",- "com.nousresearch.hermes.managed-python",- "--requirements",- '=designated => identifier "com.nousresearch.hermes.managed-python"',- str(python),- ]- assert calls[1][0] == [- "/usr/bin/codesign",- "--verify",- "--deep",- "--strict",- str(python),- ]-- def test_is_non_blocking_when_signing_fails(self, tmp_path, monkeypatch):- import hermes_cli.managed_uv as managed_uv-- python = tmp_path / "python3.11"- monkeypatch.setattr(managed_uv.platform, "system", lambda: "Darwin")- monkeypatch.setattr(managed_uv.shutil, "which", lambda name: "/usr/bin/codesign")- monkeypatch.setattr(- managed_uv.subprocess,- "run",- lambda *args, **kwargs: SimpleNamespace(- returncode=1, stdout="", stderr="not signable"- ),- )-- assert managed_uv._macos_sign_managed_python(python) is False-- def test_skips_non_macos(self, tmp_path, monkeypatch):- import hermes_cli.managed_uv as managed_uv-- monkeypatch.setattr(managed_uv.platform, "system", lambda: "Linux")- monkeypatch.setattr(- managed_uv.subprocess,- "run",- lambda *args, **kwargs: pytest.fail("codesign must not run on Linux"),- )-- assert managed_uv._macos_sign_managed_python(tmp_path / "python") is False# ---------------------------------------------------------------------------@@ -338,14 +272,6 @@ class TestEnsureUvWindowsSafe:the wrapper entirely."""- def test_uvresult_would_break_windows_list2cmdline(self):- # Canary: this is *why* the wrapper is gated off Windows. If a future- # change makes _UvResult char-iterable (and thus list2cmdline-safe),- # the gate may be revisited.- import subprocess- from hermes_cli.managed_uv import _UvResult- with pytest.raises(TypeError):- subprocess.list2cmdline([_UvResult("C:\\hermes\\uv.exe"), "pip"])@pytest.mark.windows_onlydef test_windows_returns_plain_str_safe_for_subprocess(self, tmp_path):@@ -902,7 +828,6 @@ class TestPatchRetryOnVulnerableCandidate:resolves to a DIFFERENT candidate Python version depending on whichexact version string was requested, so retries with explicitpatches can be distinguished from the initial bare-minor attempt."""- import hermes_cli.managed_uv as managed_uvfrom hermes_cli.sqlite_runtime import SQLiteRuntimeInfostate = {"requested": None}@@ -1459,40 +1384,4 @@ class TestVenvPythonUpdateBoundary:if sys.platform == "win32" else Path("/opt/hermes/venv/bin/python")assert _venv_python(Path("/opt/hermes/venv")) == expected- def test_recovery_uses_the_shared_helper_not_a_second_copy(self, monkeypatch):- """The reload must resolve through hermes_constants, not open-code it.-- Hand-rolling `Scripts`/`bin` here is what #76105 deduped away and what- `test_no_open_coded_venv_layout_remains_in_hermes_cli` bans.- """- import hermes_constants-- from hermes_cli.managed_uv import _venv_python-- monkeypatch.delattr(hermes_constants, "venv_python_path", raising=False)-- sentinel = Path("/sentinel/from/shared/helper")- real_reload = __import__("importlib").reload- def _reload_with_marker(module):- fresh = real_reload(module)- monkeypatch.setattr(- fresh, "venv_python_path", lambda *a, **k: sentinel, raising=False- )- return fresh-- monkeypatch.setattr("importlib.reload", _reload_with_marker)- assert _venv_python(Path("/opt/hermes/venv")) == sentinel-- def test_uses_the_real_helper_when_it_is_importable(self, monkeypatch):- """The normal path never reloads — recovery stays a fallback."""- from hermes_cli.managed_uv import _venv_python-- def _no_reload(module): # pragma: no cover - must not run- raise AssertionError("reload must not run when the import succeeds")-- monkeypatch.setattr("importlib.reload", _no_reload)-- expected = Path("/opt/hermes/venv/Scripts/python.exe") \- if sys.platform == "win32" else Path("/opt/hermes/venv/bin/python")- assert _venv_python(Path("/opt/hermes/venv")) == expecteddiff --git a/tests/hermes_cli/test_manual_compress.py b/tests/hermes_cli/test_manual_compress.pyindex 84646fdceb2..e21a6b08feb 100644--- a/tests/hermes_cli/test_manual_compress.py+++ b/tests/hermes_cli/test_manual_compress.py@@ -47,37 +47,6 @@ def test_manual_compress_keeps_tui_composer_editable(capsys):-def test_manual_compress_explains_when_token_estimate_rises(capsys):- shell = _make_cli()- history = _make_history()- compressed = [- history[0],- {"role": "assistant", "content": "Dense summary that still counts as more tokens."},- 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 # no-op: no split- shell.agent._compress_context.return_value = (compressed, "")- shell.agent._compression_skipped_due_to_lock = False-- def _estimate(messages, **_kwargs):- if messages == history:- return 100- if messages == compressed:- return 120- raise AssertionError(f"unexpected transcript: {messages!r}")-- with patch("agent.model_metadata.estimate_request_tokens_rough", side_effect=_estimate):- shell._manual_compress()-- output = capsys.readouterr().out- assert "✅ Compressed: 4 → 3 messages" in output- assert "Approx request size: ~100 → ~120 tokens" in output- assert "denser summaries" in outputdef test_manual_compress_syncs_session_id_after_split():diff --git a/tests/hermes_cli/test_manual_serve_deferral.py b/tests/hermes_cli/test_manual_serve_deferral.pyindex b9d813caf00..336f4d36d00 100644--- a/tests/hermes_cli/test_manual_serve_deferral.py+++ b/tests/hermes_cli/test_manual_serve_deferral.py@@ -9,7 +9,7 @@ from hermes_cli import process_identityfrom hermes_cli import update_cmd_fleet as fleetfrom hermes_cli import update_receiptfrom hermes_cli.update_inventory import RuntimeRecord, UpdatePlan-from hermes_cli.update_serve_obligations import defer_manual_serve, retain_receipt_manual_serves, warn_pending_manual_serves+from hermes_cli.update_serve_obligations import defer_manual_serve, retain_receipt_manual_servesfrom hermes_constants import get_hermes_home@@ -205,14 +205,6 @@ def test_unreadable_create_time_discharges_only_a_proven_dead_pid(monkeypatch, kassert defer_manual_serve(runtime, require_alive=True) is False-def test_unreadable_create_time_warning_names_identity_not_storage(monkeypatch, capsys):- runtime = asdict(RuntimeRecord(kind="serve", profile="work", pid=900, supervisor="manual-serve", restart_via="respawn-argv", detail={"create_time": None}))- monkeypatch.setattr(process_identity, "_pid_alive_matches", lambda *a: True)- warn_pending_manual_serves(pending_manual=[runtime])- out = capsys.readouterr().out- assert "could not read the process creation time" in out- assert "storage permissions" not in out- assert "relaunch" in outdef test_launchd_serve_row_never_pessimize_gateway_coverage():diff --git a/tests/hermes_cli/test_mcp_add_command_dest.py b/tests/hermes_cli/test_mcp_add_command_dest.pydeleted file mode 100644index abc1f107dc0..00000000000--- a/tests/hermes_cli/test_mcp_add_command_dest.py+++ /dev/null@@ -1,92 +0,0 @@-"""Regression test: ``hermes mcp add --command`` must not clobber the-top-level ``args.command`` subparser dest.--The top-level argparse parser uses ``dest="command"`` for its subparsers-(``hermes_cli/_parser.py``). The dispatcher in ``hermes_cli/main.py``-reads ``args.command`` to decide which command to run; if it is ``None``-it falls through to interactive chat.--The ``mcp add`` subparser exposes a ``--command`` flag (the stdio command-for an MCP server, e.g. ``npx``). Without an explicit ``dest=``, argparse-derives the dest from the flag name and writes ``args.command = None``-when the flag is omitted, overwriting the top-level ``"mcp"`` value. As a-result, ``hermes mcp add foo --url ...`` silently launches chat instead-of registering an MCP server.--The fix: declare the flag with ``dest="mcp_command"``. The CLI flag name-is unchanged; only the in-memory attribute moves.--We replicate the relevant parser shape here rather than importing the-real builder, mirroring ``test_argparse_flag_propagation.py`` and-``test_subparser_routing_fallback.py``.-"""--import argparse---def _build_parser():- """Minimal replica of the slice of the hermes parser that exhibits- the bug: top-level subparsers (dest="command") and ``mcp add`` with- its ``--command`` flag.- """- parser = argparse.ArgumentParser(prog="hermes")- subparsers = parser.add_subparsers(dest="command")-- subparsers.add_parser("chat")-- mcp_p = subparsers.add_parser("mcp")- mcp_sub = mcp_p.add_subparsers(dest="mcp_action")-- mcp_add = mcp_sub.add_parser("add")- mcp_add.add_argument("name")- mcp_add.add_argument("--url")- mcp_add.add_argument("--command", dest="mcp_command")- mcp_add.add_argument("--connect-timeout", type=float)- mcp_add.add_argument("--args", nargs=argparse.REMAINDER, default=[])-- return parser---class TestMcpAddCommandDest:- def test_url_invocation_preserves_top_level_command(self):- """`hermes mcp add foo --url ...` must keep args.command == "mcp".-- Before the dest fix this was clobbered to None, sending the- dispatcher into the chat fallback.- """- parser = _build_parser()- args = parser.parse_args(- ["mcp", "add", "foo", "--url", "https://example.com/mcp"]- )-- assert args.command == "mcp"- assert args.mcp_action == "add"- assert args.name == "foo"- assert args.url == "https://example.com/mcp"- assert args.mcp_command is None----- def test_args_passthrough_keeps_nested_option_flags(self):- """`--args` must keep command flags like Docker MCP's --profile."""- parser = _build_parser()- args = parser.parse_args(- [- "mcp",- "add",- "docker-research",- "--command",- "docker",- "--args",- "mcp",- "gateway",- "run",- "--profile",- "research",- ]- )-- assert args.command == "mcp"- assert args.mcp_command == "docker"- assert args.args == ["mcp", "gateway", "run", "--profile", "research"]diff --git a/tests/hermes_cli/test_mcp_catalog.py b/tests/hermes_cli/test_mcp_catalog.pyindex 2a5c79b1c67..ca3edafd79e 100644--- a/tests/hermes_cli/test_mcp_catalog.py+++ b/tests/hermes_cli/test_mcp_catalog.py@@ -9,7 +9,6 @@ from __future__ import annotationsimport refrom pathlib import Path-from unittest.mock import patchimport pytestimport yaml@@ -694,12 +693,6 @@ class TestUninstall:class TestPicker:- def test_show_catalog_empty(self, catalog_dir, capsys):- from hermes_cli.mcp_picker import show_catalog-- show_catalog()- out = capsys.readouterr().out- assert "No MCPs in the catalog or configured" in outdef test_install_by_name_success(self, catalog_dir):@@ -720,7 +713,7 @@ class TestPicker:run_picker()out = capsys.readouterr().out- assert "MCP Catalog + configured servers" in out+ assert "demo" in out# ---------------------------------------------------------------------------@@ -962,29 +955,6 @@ class TestToolsConfigIncludeMode:class TestShippedCatalog:- def test_asana_catalog_targets_v2_with_preregistered_client(self, monkeypatch):- """Asana's V1 ``/sse`` server is retired and V2 has no DCR: the shipped entry must install- as the V2 Streamable HTTP URL plus a pre-registered client whose credentials are ``${VAR}``- references the install path actually prompts for (never literal values)."""- monkeypatch.delenv("HERMES_OPTIONAL_MCPS", raising=False)- from hermes_cli.mcp_catalog import _build_server_config, _catalog_root, _parse_manifest-- root = _catalog_root()- if not root.exists():- pytest.skip("optional-mcps/ not present in this checkout")- for m in root.glob("*/manifest.yaml"):- assert (_parse_manifest(m).transport.url or "") != "https://mcp.asana.com/sse", m-- entry = _parse_manifest(root / "asana" / "manifest.yaml")- cfg = _build_server_config(entry, None)- assert cfg["url"] == "https://mcp.asana.com/v2/mcp"- assert cfg["auth"] == "oauth"- declared = {spec.name for spec in entry.auth.env}- for key in ("client_id", "client_secret"):- ref = re.fullmatch(r"\$\{([A-Z_]+)\}", cfg["oauth"][key])- assert ref and ref.group(1) in declared, (key, cfg["oauth"][key])- # Asana matches the registered redirect URL exactly; the callback must be pinned.- assert cfg["oauth"]["redirect_host"] and cfg["oauth"]["redirect_port"]def test_manifest_connector_slugs_are_valid_and_unique(self, monkeypatch):from hermes_cli.mcp_catalog import catalog_diagnostics, list_catalogdiff --git a/tests/hermes_cli/test_mcp_config.py b/tests/hermes_cli/test_mcp_config.pyindex f509f0e23b1..0d7c91eb060 100644--- a/tests/hermes_cli/test_mcp_config.py+++ b/tests/hermes_cli/test_mcp_config.py@@ -82,12 +82,6 @@ class FakeTool:# ---------------------------------------------------------------------------class TestMcpList:- def test_list_empty_config(self, tmp_path, capsys):- from hermes_cli.mcp_config import cmd_mcp_list-- cmd_mcp_list()- out = capsys.readouterr().out- assert "No MCP servers configured" in outdef test_list_with_servers(self, tmp_path, capsys):_seed_config(tmp_path, {@@ -285,23 +279,6 @@ class TestMcpAdd:class TestMcpTest:- def test_test_success(self, tmp_path, capsys, monkeypatch):- _seed_config(tmp_path, {- "ink": {"url": "https://mcp.ml.ink/mcp"},- })-- def mock_probe(name, config, **kw):- return [("create_service", "Deploy"), ("list_services", "List all")]-- monkeypatch.setattr(- "hermes_cli.mcp_config._probe_single_server", mock_probe- )- from hermes_cli.mcp_config import cmd_mcp_test-- cmd_mcp_test(_make_args(name="ink"))- out = capsys.readouterr().out- assert "Connected" in out- assert "Tools discovered: 2" in outdef test_exit_codes_distinguish_failure_from_unknown_server(self, tmp_path, capsys, monkeypatch):"""0 connected, 1 connection failed, 3 not in config — never argparse's 2, never a silent 0."""@@ -336,7 +313,6 @@ class TestMcpTest:"""OAuth-capable probes must not hard-code a short 30s timeout."""import asynciofrom hermes_cli import mcp_config- import tools.mcp_tool as mcp_toolfrom tools import mcp_tool_discovery as _mcp_discoveryfrom tools import mcp_tool_lifecycle as _mcp_lifecyclefrom tools import mcp_tool_loop as _mcp_loop@@ -417,7 +393,6 @@ class TestContextVarInterpolation:assert _interpolate_env_vars("${/}") == os.sepdef test_workspace_folder_and_basename(self, monkeypatch):- import tools.mcp_tool as mcp_toolmonkeypatch.setattr(_mcp_config, "_workspace_folder", lambda: "/srv/projects/myapp"@@ -443,7 +418,6 @@ class TestContextVarInterpolation:def test_mixed_string_with_env_and_context_vars(self, monkeypatch):import os- import tools.mcp_tool as mcp_toolmonkeypatch.setenv("MY_TOKEN", "tok-1")monkeypatch.setattr(_mcp_config, "_workspace_folder", lambda: "/ws/app")@@ -472,7 +446,6 @@ class TestContextVarInterpolation:def test_context_vars_in_nested_config(self, monkeypatch):import os- import tools.mcp_tool as mcp_toolfrom tools import mcp_tool_config as _mcp_configmonkeypatch.setattr(_mcp_config, "_workspace_folder", lambda: "/ws/app")diff --git a/tests/hermes_cli/test_mcp_discovery_timing.py b/tests/hermes_cli/test_mcp_discovery_timing.pyindex fe2671e0986..9b6c8f3c6b6 100644--- a/tests/hermes_cli/test_mcp_discovery_timing.py+++ b/tests/hermes_cli/test_mcp_discovery_timing.py@@ -141,20 +141,6 @@ def test_ensure_helper_starts_discovery_and_waits(monkeypatch):assert any(call[1] is True for call in waited)-def test_ensure_helper_is_idempotent(monkeypatch):- """Calling the helper twice doesn't start a second discovery thread."""- _stub_mcp_modules(monkeypatch)- logger = types.SimpleNamespace(debug=lambda *_a, **_k: None, warning=lambda *_a, **_k: None)-- mcp_startup.ensure_mcp_discovery_before_agent_build(logger=logger)- thread1 = mcp_startup._current_home_thread()- if thread1:- thread1.join(timeout=2.0)-- mcp_startup.ensure_mcp_discovery_before_agent_build(logger=logger)- thread2 = mcp_startup._current_home_thread()- if thread2:- thread2.join(timeout=2.0)# Second call didn't create a new thread (first one completed, status shows connected)# or if it did, it's because the first exited with zero connected — but we stubbed@@ -182,41 +168,11 @@ def test_ensure_helper_swallows_errors(monkeypatch):# ── oneshot ordering: discovery before AIAgent ──────────────────────────────-def test_oneshot_calls_ensure_helper_before_aiagent(monkeypatch):- """oneshot._run_agent must call ensure_mcp_discovery_before_agent_build- before constructing AIAgent (#38448)."""- import inspect-- import hermes_cli.oneshot as oneshot_mod-- src = inspect.getsource(oneshot_mod._run_agent)- helper_idx = src.find("ensure_mcp_discovery_before_agent_build")- agent_idx = src.find("AIAgent(")- assert helper_idx != -1, "oneshot._run_agent must call ensure_mcp_discovery_before_agent_build"- assert agent_idx != -1, "oneshot._run_agent must construct AIAgent"- assert helper_idx < agent_idx, (- "ensure_mcp_discovery_before_agent_build must be called BEFORE AIAgent "- "construction in oneshot._run_agent (#38448)"- )# ── _init_agent ordering: discovery before AIAgent (CLI path) ───────────────-def test_init_agent_calls_ensure_helper_before_aiagent(monkeypatch):- """cli_agent_setup_mixin._init_agent must call- ensure_mcp_discovery_before_agent_build before constructing AIAgent."""- import inspect-- from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin-- src = inspect.getsource(CLIAgentSetupMixin._init_agent)- helper_idx = src.find("ensure_mcp_discovery_before_agent_build")- # _init_agent delegates AIAgent construction to cli.py, so we check- # the helper appears before the session_db / agent construction logic- assert helper_idx != -1, (- "_init_agent must call ensure_mcp_discovery_before_agent_build"- )def test_init_agent_forwards_single_query_flag(monkeypatch):@@ -305,9 +261,3 @@ def test_wait_stays_bounded_when_discovery_is_slow(monkeypatch):)-def test_wait_returns_instantly_when_discovery_done():- """When discovery is already complete, the wait returns immediately."""- mcp_startup._mcp_discovery_thread.clear()- t0 = time.time()- mcp_startup.wait_for_mcp_discovery(single_query=True)- assert time.time() - t0 < 0.2diff --git a/tests/hermes_cli/test_mcp_helper_ledger.py b/tests/hermes_cli/test_mcp_helper_ledger.pyindex ab052102133..3970672f329 100644--- a/tests/hermes_cli/test_mcp_helper_ledger.py+++ b/tests/hermes_cli/test_mcp_helper_ledger.py@@ -95,10 +95,6 @@ def test_register_child_rejects_dead_or_invalid_pids(ledger):assert not ledger.exists() or json.loads(ledger.read_text()) == []-def test_mcp_helper_is_reapable_purpose():- assert "mcp-helper" in pi.REAPABLE_PURPOSES- # Interactive purposes still excluded.- assert "chat" not in pi.REAPABLE_PURPOSES# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_mcp_reload_confirm_gate.py b/tests/hermes_cli/test_mcp_reload_confirm_gate.pydeleted file mode 100644index 980bdad4ff3..00000000000--- a/tests/hermes_cli/test_mcp_reload_confirm_gate.py+++ /dev/null@@ -1,62 +0,0 @@-"""Tests for the approvals.mcp_reload_confirm config gate.--When the user runs /reload-mcp, the MCP tool set is rebuilt which-invalidates the provider prompt cache for the active session. That's-expensive on long-context / high-reasoning models. The config gate-adds a three-option confirmation (Approve Once / Always Approve /-Cancel); "Always Approve" flips this key to false so subsequent reloads-run silently.-"""--from __future__ import annotations---from hermes_cli.config import DEFAULT_CONFIG---class TestMcpReloadConfirmDefault:- def test_default_config_has_the_key(self):- approvals = DEFAULT_CONFIG.get("approvals")- assert isinstance(approvals, dict)- assert "mcp_reload_confirm" in approvals-- def test_default_is_true(self):- # New installs confirm by default — this is the safe behavior.- assert DEFAULT_CONFIG["approvals"]["mcp_reload_confirm"] is True-- def test_shape_matches_other_approval_keys(self):- # Same flat dict level as `mode` / `timeout` / `cron_mode`.- approvals = DEFAULT_CONFIG["approvals"]- assert isinstance(approvals.get("mode"), str)- assert isinstance(approvals.get("timeout"), int)- assert isinstance(approvals.get("cron_mode"), str)- assert isinstance(approvals.get("mcp_reload_confirm"), bool)---class TestUserConfigMerge:- """If a user has a pre-existing config without this key, load_config- should fill it in from DEFAULT_CONFIG (deep merge preserves keys the- user didn't override).- """-- def test_existing_user_config_without_key_gets_default(self, tmp_path, monkeypatch):- import yaml-- # Simulate a legacy user config without the new key.- home = tmp_path / ".hermes"- home.mkdir()- cfg_path = home / "config.yaml"- legacy = {- "approvals": {"mode": "manual", "timeout": 60, "cron_mode": "deny"},- }- cfg_path.write_text(yaml.safe_dump(legacy))-- monkeypatch.setenv("HERMES_HOME", str(home))- # Force a fresh reimport of config.py so the HERMES_HOME is honored.- import importlib- import hermes_cli.config as cfg_mod- importlib.reload(cfg_mod)-- cfg = cfg_mod.load_config()- assert cfg["approvals"]["mcp_reload_confirm"] is True-diff --git a/tests/hermes_cli/test_mcp_startup.py b/tests/hermes_cli/test_mcp_startup.pyindex df03dade2da..6666dba3b65 100644--- a/tests/hermes_cli/test_mcp_startup.py+++ b/tests/hermes_cli/test_mcp_startup.py@@ -11,7 +11,6 @@ import typesimport pytest-import cli as cli_modfrom hermes_cli import main as main_modfrom hermes_cli import mcp_startup@@ -91,7 +90,7 @@ def test_prepare_agent_startup_backgrounds_blocking_mcp_for_chat(monkeypatch):start = time.monotonic()main_mod._prepare_agent_startup(_agent_args())elapsed = time.monotonic() - start- assert elapsed < 0.2+ assert elapsed < 2.0deadline = time.monotonic() + 3.0while calls["mcp"] == 0 and time.monotonic() < deadline:time.sleep(0.01)diff --git a/tests/hermes_cli/test_mem_trim.py b/tests/hermes_cli/test_mem_trim.pyindex 575a4a8dcdb..8886166447b 100644--- a/tests/hermes_cli/test_mem_trim.py+++ b/tests/hermes_cli/test_mem_trim.py@@ -43,15 +43,6 @@ def test_config_kill_switch_overrides_force_from_config_file(monkeypatch, tmp_pareset_hermes_home_override(token)-def test_default_config_declares_memory_trim_controls():- from hermes_cli.config import DEFAULT_CONFIG-- context = DEFAULT_CONFIG["context"]- assert isinstance(context, dict)- settings = context["memory_trim"]- assert isinstance(settings, dict)- assert isinstance(settings["enabled"], bool)- assert isinstance(settings["cooldown_seconds"], float)def test_collect_memory_snapshot_parses_linux_proc_status(monkeypatch):@@ -86,47 +77,8 @@ def test_success_collects_then_trims(monkeypatch):assert mem_trim._last_trim_monotonic == 100.0-def test_success_logs_memory_snapshot_and_trim_result(monkeypatch, caplog):- monkeypatch.setattr(mem_trim.gc, "collect", lambda: None)- monkeypatch.setattr(mem_trim, "_malloc_trim", lambda _pad: 1)- monkeypatch.setattr(mem_trim.time, "monotonic", lambda: 100.0)- snapshots = iter(- (- {"rss_kib": 4096, "rss_anon_kib": 3072, "thread_count": 3},- {"rss_kib": 2048, "rss_anon_kib": 1024, "thread_count": 3},- )- )- monkeypatch.setattr(mem_trim, "collect_memory_snapshot", lambda: next(snapshots))-- with caplog.at_level("INFO", logger="hermes_cli.mem_trim"):- assert mem_trim.trim_memory(reason="test turn") is True-- assert "reason=test turn" in caplog.text- assert "malloc_trim=1" in caplog.text- assert "rss_kib=4096->2048" in caplog.text---def test_force_logs_even_when_periodic_log_sampling_skips(monkeypatch, caplog):- monkeypatch.setattr(mem_trim.gc, "collect", lambda: None)- monkeypatch.setattr(mem_trim, "_malloc_trim", lambda _pad: 1)- monkeypatch.setattr(mem_trim, "_config_settings", lambda: (True, 0.0, 99, 1.0))- # Two ticks: the forced call comes after the 5s force floor so it runs- # (the floor exists to coalesce burst closes, not to mute logging).- _ticks = iter([100.0, 110.0])- monkeypatch.setattr(mem_trim.time, "monotonic", lambda: next(_ticks, 110.0))- monkeypatch.setattr(- mem_trim,- "collect_memory_snapshot",- lambda: {"rss_kib": 4096, "rss_anon_kib": 3072, "thread_count": 3},- )- with caplog.at_level("INFO", logger="hermes_cli.mem_trim"):- assert mem_trim.trim_memory(reason="periodic") is True- assert mem_trim.trim_memory(force=True, reason="close") is True- messages = [record.getMessage() for record in caplog.records]- assert not any("reason=periodic" in message for message in messages)- assert any("reason=close" in message for message in messages)def test_cooldown_suppresses_repeated_collection(monkeypatch):@@ -161,17 +113,6 @@ def test_config_cooldown_controls_rate_limit(monkeypatch):trim.assert_not_called()-def test_legacy_environment_switch_does_not_control_behavior(monkeypatch):- trim = Mock(return_value=1)- monkeypatch.setattr(mem_trim, "_malloc_trim", trim)- monkeypatch.setenv("HERMES_DISABLE_MEMORY_TRIM", "1")- monkeypatch.setattr(- "hermes_cli.config.load_config_readonly",- lambda: {"context": {"memory_trim": {"enabled": True}}},- )-- assert mem_trim.trim_memory(force=True) is True- trim.assert_called_once_with(0)def test_libc_failure_is_fail_open_and_rate_limited(monkeypatch):diff --git a/tests/hermes_cli/test_memory_reset.py b/tests/hermes_cli/test_memory_reset.pydeleted file mode 100644index c43220361b5..00000000000--- a/tests/hermes_cli/test_memory_reset.py+++ /dev/null@@ -1,95 +0,0 @@-"""Tests for the `hermes memory reset` CLI command.--Covers:-- Reset both stores (MEMORY.md + USER.md)-- Reset individual stores (--target memory / --target user)-- Skip confirmation with --yes-- Graceful handling when no memory files exist-- Profile-scoped reset (uses HERMES_HOME)-"""--import pytest---def memory_env(tmp_path, monkeypatch):- """Set up a fake HERMES_HOME with memory files."""- hermes_home = tmp_path / ".hermes"- memories = hermes_home / "memories"- memories.mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- # Create sample memory files- (memories / "MEMORY.md").write_text(- "§\nHermes repo is at ~/.hermes/hermes-agent\n§\nUser prefers dark themes",- encoding="utf-8",- )- (memories / "USER.md").write_text(- "§\nUser is Teknium\n§\nTimezone: US Pacific",- encoding="utf-8",- )- return hermes_home, memories---def _run_memory_reset(target="all", yes=False, monkeypatch=None, confirm_input="no"):- """Invoke the memory reset logic from cmd_memory in main.py.-- Simulates what happens when `hermes memory reset` is run.- """- from hermes_constants import get_hermes_home-- mem_dir = get_hermes_home() / "memories"- files_to_reset = []- if target in {"all", "memory"}:- files_to_reset.append(("MEMORY.md", "agent notes"))- if target in {"all", "user"}:- files_to_reset.append(("USER.md", "user profile"))-- existing = [(f, desc) for f, desc in files_to_reset if (mem_dir / f).exists()]- if not existing:- return "nothing"-- if not yes:- if confirm_input != "yes":- return "cancelled"-- for f, desc in existing:- (mem_dir / f).unlink()-- return "deleted"---class TestMemoryReset:- """Tests for `hermes memory reset` subcommand."""-- def test_reset_all_with_yes_flag(self, memory_env):- """--yes flag should skip confirmation and delete both files."""- hermes_home, memories = memory_env- assert (memories / "MEMORY.md").exists()- assert (memories / "USER.md").exists()-- result = _run_memory_reset(target="all", yes=True)- assert result == "deleted"- assert not (memories / "MEMORY.md").exists()- assert not (memories / "USER.md").exists()--- def test_reset_no_files_exist(self, tmp_path, monkeypatch):- """Should return 'nothing' when no memory files exist."""- hermes_home = tmp_path / ".hermes"- (hermes_home / "memories").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- result = _run_memory_reset(target="all", yes=True)- assert result == "nothing"--- def test_reset_partial_files(self, memory_env):- """Reset should work when only one memory file exists."""- hermes_home, memories = memory_env- (memories / "USER.md").unlink()-- result = _run_memory_reset(target="all", yes=True)- assert result == "deleted"- assert not (memories / "MEMORY.md").exists()-diff --git a/tests/hermes_cli/test_memory_setup.py b/tests/hermes_cli/test_memory_setup.pyindex 93903e67865..ef40a1d643a 100644--- a/tests/hermes_cli/test_memory_setup.py+++ b/tests/hermes_cli/test_memory_setup.py@@ -1,8 +1,9 @@+import refrom types import SimpleNamespacefrom unittest.mock import MagicMockimport hermes_cli.memory_setup as memory_setup-from hermes_cli.memory_setup import _CANCELLED, _curses_select+from hermes_cli.memory_setup import _CANCELLED@@ -101,9 +102,9 @@ def test_cmd_status_memory_tool_gate_disabled(capsys, monkeypatch):memory_setup.cmd_status(SimpleNamespace())captured = capsys.readouterr().out- assert "Memory tool: disabled ✗" in captured- assert "Memory injection: disabled ✗" in captured- assert "User profile: disabled ✗" in captured+ assert re.search(r"Memory tool:\s+disabled", captured)+ assert re.search(r"Memory injection:\s+disabled", captured)+ assert re.search(r"User profile:\s+disabled", captured)def test_cmd_status_memory_tool_gate_enabled(capsys, monkeypatch):@@ -118,6 +119,6 @@ def test_cmd_status_memory_tool_gate_enabled(capsys, monkeypatch):memory_setup.cmd_status(SimpleNamespace())captured = capsys.readouterr().out- assert "Memory tool: enabled ✓" in captured- assert "Memory injection: enabled ✓" in captured- assert "User profile: disabled ✗" in captured+ assert re.search(r"Memory tool:\s+enabled", captured)+ assert re.search(r"Memory injection:\s+enabled", captured)+ assert re.search(r"User profile:\s+disabled", captured)diff --git a/tests/hermes_cli/test_memory_status.py b/tests/hermes_cli/test_memory_status.pydeleted file mode 100644index 5bb9a2b847e..00000000000--- a/tests/hermes_cli/test_memory_status.py+++ /dev/null@@ -1,57 +0,0 @@-"""Tests for `hermes memory status` CLI command.--Covers:-- Status output shows config-aware indicators instead of hardcoded 'always active'-- memory_enabled, user_profile_enabled, and memory tool are each reflected-- Memory tool resolution uses the canonical _get_platform_tools resolver-- Original issue: 'Built-in: always active' was misleading when features were disabled-"""--import pytest-from unittest.mock import patch---def _run_cmd_status(capfd, mem_config=None, memory_tools=None):- """Run cmd_status with a mocked config and return captured stdout.-- Args:- mem_config: The "memory" section of config.- memory_tools: Set of tool names returned by _get_platform_tools.- Defaults to {"memory"} (tool enabled).- """- from hermes_cli.memory_setup import cmd_status-- config = {"memory": mem_config or {}}- if memory_tools is None:- memory_tools = {"memory"}-- with patch("hermes_cli.config.load_config", return_value=config):- with patch("hermes_cli.memory_setup._get_available_providers", return_value=[]):- with patch(- "hermes_cli.tools_config._get_platform_tools",- return_value=memory_tools,- ):- cmd_status(args=None)-- captured = capfd.readouterr()- return captured.out---class TestMemoryStatusLabels:- """Status output should reflect actual config, not a hardcoded string."""--- def test_shows_memory_injection_enabled_by_default(self, capfd):- """Memory injection defaults to enabled."""- out = _run_cmd_status(capfd)- assert "Memory injection:" in out- assert "enabled ✓" in out-- def test_shows_memory_injection_disabled(self, capfd):- """When memory_enabled is false, status reflects it."""- out = _run_cmd_status(capfd, mem_config={"memory_enabled": False})- assert "Memory injection:" in out- assert "disabled ✗" in out---diff --git a/tests/hermes_cli/test_meta_prompt_cache.py b/tests/hermes_cli/test_meta_prompt_cache.pyindex 662088b2a4c..42e489e6324 100644--- a/tests/hermes_cli/test_meta_prompt_cache.py+++ b/tests/hermes_cli/test_meta_prompt_cache.py@@ -89,14 +89,3 @@ class TestMetaConfigRoundtrip:# transport is lifted to api_mode via _normalize path or at least preservedassert normalized2.get("api_mode") == "codex_responses" or normalized2.get("transport") == "codex_responses"- def test_providers_dict_to_custom_providers_preserves_meta_without_explicit_mode(self):- # Without explicit api_mode, host mandate resolves via providers.determine_api_mode- # This test ensures the providers entry survives normalization and the host still mandates- from hermes_cli.providers import host_mandated_api_mode-- assert host_mandated_api_mode("https://api.meta.ai/v1") == "codex_responses"- # Simulate providers dict path: providers.meta.base_url stored, no api_mode field- # The resolution layer (determine_api_mode / runtime_provider) must mandate.- from hermes_cli.providers import determine_api_mode-- assert determine_api_mode("meta", "https://api.meta.ai/v1", "muse-spark-1.2") == "codex_responses"diff --git a/tests/hermes_cli/test_minimax_model_validation.py b/tests/hermes_cli/test_minimax_model_validation.pyindex 05fa4c447c3..67dc6c4acd9 100644--- a/tests/hermes_cli/test_minimax_model_validation.py+++ b/tests/hermes_cli/test_minimax_model_validation.py@@ -72,13 +72,5 @@ class TestMiniMaxModelValidation:# -------------------------------------------------------------------------# Test 4: Verify catalog path is used (probe_api_models returns None)# -------------------------------------------------------------------------- def test_minimax_uses_catalog_not_api_probe(self):- """Ensure that when fetch_api_models returns None, the catalog is still checked."""- # The _isolate_minimax fixture already patches fetch_api_models to return None.- # If we reach the catalog path, MiniMax-M2.5 should be found and recognized.- result = validate_requested_model("MiniMax-M2.5", "minimax")- assert result["accepted"] is True- assert result["recognized"] is True- assert result["message"] is Nonediff --git a/tests/hermes_cli/test_minimax_oauth.py b/tests/hermes_cli/test_minimax_oauth.pyindex 0f807a6dc72..bc88849a4c3 100644--- a/tests/hermes_cli/test_minimax_oauth.py+++ b/tests/hermes_cli/test_minimax_oauth.py@@ -20,7 +20,6 @@ from unittest.mock import MagicMock, patchimport pytestfrom hermes_cli.auth import (- PROVIDER_REGISTRY,AuthError,MINIMAX_OAUTH_CLIENT_ID,MINIMAX_OAUTH_GLOBAL_BASE,@@ -28,7 +27,6 @@ from hermes_cli.auth import (MINIMAX_OAUTH_REFRESH_SKEW_SECONDS,_minimax_pkce_pair,_minimax_request_user_code,- _minimax_poll_token,_minimax_resolve_token_expiry_unix,_refresh_minimax_oauth_state,resolve_minimax_oauth_runtime_credentials,@@ -505,7 +503,6 @@ def test_refresh_error_body_bounded_and_readable_with_real_client():import socketserverimport threading- import httpxfrom hermes_cli.auth import _refresh_minimax_oauth_state@@ -547,24 +544,3 @@ def test_refresh_error_body_bounded_and_readable_with_real_client():assert "...[truncated]" in msg-def test_minimax_response_error_text_truncates_above_limit():- """Bodies above the 16KB bound are cut and marked truncated."""- import httpx-- from hermes_cli.auth import (- _MINIMAX_OAUTH_ERROR_BODY_LIMIT,- _minimax_response_error_text,- )-- big = "e" * (_MINIMAX_OAUTH_ERROR_BODY_LIMIT * 4)-- def handler(request: httpx.Request) -> httpx.Response:- return httpx.Response(500, text=big)-- with httpx.Client(transport=httpx.MockTransport(handler)) as client:- request = client.build_request("POST", "https://api.minimax.io/oauth/token")- response = client.send(request, stream=True)- text = _minimax_response_error_text(response)-- assert text.endswith("...[truncated]")- assert len(text) <= _MINIMAX_OAUTH_ERROR_BODY_LIMIT + len("...[truncated]")diff --git a/tests/hermes_cli/test_moa_command.py b/tests/hermes_cli/test_moa_command.pyindex 03aca18c2b6..f75ddf9dca0 100644--- a/tests/hermes_cli/test_moa_command.py+++ b/tests/hermes_cli/test_moa_command.py@@ -2,7 +2,6 @@ import queuefrom unittest.mock import patchfrom cli import HermesCLI-from hermes_cli.moa_config import decode_moa_turndef _make_cli():@@ -102,14 +101,4 @@ class TestNormalizeMoaModel:"openrouter:deepseek/deepseek-v4",)- def test_override_wins_over_explicit_provider(self):- # __init__ resolves requested_provider as- # ``_moa_provider_override or provider or ...``, so a moa: prefix must- # take precedence over an explicit --provider (the #56828 deepseek case- # where MoA was silently ignored).- from cli import _normalize_moa_model- override, model = _normalize_moa_model("moa:strategy")- requested_provider = override or "deepseek" or "auto"- assert requested_provider == "moa"- assert model == "strategy"diff --git a/tests/hermes_cli/test_moa_config.py b/tests/hermes_cli/test_moa_config.pyindex afc905e3fbe..3e23f095ca2 100644--- a/tests/hermes_cli/test_moa_config.py+++ b/tests/hermes_cli/test_moa_config.py@@ -5,7 +5,6 @@ from hermes_cli.moa_config import (DEFAULT_MOA_AGGREGATOR,DEFAULT_MOA_PRESET_NAME,DEFAULT_MOA_REFERENCE_MODELS,- decode_moa_turn,exact_moa_preset_name,normalize_moa_config,resolve_moa_preset,@@ -87,7 +86,6 @@ def test_resolve_missing_moa_preset_has_actionable_error():assert "日常对话-高峰期" in messageassert "日常对话-高峰" in messageassert "日常对话-非高峰" in message- assert "hermes moa list" in messagedef test_missing_moa_preset_is_non_retryable():@@ -164,10 +162,9 @@ def test_print_config_marks_aggregator_as_billed_and_warns_on_provider_mismatch(moa_cmd._print_config({"model": {"provider": "openai-codex"}})out = capsys.readouterr().out- assert "acting model — runs every step" in out- assert "advise once per user turn" in out# Default preset's aggregator is on openrouter → the notice names both providers.- assert "Aggregator is on openrouter; the whole tool loop will be billed there, not to openai-codex." in out+ notice = next(line for line in out.splitlines() if "Aggregator is on" in line)+ assert "openrouter" in notice and "openai-codex" in notice@pytest.mark.parametrize("cfg", [{"model": {"provider": "openrouter"}}, {}])@@ -177,7 +174,6 @@ def test_billing_notice_silent_when_providers_match_or_main_unknown(cfg, capsys)moa_cmd._print_config(cfg)out = capsys.readouterr().out- assert "acting model — runs every step" in outassert "Aggregator is on" not in outdiff --git a/tests/hermes_cli/test_model_alias_credentials.py b/tests/hermes_cli/test_model_alias_credentials.pyindex b89eebda3d4..75ca2cf55d5 100644--- a/tests/hermes_cli/test_model_alias_credentials.py+++ b/tests/hermes_cli/test_model_alias_credentials.py@@ -86,13 +86,6 @@ class TestDirectAliasCredentialLoading:assert alias.api_key == "sk-literal"assert alias.key_env == "THETA_API_KEY"- def test_credential_fields_default_to_empty(self, monkeypatch):- """Aliases without credentials keep working (positional construction)."""- from hermes_cli.model_switch import DirectAlias-- alias = DirectAlias("theta-1", "custom", ALIAS_HOST)- assert alias.api_key == ""- assert alias.key_env == ""class TestNestedModelAliasesCredentials:@@ -525,13 +518,6 @@ class TestSchemelessBaseUrls:"http://localhost:11434/v1", "localhost:11434/v1") is False- def test_httpx_cannot_use_a_schemeless_base_url(self):- """Pins the premise above: this is why the strict answer is harmless."""- httpx = pytest.importorskip("httpx")-- assert httpx.URL("localhost:11434/v1").host == ""- assert httpx.URL("api.example.com/v1").host == ""- assert httpx.URL("http://localhost:11434/v1").host == "localhost"class TestAliasCacheIsProfileScoped:@@ -772,128 +758,3 @@ class TestOneshotPassesAliasCredential:assert captured["explicit_api_key"] == "sk-theta-ALIAS"-class TestNoProductionCodeMutatesTheAliasCacheInPlace:- """The profile-isolation property depends on an unwritten rule.-- ``_ensure_direct_aliases`` keeps a copy of what it loaded and treats any- divergence as a caller's data, not its own stale cache — that is what lets- tests seed ``DIRECT_ALIASES`` in place without the loader wiping them- (#16767). The cost is that a *production* in-place mutation would pin the- cache: contents would never again match the copy, so the config-identity- check that reloads on a profile switch would stop being consulted, and one- profile's aliases and credentials would be served to the next.-- No production code mutates it today — only the loader itself, and every- other reference is a read. This pins that, because the failure mode is- silent: nothing raises, nothing logs, and the leak only shows up as one- profile answering with another profile's key.- """-- #: The only place allowed to write the cache.- OWNER = ("hermes_cli/model_switch.py", "_ensure_direct_aliases")-- MUTATORS = frozenset(- {"update", "clear", "pop", "popitem", "setdefault", "__setitem__"}- )-- @staticmethod- def _production_sources():- import pathlib-- repo = pathlib.Path(__file__).resolve().parents[2]- skip = {".git", "node_modules", "tests", "build", "dist", ".venv"}- for path in repo.rglob("*.py"):- if any(part in skip for part in path.parts):- continue- yield path, path.relative_to(repo).as_posix()-- @classmethod- def _violations(cls, source: str, rel: str):- """Yield (function, description) for each in-place write."""- import ast-- tree = ast.parse(source)- enclosing = {}- for node in ast.walk(tree):- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):- for child in ast.walk(node):- enclosing[id(child)] = node.name-- def _names(node):- """DIRECT_ALIASES, whether bare or attribute-qualified."""- if isinstance(node, ast.Name):- return node.id- if isinstance(node, ast.Attribute):- return node.attr- return None-- for node in ast.walk(tree):- where = enclosing.get(id(node), "<module>")- if (rel, where) == cls.OWNER:- continue- if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):- if (- _names(node.func.value) == "DIRECT_ALIASES"- and node.func.attr in cls.MUTATORS- ):- yield where, f"DIRECT_ALIASES.{node.func.attr}()"- if isinstance(node, (ast.Assign, ast.AugAssign)):- targets = node.targets if isinstance(node, ast.Assign) else [node.target]- for target in targets:- if (- isinstance(target, ast.Subscript)- and _names(target.value) == "DIRECT_ALIASES"- ):- yield where, "DIRECT_ALIASES[...] = ..."-- def test_only_the_loader_writes_the_cache(self):- found = []- for path, rel in self._production_sources():- try:- source = path.read_text(encoding="utf-8")- except (OSError, UnicodeDecodeError):- continue- if "DIRECT_ALIASES" not in source:- continue- try:- found.extend(- f"{rel}:{where}: {what}"- for where, what in self._violations(source, rel)- )- except SyntaxError:- continue-- assert not found, (- "In-place writes to DIRECT_ALIASES outside "- f"{self.OWNER[0]}::{self.OWNER[1]} pin the alias cache and break "- "per-profile isolation:\n " + "\n ".join(found)- )-- def test_the_scan_actually_detects_a_violation(self):- """Negative control — an always-passing scanner would prove nothing."""- offending = (- "from hermes_cli.model_switch import DIRECT_ALIASES\n"- "def warm():\n"- " DIRECT_ALIASES.update({'x': 1})\n"- " DIRECT_ALIASES['y'] = 2\n"- )-- hits = list(self._violations(offending, "some/other_module.py"))-- assert {what for _, what in hits} == {- "DIRECT_ALIASES.update()",- "DIRECT_ALIASES[...] = ...",- }- assert all(where == "warm" for where, _ in hits)-- def test_the_owner_itself_is_exempt(self):- """...and an exemption that swallowed everything would prove nothing."""- import pathlib-- repo = pathlib.Path(__file__).resolve().parents[2]- source = (repo / self.OWNER[0]).read_text(encoding="utf-8")-- assert list(self._violations(source, self.OWNER[0])) == []- # The loader really does write in place, so the exemption is load-bearing.- assert "DIRECT_ALIASES.clear()" in source- assert "DIRECT_ALIASES.update(loaded)" in sourcediff --git a/tests/hermes_cli/test_model_cache_parallel_prefetch.py b/tests/hermes_cli/test_model_cache_parallel_prefetch.pyindex 61d8b15e3dd..c163d431a36 100644--- a/tests/hermes_cli/test_model_cache_parallel_prefetch.py+++ b/tests/hermes_cli/test_model_cache_parallel_prefetch.py@@ -10,10 +10,8 @@ concurrently via ThreadPoolExecutor before the serial picker loop starts.from __future__ import annotationsimport time-from unittest.mock import patch, MagicMock+from unittest.mock import patch-import pytest-from hermes_cli import model_switch_providers# ---------------------------------------------------------------------------@@ -194,58 +192,3 @@ class TestPrefetchProviderModelsParallel:# Integration: prefetch is called from list_authenticated_providers# ----------------------------------------------------------------------------class TestPrefetchIntegration:- """Verify ``list_authenticated_providers`` triggers parallel prefetch."""-- def test_prefetch_called_with_more_than_3_providers(self):- """When >3 providers are authed, parallel prefetch is invoked."""- from hermes_cli import model_switch-- slugs = [f"prov_{i}" for i in range(5)]- captured_slugs = []-- def mock_collect(data, curated, excluded):- return slugs-- with patch.object(model_switch_providers, "_collect_authed_provider_slugs", side_effect=mock_collect), \- patch.object(model_switch_providers, "_prefetch_provider_models_parallel") as prefetch:- try:- model_switch.list_authenticated_providers()- except Exception:- pass # we only care about the prefetch call- captured_slugs = prefetch.call_args[0][0] if prefetch.called else []-- assert prefetch.called- assert captured_slugs == slugs-- def test_prefetch_skipped_with_3_or_fewer_providers(self):- """When ≤3 providers are authed, parallel prefetch is skipped."""- from hermes_cli import model_switch-- slugs = ["prov_a", "prov_b"]-- def mock_collect(data, curated, excluded):- return slugs-- with patch.object(model_switch_providers, "_collect_authed_provider_slugs", side_effect=mock_collect), \- patch.object(model_switch_providers, "_prefetch_provider_models_parallel") as prefetch:- try:- model_switch.list_authenticated_providers()- except Exception:- pass-- prefetch.assert_not_called()-- def test_prefetch_skipped_on_refresh(self):- """When refresh=True, prefetch is skipped (serial path force-refreshes)."""- from hermes_cli import model_switch-- with patch.object(model_switch_providers, "_collect_authed_provider_slugs") as collect, \- patch.object(model_switch_providers, "_prefetch_provider_models_parallel") as prefetch:- try:- model_switch.list_authenticated_providers(refresh=True)- except Exception:- pass-- collect.assert_not_called()- prefetch.assert_not_called()diff --git a/tests/hermes_cli/test_model_cost_guard.py b/tests/hermes_cli/test_model_cost_guard.pyindex aeb3b3cd141..887f18a5adf 100644--- a/tests/hermes_cli/test_model_cost_guard.py+++ b/tests/hermes_cli/test_model_cost_guard.py@@ -38,8 +38,6 @@ def test_warns_when_models_dev_input_price_exceeds_threshold():assert warning is not Noneassert warning.input_cost_per_million == Decimal("20.01")- assert "EXPENSIVE MODEL WARNING" in warning.message- assert "$20/M input" in warning.message@pytest.mark.parametrize("provider", ["custom", "custom:routerai", "routerai"])@@ -122,21 +120,6 @@ def test_warns_when_pricing_entry_output_price_exceeds_threshold(monkeypatch):assert "$100.01/M" in warning.message-def test_openai_gpt55_pro_adds_suggestion(monkeypatch):- monkeypatch.setattr("agent.models_dev.get_model_info", lambda *_args, **_kwargs: None)- monkeypatch.setattr(- "agent.usage_pricing.get_pricing_entry",- lambda *_args, **_kwargs: PricingEntry(- input_cost_per_million=Decimal("25"),- output_cost_per_million=Decimal("125"),- source="provider_models_api",- ),- )-- warning = expensive_model_warning("openai/gpt-5.5-pro", provider="openrouter")-- assert warning is not None- assert "did you mean to select openai/gpt-5.5?" in warning.messagedef test_openai_gpt55_pro_warns_even_without_pricing(monkeypatch):diff --git a/tests/hermes_cli/test_model_data_policy_guard.py b/tests/hermes_cli/test_model_data_policy_guard.pyindex 2546dba15d8..8ab7c068266 100644--- a/tests/hermes_cli/test_model_data_policy_guard.py+++ b/tests/hermes_cli/test_model_data_policy_guard.py@@ -10,13 +10,7 @@ def test_fires_on_meta_contributor():w = data_training_warning("muse-spark-1.2-contributor", provider="meta-ai")assert isinstance(w, DataTrainingWarning)assert w.model == "muse-spark-1.2-contributor"- assert "train" in w.message.lower()- assert "-contributor" in w.message.lower() or "contributor" in w.message.lower() # mentions the tier- # Points to Meta's live pricing page instead of hardcoding prices.- assert "pricing and rate limits" in w.message.lower()- assert "$0.10" not in w.message and "$0.20" not in w.message and "$0.002" not in w.message- assert "prompts and completions" in w.message.lower()- assert "dev.meta.ai/docs/pricing-rate-limits" in w.message+ assert w.messagedef test_silent_on_non_contributor_muse():diff --git a/tests/hermes_cli/test_model_normalize.py b/tests/hermes_cli/test_model_normalize.pyindex 3e3263f4825..3b368d0ee77 100644--- a/tests/hermes_cli/test_model_normalize.py+++ b/tests/hermes_cli/test_model_normalize.py@@ -7,9 +7,7 @@ import pytestfrom hermes_cli.model_normalize import (normalize_model_for_provider,- _DOT_TO_HYPHEN_PROVIDERS,_normalize_for_deepseek,- detect_vendor,)@@ -29,28 +27,15 @@ class TestIssue5211OpenCodeGoDotPreservation:result = normalize_model_for_provider(model, "opencode-go")assert result == expected, f"Expected {expected!r}, got {result!r}"- def test_opencode_go_not_in_dot_to_hyphen_set(self):- """opencode-go must NOT be in the dot-to-hyphen provider set."""- assert "opencode-go" not in _DOT_TO_HYPHEN_PROVIDERS-# ── Anthropic dot-to-hyphen conversion (regression) ────────────────────-class TestAnthropicDotToHyphen:- """Anthropic API still needs dots→hyphens."""-# ── OpenCode Zen regression ────────────────────────────────────────────-class TestOpenCodeZenModelNormalization:- """OpenCode Zen preserves dots for most models, but Claude stays hyphenated."""-# ── Copilot dot preservation (regression) ──────────────────────────────-class TestCopilotDotPreservation:- """Copilot preserves dots in model names."""-# ── Copilot model-name normalization (issue #6879 regression) ──────────@@ -64,7 +49,6 @@ class TestCopilotModelNormalization:the request with HTTP 400 "model_not_supported"."""-def test_openai_codex_still_strips_openai_prefix(self):"""Regression: openai-codex must still strip the openai/ prefix."""assert normalize_model_for_provider("openai/gpt-5.4", "openai-codex") == "gpt-5.4"@@ -72,22 +56,6 @@ class TestCopilotModelNormalization:# ── Aggregator providers (regression) ──────────────────────────────────-class TestAggregatorProviders:- """Aggregators need vendor/model slugs."""---class TestCustomProviderIsNotAVendorIdentity:- """``custom`` is a generic bucket, not a vendor -- an alias that merely- *resolves to* ``custom`` (e.g. ``ollama`` -> ``custom`` in- ``_PROVIDER_ALIASES``) must not be treated as a redundant prefix the- way ``zai/``, ``gemini/``, etc. are for their own native providers.-- Regression for: a named custom provider (e.g. a LiteLLM proxy fronting- Ollama) registers its own routing name as ``ollama/glm-5.2``. Stripping- the ``ollama/`` prefix because it happens to alias to ``custom``- produced a bare ``glm-5.2`` the proxy doesn't recognise.- """-# ── detect_vendor ──────────────────────────────────────────────────────@@ -103,7 +71,6 @@ class TestDeepseekVSeriesPassThrough:silently downgrading users who picked V4."""-def test_deepseek_provider_preserves_v4_pro(self):"""End-to-end via normalize_model_for_provider — user selectingV4 Pro must reach DeepSeek's API as V4 Pro, not V3 alias."""@@ -199,7 +166,6 @@ class TestIssue78796NvidiaPrefixRepair:)-class TestColonProviderPrefixIsStrippedLikeSlash:"""Issue #64787: ``-m openai-codex:gpt-5.6-sol`` (Hermes's own ``provider:model`` switch syntax)reached the Codex wire with the prefix attached and got HTTP 400. A matching ``provider:`` prefixdiff --git a/tests/hermes_cli/test_model_provider_persistence.py b/tests/hermes_cli/test_model_provider_persistence.pyindex e3a1d0639de..80085bd94ed 100644--- a/tests/hermes_cli/test_model_provider_persistence.py+++ b/tests/hermes_cli/test_model_provider_persistence.py@@ -6,7 +6,7 @@ isinstance(model, dict)) to silently fail — leaving the provider unset andfalling back to auto-detection."""-from unittest.mock import patch, MagicMock+from unittest.mock import patchimport pytest@@ -111,11 +111,6 @@ class TestProviderPersistsAfterModelSave:assert model.get("default") == "kimi-k2.5"-----class TestBaseUrlValidation:"""Reject non-URL values in the base URL prompt (e.g. shell commands).@@ -125,7 +120,6 @@ class TestBaseUrlValidation:TestZaiEndpointPicker below."""-def test_empty_base_url_keeps_default(self, config_home, monkeypatch):"""Pressing Enter (empty) should not change the base URL."""from hermes_cli.auth import PROVIDER_REGISTRY@@ -152,9 +146,7 @@ class TestBaseUrlValidation:class TestZaiEndpointPicker:"""Z.AI setup should present a curses picker for endpoint selection."""--- def test_custom_proxy_rejects_invalid_url(self, config_home, monkeypatch, capsys):+ def test_custom_proxy_rejects_invalid_url(self, config_home, monkeypatch):"""Custom proxy must start with http:// or https://."""from hermes_cli.model_setup_flows import _model_flow_api_key_providerfrom hermes_cli.config import load_config@@ -173,9 +165,6 @@ class TestZaiEndpointPicker:# The invalid URL should not have been saved as base_urlmodel = load_config()["model"]assert model["base_url"] != "not-a-url"- captured = capsys.readouterr()- assert "Invalid URL" in captured.out-def test_current_endpoint_is_default_choice(self, config_home, monkeypatch):"""When a known endpoint is already active, it should be the default."""@@ -197,4 +186,3 @@ class TestZaiEndpointPicker:# Default should point at index 2 (coding-global)assert captured["default"] == 2assert result == coding_url-diff --git a/tests/hermes_cli/test_model_search.py b/tests/hermes_cli/test_model_search.pyindex a4306086039..add3b740eff 100644--- a/tests/hermes_cli/test_model_search.py+++ b/tests/hermes_cli/test_model_search.py@@ -16,17 +16,9 @@ def test_filter_indices_surfaces_k3_for_kimi_query():assert "k3" in ranked-def test_model_search_text_adds_ox_alpha_aliases():- assert model_search_text("x-preview-f-free") == "x-preview-f-free ox-alpha ox"- assert model_search_text("X-Preview-F-Free") == "X-Preview-F-Free ox-alpha ox"--def test_filter_indices_surfaces_ox_alpha_preview_slug():models = ["x-preview-f-free", "gpt-5.6-sol", "kimi-k3"]haystacks = [model_search_text(m) for m in models]for query in ("ox", "ox-alpha"):ranked = [models[i] for i in _filter_indices(haystacks, query)]assert "x-preview-f-free" in ranked, query---diff --git a/tests/hermes_cli/test_model_selection_guards.py b/tests/hermes_cli/test_model_selection_guards.pyindex e5d0b1e300a..61dbaab5312 100644--- a/tests/hermes_cli/test_model_selection_guards.py+++ b/tests/hermes_cli/test_model_selection_guards.py@@ -4,7 +4,6 @@ from unittest.mock import patchfrom hermes_cli.model_selection_guards import (SelectionWarning,- combined_message,combined_selection_warning,selection_warnings,)@@ -22,7 +21,6 @@ def test_data_policy_guard_fires_through_registry():assert "data_policy" in kindsw = next(w for w in warnings if w.kind == "data_policy")assert "train" in w.message.lower()- assert w.title == "Data-Training Tier Warning"def test_include_kinds_filters_guards():@@ -78,12 +76,6 @@ def test_misbehaving_guard_never_breaks_selection():assert selection_warnings("anything") == []-def test_combined_message_joins_blocks():- a = SelectionWarning("cost", "t1", "m", "p", "AAA")- b = SelectionWarning("data_policy", "t2", "m", "p", "BBB")- assert combined_message([a, b]) == "AAA\n\nBBB"--def test_cost_guard_still_fires_through_registry():# The registry must preserve the existing cost-guard behavior; feed it# explicit model_info so no network lookup is needed.diff --git a/tests/hermes_cli/test_model_switch_context_display.py b/tests/hermes_cli/test_model_switch_context_display.pyindex 4f151e0395d..bbe2538ef1d 100644--- a/tests/hermes_cli/test_model_switch_context_display.py+++ b/tests/hermes_cli/test_model_switch_context_display.py@@ -41,23 +41,6 @@ class TestResolveDisplayContextLength:"Codex OAuth's 272K cap must win over models.dev's 1.05M for gpt-5.5")---- def test_prefers_resolver_even_when_model_info_has_larger_value(self):- """Invariant: provider-aware resolver is authoritative, even if models.dev- reports a bigger window."""- fake_mi = _FakeModelInfo(2_000_000)- with patch(- "agent.model_metadata.get_model_context_length", return_value=128_000- ):- ctx = resolve_display_context_length(- "capped-model",- "capped-provider",- model_info=fake_mi,- )- assert ctx == 128_000-def test_custom_providers_override_honored(self):"""Regression for #15779: /model switch onto a custom provider mustsurface the configured per-model context_length, not the 128K/256K@@ -90,6 +73,3 @@ class TestResolveDisplayContextLength:"custom_providers[].models.gpt-5.5.context_length=1.05M must win ""over probe-down fallback")---diff --git a/tests/hermes_cli/test_model_switch_context_offload.py b/tests/hermes_cli/test_model_switch_context_offload.pyindex c44bfd6bbfe..fd63bd181a1 100644--- a/tests/hermes_cli/test_model_switch_context_offload.py+++ b/tests/hermes_cli/test_model_switch_context_offload.py@@ -11,7 +11,6 @@ the sync helper directly, freezing the loop for every user on every platform forthe duration of the probe ladder."""-import asyncioimport threadingimport time@@ -20,7 +19,7 @@ import pytestimport agent.model_metadata as model_meta_modfrom hermes_cli import model_switch-PROBE_SECONDS = 0.4+PROBE_SECONDS = 0.05RESOLVE_ARGS = dict(model="claude-opus-4",@@ -62,38 +61,3 @@ async def test_resolution_runs_off_the_event_loop_thread(slow_probe):loop_thread = threading.current_thread()await model_switch.resolve_display_context_length_async(**RESOLVE_ARGS)assert slow_probe["thread"] is not loop_thread---async def test_event_loop_stays_responsive_during_resolution(slow_probe):- """A concurrent heartbeat keeps ticking while the probe ladder runs.-- This is the regression: with the bare sync call the loop stalled for the- full probe duration, which is what times out Discord heartbeats and stalls- Telegram polling for every other chat.- """- lags = []- stop = asyncio.Event()-- async def heartbeat():- interval = 0.02- while not stop.is_set():- t0 = time.monotonic()- try:- await asyncio.wait_for(stop.wait(), timeout=interval)- except asyncio.TimeoutError:- pass- lags.append(time.monotonic() - t0 - interval)-- hb = asyncio.create_task(heartbeat())- await asyncio.sleep(0.05) # let the heartbeat settle-- ctx = await model_switch.resolve_display_context_length_async(**RESOLVE_ARGS)-- stop.set()- await hb-- assert ctx == 128000- # The loop was never blocked for anything close to the probe duration.- assert max(lags) < PROBE_SECONDS / 2, f"event loop stalled {max(lags):.3f}s"-diff --git a/tests/hermes_cli/test_model_switch_custom_providers.py b/tests/hermes_cli/test_model_switch_custom_providers.pyindex 3e56fa1bd56..ee43cb16d79 100644--- a/tests/hermes_cli/test_model_switch_custom_providers.py+++ b/tests/hermes_cli/test_model_switch_custom_providers.py@@ -178,26 +178,6 @@ def test_picker_empty_native_catalog_is_not_stale_served(monkeypatch):assert _fetch_picker_live_models("sk-ollama", url, "custom", False) == ["back:latest"]-def test_picker_generic_discovery_preserves_api_mode(monkeypatch):- calls = []-- def cached(*args, **kwargs):- calls.append((args, kwargs))- return ["model-a"]-- monkeypatch.setattr(- "hermes_cli.models_local.should_use_ollama_native_catalog", lambda *a, **k: False- )- monkeypatch.setattr("hermes_cli.models.cached_fetch_api_models", cached)-- assert _fetch_picker_live_models(- "key",- "https://proxy.example/anthropic/v1",- "custom",- False,- api_mode="anthropic_messages",- ) == ["model-a"]- assert calls[0][1]["api_mode"] == "anthropic_messages"def test_list_authenticated_providers_includes_custom_providers(monkeypatch):@@ -446,7 +426,6 @@ def test_list_authenticated_providers_includes_active_bare_custom_endpoint(monkebare_custom = next((p for p in providers if p["slug"] == "custom"), None)assert bare_custom is not None- assert bare_custom["name"] == "Custom endpoint"assert bare_custom["is_current"] is Trueassert bare_custom["is_user_defined"] is Trueassert bare_custom["models"] == ["gpt-4o"]@@ -495,7 +474,6 @@ def test_switch_model_accepts_explicit_bare_custom_current_endpoint(monkeypatch)assert result.success is Trueassert result.target_provider == "custom"- assert result.provider_label == "Custom endpoint"assert result.new_model == "gpt-4o-mini"assert result.base_url == "https://www.ccsub.net/v1"assert result.api_key == "sk-test"@@ -628,8 +606,6 @@ def test_is_aggregator_recognizes_named_custom_provider():assert providers_mod.is_aggregator("custom:litellm") is True-def test_is_aggregator_leaves_unknown_provider_non_aggregator():- assert providers_mod.is_aggregator("not-a-provider") is Falsedef test_switch_model_does_not_send_ollama_headers_to_unrelated_custom_endpoint(monkeypatch):@@ -690,21 +666,6 @@ def test_switch_model_does_not_send_ollama_headers_to_unrelated_custom_endpoint(-def test_is_routing_aggregator_excludes_flat_namespace_resellers():- """opencode-go / opencode-zen stay ``is_aggregator=True`` (model-switch- relies on it to search their flat bare-name catalog), but they are NOT- routing aggregators — their models are first-party, so the picker dedup- must not strip them. (#47077)"""- # Still aggregators for model-switch flat-catalog resolution.- assert providers_mod.is_aggregator("opencode-go") is True- assert providers_mod.is_aggregator("opencode-zen") is True- # But NOT routing aggregators for picker-dedup purposes.- assert providers_mod.is_routing_aggregator("opencode-go") is False- assert providers_mod.is_routing_aggregator("opencode-zen") is False- # True routers and custom proxies remain routing aggregators.- assert providers_mod.is_routing_aggregator("openrouter") is True- assert providers_mod.is_routing_aggregator("custom:litellm") is True- assert providers_mod.is_routing_aggregator("not-a-provider") is Falsedef test_picker_selection_resolves_named_custom_provider_model_id(monkeypatch):@@ -842,51 +803,12 @@ def test_custom_provider_no_key_singular_model_still_probes_live_models(monkeypamax_models=50,)- assert calls == [- ("", "http://localhost:8080/v1", {- "timeout": 5.0,- "api_mode": None,- "headers": None,- })- ]+ assert [(key, url) for key, url, _kw in calls] == [("", "http://localhost:8080/v1")]row = next(p for p in providers if p["name"] == "Local llama.cpp")assert row["models"] == ["llama3", "mistral", "qwen3-coder"]assert row["total_models"] == 3-def test_custom_provider_model_metadata_dict_still_probes(monkeypatch):- """Dict-shaped ``models:`` is metadata, not an explicit allowlist."""- monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})- monkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})- calls = []-- def fetch(*args, **kwargs):- calls.append((args, kwargs))- return ["unexpected-live-model"]-- monkeypatch.setattr("hermes_cli.models.fetch_api_models", fetch)-- providers = list_authenticated_providers(- current_provider="custom:local-ollama",- user_providers={},- custom_providers=[- {- "name": "Local Ollama",- "base_url": "http://localhost:11434/v1",- "model": "llama3",- "models": {"llama3": {}},- }- ],- )-- row = next(p for p in providers if p["name"] == "Local Ollama")- assert calls == [- (- ("", "http://localhost:11434/v1"),- {"timeout": 5.0, "api_mode": None, "headers": None},- )- ]- assert row["models"] == ["unexpected-live-model"]def test_custom_provider_group_explicit_duplicate_skips_probe(monkeypatch):@@ -961,13 +883,7 @@ def test_custom_provider_current_only_probe_respects_explicit_catalog(monkeypatcprobe_current_custom_provider=True,)- assert calls == [- (- "",- "http://active.local/v1",- {"timeout": 5.0, "api_mode": None, "headers": None},- )- ]+ assert [url for _key, url, _kw in calls] == ["http://active.local/v1"]rows = {row["name"]: row for row in providers if row.get("is_user_defined")}assert rows["Active"]["models"] == ["live-a", "live-b"]assert rows["Offline"]["models"] == ["offline-seed"]@@ -1033,13 +949,7 @@ def test_custom_provider_empty_explicit_list_allows_probe(monkeypatch):],)- assert calls == [- (- "",- "http://local.test/v1",- {"timeout": 5.0, "api_mode": None, "headers": None},- )- ]+ assert [url for _key, url, _kw in calls] == ["http://local.test/v1"]row = next(p for p in providers if p["name"] == "Local")assert row["models"] == ["live-a", "live-b"]@@ -1113,32 +1023,6 @@ def test_list_enumerates_dict_format_models_without_singular_model(monkeypatch):assert thor_rows[0]["total_models"] == 3-def test_list_dedupes_dict_model_matching_singular_default(monkeypatch):- """When the singular ``model:`` is also a key in the ``models:`` dict,- it must appear exactly once in the picker."""- monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})- monkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})-- providers = list_authenticated_providers(- current_provider="openai-codex",- user_providers={},- custom_providers=[- {- "name": "DeepSeek",- "base_url": "https://api.deepseek.com",- "model": "deepseek-chat",- "models": {- "deepseek-chat": {"context_length": 128000},- "deepseek-reasoner": {"context_length": 128000},- },- }- ],- max_models=50,- )-- ds_rows = [p for p in providers if p["name"] == "DeepSeek"]- assert ds_rows[0]["models"].count("deepseek-chat") == 1- assert ds_rows[0]["models"] == ["deepseek-chat", "deepseek-reasoner"]@@ -1411,30 +1295,6 @@ def test_list_authenticated_providers_same_url_different_key_env_and_api_mode_stassert by_slug["custom:claude"]["is_current"] is False-def test_list_authenticated_providers_total_models_reflects_grouped_count(monkeypatch):- """After grouping six entries into one row, total_models must reflect- the full count, and every grouped model appears in the list."""- monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})- monkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})-- entries = [- {"name": f"Ollama \u2014 Model {i}", "base_url": "http://localhost:11434/v1",- "api_key": "ollama", "model": f"model-{i}"}- for i in range(6)- ]- providers = list_authenticated_providers(- user_providers={},- custom_providers=entries,- max_models=4,- probe_custom_providers=False,- )-- groups = [p for p in providers if p.get("is_user_defined")]- assert len(groups) == 1- group = groups[0]- assert group["total_models"] == 6- # All six models are preserved in the grouped row.- assert sorted(group["models"]) == sorted(f"model-{i}" for i in range(6))def test_lmstudio_picker_probes_active_config_base_url(monkeypatch):@@ -1653,12 +1513,8 @@ def test_custom_providers_uses_live_models_for_multi_model_endpoint(monkeypatch))assert gateway_prov is not None, "Custom provider group not found in results"- assert calls == [- (- "sk-gateway-key",- "https://gateway.example.com/v1",- {"timeout": 5.0, "api_mode": None, "headers": None},- )+ assert [(key, url) for key, url, _kw in calls] == [+ ("sk-gateway-key", "https://gateway.example.com/v1")], "fetch_api_models must be called with the custom provider's credentials"assert gateway_prov["models"] == ["gateway-model-a",diff --git a/tests/hermes_cli/test_model_switch_parsing.py b/tests/hermes_cli/test_model_switch_parsing.pyindex 4a2ff97d38d..4310ec62cf2 100644--- a/tests/hermes_cli/test_model_switch_parsing.py+++ b/tests/hermes_cli/test_model_switch_parsing.py@@ -1,24 +1,10 @@-"""Single-owner /model parsing + effective-model resolution tests.+"""Single-owner /model argument parsing (hermes_cli.model_switch.parse_model_switch_args)."""-Covers the consolidation of the 7 historical parsing/resolution variants-into hermes_cli.model_switch (parse_model_switch_args +-resolve_effective_model), including the 7dd00bb47d regression class-(api_server discarding session-persisted models) as a permanent parity-test against the pre-consolidation logic captured from origin/main.--Real imports throughout (AGENTS.md: no mocks for resolution chains).-"""--import pytestfrom hermes_cli.model_switch import (- MODEL_SWITCH_ERR_ONCE_REQUIRES_TARGET,MODEL_SWITCH_ERR_ONCE_WITH_GLOBAL,MODEL_SWITCH_ERROR_TEXT,- ModelSwitchRequest,- parse_model_flags_detailed,parse_model_switch_args,- resolve_effective_model,)@@ -27,7 +13,6 @@ from hermes_cli.model_switch import (# ----------------------------------------------------------------------------def test_provider_flag_and_scopes():req = parse_model_switch_args("sonnet --provider anthropic --global")assert req.target == "sonnet"@@ -44,89 +29,4 @@ def test_provider_flag_and_scopes():def test_once_with_global_conflict():req = parse_model_switch_args("sonnet --once --global")assert MODEL_SWITCH_ERR_ONCE_WITH_GLOBAL in req.errors- assert (- MODEL_SWITCH_ERROR_TEXT[MODEL_SWITCH_ERR_ONCE_WITH_GLOBAL]- == "/model --once cannot be combined with --global"- )- assert "/model --once cannot be combined with --global" in req.error_messages()-----# ----------------------------------------------------------------------------# resolve_effective_model — session > channel/session-persisted > global-# -----------------------------------------------------------------------------class _ChannelOverride:- def __init__(self, model):- self.model = model---------# ----------------------------------------------------------------------------# Parity: run.py-style channel resolution (old logic from origin/main)-# -----------------------------------------------------------------------------def _old_run_py_resolve(override, global_model):- # Captured from origin/main gateway/run.py:_resolve_model_for_channel:- # if override and override.model:- # return override.model- # return _resolve_gateway_model(user_config)- if override and override.model:- return override.model- return global_model-----# ----------------------------------------------------------------------------# Parity: api_server-style resolution (old logic from origin/main)-# -----------------------------------------------------------------------------def _clean(value):- # api_server._clean_request_string equivalent for the parity harness.- if value is None:- return None- text = str(value).strip()- return text or None---def _old_api_server_resolve(session_override, session_row_model, global_model):- # Captured from origin/main gateway/platforms/api_server.py:_create_agent- # (post-7dd00bb47d — session /model override > session-persisted model >- # global default):- model = global_model- if session_override:- model = (_clean(session_override.get("model")) or model)- elif _clean(session_row_model):- model = _clean(session_row_model)- return model--- "session_override,session_row_model,global_model",- [- (None, None, "global-model"),- (None, "session-persisted", "global-model"), # the 7dd00bb47d regression- ({"model": "override-model"}, "session-persisted", "global-model"),- ({"model": ""}, "session-persisted", "global-model"),- ({"model": "override-model"}, None, "global-model"),- (None, " ", "global-model"),- ],-)-def test_api_server_resolution_parity(session_override, session_row_model, global_model):- # New logic mirrors the migrated api_server code path exactly:- if session_override:- new = resolve_effective_model(session_override, None, global_model)- elif _clean(session_row_model):- new = resolve_effective_model(None, session_row_model, global_model)- else:- new = global_model- assert new == _old_api_server_resolve(session_override, session_row_model, global_model)--+ assert MODEL_SWITCH_ERROR_TEXT[MODEL_SWITCH_ERR_ONCE_WITH_GLOBAL] in req.error_messages()diff --git a/tests/hermes_cli/test_model_validation.py b/tests/hermes_cli/test_model_validation.pyindex 4b7430e63fc..b6597246347 100644--- a/tests/hermes_cli/test_model_validation.py+++ b/tests/hermes_cli/test_model_validation.py@@ -3,7 +3,7 @@import pytestfrom unittest.mock import MagicMock, patch-from hermes_cli.models import azure_foundry_model_api_mode, copilot_model_api_mode, fetch_github_model_catalog, curated_models_for_provider, fetch_api_models, github_model_reasoning_efforts, normalize_copilot_model_id, normalize_opencode_model_id, normalize_provider, opencode_model_api_mode, parse_model_input, probe_api_models, provider_label, provider_model_ids+from hermes_cli.models import azure_foundry_model_api_mode, copilot_model_api_mode, curated_models_for_provider, fetch_api_models, normalize_provider, opencode_model_api_mode, parse_model_input, probe_api_models, provider_model_idsfrom hermes_cli.models_local import fetch_lmstudio_modelsfrom hermes_cli.models_validate import validate_requested_model@@ -45,17 +45,6 @@ class TestParseModelInput:# -- curated_models_for_provider ---------------------------------------------class TestCuratedModelsForProvider:- def test_openrouter_returns_curated_list(self):- with patch(- "hermes_cli.models.fetch_openrouter_models",- return_value=[- ("anthropic/claude-opus-4.6", "recommended"),- ("qwen/qwen3.6-plus", ""),- ],- ):- models = curated_models_for_provider("openrouter")- assert len(models) > 0- assert any("claude" in m[0] for m in models)def test_unknown_provider_returns_empty(self):assert curated_models_for_provider("totally-unknown") == []@@ -81,32 +70,11 @@ class TestNormalizeProvider:assert normalize_provider("github-copilot") == "copilot"-class TestProviderLabel:- def test_known_labels_and_auto(self):- assert provider_label("anthropic") == "Anthropic"- assert provider_label("kimi") == "Kimi / Kimi Coding Plan"- assert provider_label("stepfun") == "StepFun Step Plan"- assert provider_label("copilot") == "GitHub Copilot"- assert provider_label("copilot-acp") == "GitHub Copilot ACP"- assert provider_label("auto") == "Auto"--# -- provider_model_ids ------------------------------------------------------class TestProviderModelIds:- def test_stepfun_prefers_live_catalog(self):- with patch(- "hermes_cli.auth.resolve_api_key_provider_credentials",- return_value={"api_key": "***", "base_url": "https://api.stepfun.com/step_plan/v1"},- ), patch(- "hermes_cli.models.fetch_api_models",- return_value=["step-3.5-flash", "step-3-agent-lite"],- ):- assert provider_model_ids("stepfun") == ["step-3.5-flash", "step-3-agent-lite"]--def test_anthropic_provider_uses_configured_base_url_for_live_catalog(self):class _Resp:def __enter__(self):@@ -214,20 +182,6 @@ class TestFetchApiModels:assert probe["used_fallback"] is False-class TestGithubReasoningEfforts:- def test_gpt5_supports_minimal_to_high(self):- catalog = [{- "id": "gpt-5.4",- "capabilities": {"type": "chat", "supports": {"reasoning_effort": ["low", "medium", "high"]}},- "supported_endpoints": ["/responses"],- }]- assert github_model_reasoning_efforts("gpt-5.4", catalog=catalog) == [- "low",- "medium",- "high",- ]--class TestCopilotNormalization:def test_copilot_api_mode_gpt5_uses_responses(self):@@ -239,9 +193,6 @@ class TestCopilotNormalization:assert copilot_model_api_mode("gpt-5.2") == "codex_responses"---def test_opencode_go_api_modes_match_docs(self):assert opencode_model_api_mode("opencode-go", "glm-5.1") == "chat_completions"assert opencode_model_api_mode("opencode-go", "opencode-go/glm-5.1") == "chat_completions"@@ -459,10 +410,6 @@ class TestValidateApiFallback:"""----def test_fetch_lmstudio_models_filters_embedding_type(self):mock_resp = MagicMock()mock_resp.__enter__.return_value = mock_resp@@ -480,7 +427,6 @@ class TestValidateApiFallback:assert models == ["publisher/chat-model"]-def test_validate_lmstudio_distinguishes_auth_failure(self):import urllib.error@@ -504,7 +450,6 @@ class TestValidateApiFallback:assert "LM_API_KEY" in result["message"]-# -- validate — the requested id is never rewritten -----------------------------class TestRequestedIdIsNeverRewritten:@@ -622,8 +567,6 @@ class TestProbeApiModelsUserAgent:assert req.get_header("Authorization") is None--# -- validate — OpenRouter routing-variant suffixes (:nitro / :floor / ...) ----class TestValidateOpenRouterVariantSuffixes:@@ -651,12 +594,6 @@ class TestValidateOpenRouterVariantSuffixes:assert result.get("corrected_model") is Noneassert result["message"] is None- def test_variant_not_fuzzy_corrected_to_base(self):- """The old failure mode: get_close_matches would 'fix' model:nitro- to the bare base id and silently drop the routing behavior."""- result = self._validate("x-ai/grok-4.6:nitro")- assert result["accepted"] is True- assert result.get("corrected_model") is Nonedef test_variant_on_unknown_base_rejected(self):result = self._validate("x-ai/notreal-model:nitro")@@ -677,15 +614,6 @@ class TestValidateOpenRouterVariantSuffixes:assert result["accepted"] is Trueassert result.get("corrected_model") is None- def test_non_openrouter_provider_unaffected(self):- """The variant carve-out is OpenRouter-only; other providers keep- their existing behavior for colon-suffixed names."""- result = _validate(- "x-ai/grok-4.6:nitro",- "groq",- api_models=["x-ai/grok-4.6"],- )- assert result.get("corrected_model") != "x-ai/grok-4.6:nitro"def test_static_catalog_fallback_accepts_variant(self):"""Gateway path: /models unreachable → static catalog validates the@@ -815,23 +743,6 @@ class TestValidateRequestedModelNousPortalRecommendations:mock_portal.assert_not_called()assert result["accepted"] is False- def test_curated_catalog_hit_short_circuits_before_portal_check(self):- """When the curated-catalog fallback already accepts the model, the- Portal feed should not need to be consulted at all (cheaper, and- avoids an unnecessary network call on the common path)."""- api_models = ["inclusionai/ling-2.6-flash"]- probe_payload = {- "models": api_models, "probed_url": "x", "resolved_base_url": "x",- "suggested_base_url": None, "used_fallback": False,- }- with patch("hermes_cli.models.fetch_api_models", return_value=api_models), \- patch("hermes_cli.models.probe_api_models", return_value=probe_payload), \- patch("hermes_cli.models._model_in_provider_catalog", return_value=True), \- patch("hermes_cli.models.fetch_nous_recommended_models") as mock_portal:- result = validate_requested_model("inclusionai/ling-2.6-flash", "nous")- mock_portal.assert_not_called()- assert result["accepted"] is True-# -- validate — custom endpoint fallback when /models is unreachable (#12220) --@@ -865,13 +776,9 @@ class TestValidateCustomUnreachableFallback:result = self._validate("kimi-k3", "kimi-coding", models=["k3", "k3-turbo"], api_mode="anthropic_messages")assert (result["accepted"], result["persist"], result["recognized"]) == (True, True, False)assert "do not implement" not in result["message"]- assert "not named in this endpoint's model listing" in result["message"]assert "`k3`" in result["message"]# Case-only spelling differences are a match, not a warning.assert self._validate("K3", "kimi-coding", models=["k3"], api_mode="anthropic_messages")["recognized"] is True- # The unreachable-listing wording is unchanged.- unreachable = self._validate("kimi-k3", "kimi-coding", models=None, api_mode="anthropic_messages")- assert "do not implement GET /v1/models" in unreachable["message"]# -- validate — profile-owned catalog is authoritative (#116667) ----------------diff --git a/tests/hermes_cli/test_model_validation_managed_local.py b/tests/hermes_cli/test_model_validation_managed_local.pyindex 72ed7c31914..d9a4814f615 100644--- a/tests/hermes_cli/test_model_validation_managed_local.py+++ b/tests/hermes_cli/test_model_validation_managed_local.py@@ -41,9 +41,7 @@ class TestManagedLocalValidation:True,True,)- assert "managed local-models library" in result["message"]def test_not_staged_and_not_live_still_rejected(self):result = _validate("Llama-4-90B-Q4_K_M", staged=())assert result["accepted"] is False- assert "was not found in this provider's model listing" in result["message"]diff --git a/tests/hermes_cli/test_models.py b/tests/hermes_cli/test_models.pyindex 59726061b2c..86053627d0a 100644--- a/tests/hermes_cli/test_models.py+++ b/tests/hermes_cli/test_models.py@@ -9,39 +9,15 @@ from unittest.mock import patch, MagicMockfrom hermes_cli.nous_account import NousPortalAccountInfofrom hermes_cli.models import (- OPENROUTER_MODELS, fetch_openrouter_models, model_ids, detect_provider_for_model,+ OPENROUTER_MODELS, fetch_openrouter_models, detect_provider_for_model,partition_nous_models_by_tier,- check_nous_free_tier, _FREE_TIER_CACHE_TTL,- union_with_portal_free_recommendations,+ check_nous_free_tier, union_with_portal_free_recommendations,union_with_portal_paid_recommendations,)import hermes_cli.models as _models_modfrom hermes_cli import models_localfrom hermes_cli import models_validate-LIVE_OPENROUTER_MODELS = [- ("anthropic/claude-opus-4.6", "recommended"),- ("qwen/qwen3.7-max", ""),- ("nvidia/nemotron-3-super-120b-a12b:free", "free"),-]---class TestModelIds:- def test_returns_non_empty_list(self):- with patch("hermes_cli.models.fetch_openrouter_models", return_value=LIVE_OPENROUTER_MODELS):- ids = model_ids()- assert isinstance(ids, list)- assert len(ids) > 0---class TestOpenRouterModels:- def test_structure_is_list_of_tuples(self):- for entry in OPENROUTER_MODELS:- assert isinstance(entry, tuple) and len(entry) == 2- mid, desc = entry- assert isinstance(mid, str) and len(mid) > 0- assert isinstance(desc, str)-class TestFetchOpenRouterModels:@@ -109,16 +85,9 @@ class TestFetchOpenRouterModels:assert "google/gemini-3-pro-image-preview" not in ids-class TestOpenRouterToolSupportHelper:"""Unit tests for _openrouter_model_supports_tools (Kilo port #9068)."""- def test_tools_in_supported_parameters(self):- from hermes_cli.models import _openrouter_model_supports_tools- assert _openrouter_model_supports_tools(- {"id": "x", "supported_parameters": ["temperature", "tools"]}- ) is True-def test_empty_supported_parameters_list_drops_model(self):"""Explicit empty list → no tools → drop."""@@ -128,17 +97,9 @@ class TestOpenRouterToolSupportHelper:) is False-class TestFindOpenrouterSlug:- def test_exact_match(self):- from hermes_cli.models import _find_openrouter_slug- with patch("hermes_cli.models.fetch_openrouter_models", return_value=LIVE_OPENROUTER_MODELS):- assert _find_openrouter_slug("anthropic/claude-opus-4.6") == "anthropic/claude-opus-4.6"--class TestDetectProviderForModel:-def test_short_alias_resolves_to_static_model(self):"""Short aliases (e.g. sonnet) should resolve without network lookups."""with patch(@@ -151,9 +112,6 @@ class TestDetectProviderForModel:assert result[1].startswith("claude-sonnet")---def test_custom_provider_not_overridden_by_static_catalog(self):"""When current provider is custom:*, a static-catalog match must NOToverride it — otherwise a model served by the user's own endpoint gets@@ -165,8 +123,6 @@ class TestDetectProviderForModel:assert detect_provider_for_model("gpt-5.4", "custom:foo") is None--class TestPartitionNousModelsByTier:"""Tests for partition_nous_models_by_tier — free vs paid tier model split."""@@ -250,8 +206,6 @@ class TestUnionWithPortalFreeRecommendations:assert p["anthropic/claude-opus-4.6"] == self._PAID--def test_fetch_failure_returns_inputs(self):"""Network failures don't blow up the picker."""curated = ["a"]@@ -381,7 +335,6 @@ class TestCheckNousFreeTierCache:mock_account.assert_called_with(force_fresh=True)-class TestNousRecommendedModels:"""Tests for fetch_nous_recommended_models + get_nous_recommended_aux_model."""@@ -427,11 +380,6 @@ class TestNousRecommendedModels:assert mock_urlopen.call_count == 1 # second call served from cache-----def test_paid_tier_prefers_paid_recommendation(self):"""Paid-tier users should get the paid model when it's populated."""from hermes_cli.models import get_nous_recommended_aux_model@@ -448,8 +396,6 @@ class TestNousRecommendedModels:assert vision == "openai/gpt-5.4"--def test_tier_detection_error_defaults_to_paid(self):"""If tier detection raises, assume paid so we don't downgrade silently."""from hermes_cli.models import get_nous_recommended_aux_model@@ -487,14 +433,6 @@ class TestCodexSoftAcceptPlausibilityGate:assert r["recognized"] is True-class TestClaudeSonnet5InCuratedLists:- """Regression: Claude Sonnet 5 must appear in curated model lists (#55846)."""-- def test_anthropic_native_list_includes_sonnet_5(self):- from hermes_cli.models import _PROVIDER_MODELS- assert "claude-sonnet-5" in _PROVIDER_MODELS["anthropic"]--class TestFormatPricePerMtok:"""_format_price_per_mtok: sub-cent prices must not collapse to 'free'/'$0.00'."""@@ -530,12 +468,6 @@ class TestFormatPricePerMtok:assert _format_price_per_mtok("0.00000001") == "$0.01"-- def test_nous_list_includes_sonnet_5(self):- from hermes_cli.models import _PROVIDER_MODELS- assert "anthropic/claude-sonnet-5" in _PROVIDER_MODELS["nous"]--class _FakeOllamaTagsHandler(BaseHTTPRequestHandler):"""Serve Ollama-native /api/tags while rejecting OpenAI /v1/models."""@@ -576,7 +508,8 @@ def _start_fake_ollama_server(models=None):)_FakeOllamaTagsHandler.paths_seen = []server = HTTPServer(("127.0.0.1", 0), _FakeOllamaTagsHandler)- thread = Thread(target=server.serve_forever, daemon=True)+ # Short poll interval: server.shutdown() otherwise blocks ~0.5s per test.+ thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)thread.start()return server, server.server_address[1]@@ -630,10 +563,6 @@ class TestLocalOllamaModelDiscovery:finally:server.shutdown()- def test_ollama_has_no_static_default_model(self):- from hermes_cli.models import get_default_model_for_provider-- assert get_default_model_for_provider("ollama") == ""def test_fetch_ollama_models_accepts_base_url_without_scheme(self):"""OLLAMA_HOST commonly omits http://; discovery should normalize it."""@@ -677,11 +606,6 @@ class TestLocalOllamaModelDiscovery:assert probe_ollama_local_models("http://127.0.0.1:bad-port/v1") is None- def test_fetch_ollama_models_preserves_probe_failure(self):- from hermes_cli.models_local import fetch_ollama_local_models-- with patch("hermes_cli.models_local.probe_ollama_local_models", return_value=None):- assert fetch_ollama_local_models("http://127.0.0.1:11434") is Nonedef test_ollama_port_detection_requires_working_api_tags(self):from hermes_cli.models_local import should_use_ollama_native_catalog@@ -827,8 +751,6 @@ class TestLocalOllamaModelDiscovery:def test_clear_provider_models_cache_clears_ollama_native_tags_cache(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatecache = getattr(models, "_OLLAMA_LOCAL_MODELS_CACHE")cache["http://127.0.0.1:11434"] = ("old-model",)@@ -837,8 +759,6 @@ class TestLocalOllamaModelDiscovery:def test_clear_provider_models_cache_custom_clears_native_tags_cache(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatecache = getattr(models, "_OLLAMA_LOCAL_MODELS_CACHE")cache["http://127.0.0.1:11434"] = ("old-model",)@@ -847,8 +767,6 @@ class TestLocalOllamaModelDiscovery:def test_clear_provider_models_cache_does_not_remove_custom_disk_cache(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatedisk_cache = {"custom": {"models": ["custom-model"]},@@ -915,26 +833,6 @@ class TestLocalOllamaModelDiscovery:assert "/api/tags" in _FakeOllamaTagsHandler.paths_seenassert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen- def test_picker_user_provider_verifies_ambiguous_ollama_port(self):- """A custom-named providers: entry on :11434 should use /api/tags after verification."""- from hermes_cli.model_switch import list_authenticated_providers-- with patch("hermes_cli.config.load_config", return_value={"providers": {}}), patch(- "hermes_cli.models_local.should_use_ollama_native_catalog",- return_value=True,- ), patch(- "hermes_cli.models_local.fetch_ollama_local_models",- return_value=["qwen3:1.7b"],- ), patch("hermes_cli.models.fetch_api_models", return_value=[]) as fetch_api:- rows = list_authenticated_providers(- user_providers={"local-llm": {"base_url": "http://127.0.0.1:11434/v1"}},- custom_providers=[],- max_models=10,- )-- row = next(row for row in rows if row["slug"] == "local-llm")- assert row["models"] == ["qwen3:1.7b"]- fetch_api.assert_not_called()def test_picker_bare_custom_model_config_discovers_ollama_api_tags(self):"""The documented model.provider=custom shape should use native tags."""@@ -1371,8 +1269,6 @@ class TestLocalOllamaModelDiscovery:def test_ollama_failed_probe_is_cached_briefly(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatemodels._OLLAMA_LOCAL_MODELS_CACHE.clear()models._OLLAMA_LOCAL_PROBE_FAILURE_CACHE.clear()@@ -1386,8 +1282,6 @@ class TestLocalOllamaModelDiscovery:def test_empty_ollama_catalog_does_not_resurrect_stale_disk_models(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatebase_url = "http://127.0.0.1:11434"probe_key = models._ollama_probe_cache_key(base_url, None)@@ -1408,8 +1302,6 @@ class TestLocalOllamaModelDiscovery:def test_failed_ollama_catalog_preserves_stale_disk_models(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatebase_url = "http://127.0.0.1:11434"probe_key = models._ollama_probe_cache_key(base_url, None)@@ -1430,8 +1322,6 @@ class TestLocalOllamaModelDiscovery:def test_ollama_native_request_uses_redirect_safe_catalog_helper(self):import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validateresponse = MagicMock()response.read.return_value = b'{"models": [{"name": "qwen3:1.7b"}]}'@@ -1445,9 +1335,6 @@ class TestLocalOllamaModelDiscovery:request.assert_called_once()def test_validation_with_nonmatching_ollama_root_does_not_forward_config_headers(self):- import hermes_cli.models as models- from hermes_cli import models_local- from hermes_cli import models_validatewith patch("hermes_cli.config.load_config",@@ -1476,7 +1363,6 @@ class TestLocalOllamaModelDiscovery:assert probe.call_args.kwargs["headers"] == {"X-Endpoint-Token": "explicit"}-def test_switch_model_direct_ollama_alias_preserves_matching_origin_api_key(self):import hermes_cli.model_switch as model_switchdiff --git a/tests/hermes_cli/test_models_dev_preferred_merge.py b/tests/hermes_cli/test_models_dev_preferred_merge.pyindex 0c1963d6828..13aeb117bee 100644--- a/tests/hermes_cli/test_models_dev_preferred_merge.py+++ b/tests/hermes_cli/test_models_dev_preferred_merge.py@@ -21,7 +21,6 @@ from unittest.mock import patchfrom hermes_cli.models import (- _MODELS_DEV_PREFERRED,_PROVIDER_MODELS,_merge_with_models_dev,provider_model_ids,@@ -39,7 +38,8 @@ class TestMergeHelper:patch("hermes_cli.models._profile_live_catalog", return_value=None):out = provider_model_ids("deepseek")- assert out == ["deepseek-flash", "deepseek-v4-pro"]+ assert out == list(_PROVIDER_MODELS["deepseek"])+ assert "deepseek-v4-flash" not in out and "deepseek-v4-flash-vision-exp" not in outdef test_merge_empty_mdev_returns_curated(self):"""When models.dev returns nothing, curated list is preserved verbatim."""@@ -47,7 +47,6 @@ class TestMergeHelper:out = _merge_with_models_dev("opencode-go", ["mimo-v2-pro", "kimi-k2.6"])assert out == ["mimo-v2-pro", "kimi-k2.6"]-def test_merge_case_insensitive_dedup(self):"""Dedup is case-insensitive but preserves the first occurrence's casing."""mdev = ["MiniMax-M2.7"]@@ -60,10 +59,6 @@ class TestMergeHelper:class TestProviderModelIdsPreferred:----def test_k3_live_discovery_is_scoped_to_kimi_coding_endpoint(self):"""Coding keys discover K3; legacy Moonshot keys must not advertise it."""@@ -145,24 +140,3 @@ class TestProviderModelIdsPreferred:_model_flow_kimi({}, current_model="")assert captured["models"] == _PROVIDER_MODELS["kimi-coding"]- assert captured["models"][0] == "kimi-k3"---class TestOpenRouterAndNousUnchanged:- """Per Teknium: openrouter and nous are NEVER merged with models.dev."""--- def test_openrouter_does_not_call_merge(self):- """openrouter takes its own live path — merge helper must NOT run."""- with patch(- "hermes_cli.models._merge_with_models_dev",- side_effect=AssertionError("merge should not be called for openrouter"),- ):- # Even if model_ids() fails for some other reason, we just care- # that the merge path isn't invoked.- try:- provider_model_ids("openrouter")- except AssertionError:- raise- except Exception:- pass # model_ids() may fail in the hermetic test env — that's fine.diff --git a/tests/hermes_cli/test_modify_other_keys_aliases.py b/tests/hermes_cli/test_modify_other_keys_aliases.pyindex c54db220dbb..57a23def56c 100644--- a/tests/hermes_cli/test_modify_other_keys_aliases.py+++ b/tests/hermes_cli/test_modify_other_keys_aliases.py@@ -84,80 +84,10 @@ def test_modify_other_keys_ctrl_letter_parses_as_raw_byte(letter):)[email protected]("letter", CTRL_LETTERS)-def test_modify_other_keys_ctrl_letter_single_keypress(letter):- """Each Ctrl+letter sequence must produce exactly one keypress —- a partial match would emit Escape plus literal text."""- for seq in (f"\x1b[27;5;{ord(letter)}~", f"\x1b[{ord(letter)};5u"):- result = _parse(seq)- assert len(result) == 1, (- f"{seq!r} should produce exactly 1 keypress, got {len(result)}: {result!r}"- )--# ---------------------------------------------------------------------------# Critical individual shortcuts# ----------------------------------------------------------------------------def test_ctrl_c_under_modify_other_keys():- """Ctrl+C must produce Keys.ControlC, not literal text (#56684)."""- assert _parse("\x1b[27;5;99~") == [Keys.ControlC]- assert _parse("\x1b[99;5u") == [Keys.ControlC]---def test_ctrl_a_under_modify_other_keys():- """Ctrl+A (line start) must still fire."""- assert _parse("\x1b[27;5;97~") == [Keys.ControlA]- assert _parse("\x1b[97;5u") == [Keys.ControlA]---def test_ctrl_e_under_modify_other_keys():- """Ctrl+E (line end) must still fire."""- assert _parse("\x1b[27;5;101~") == [Keys.ControlE]- assert _parse("\x1b[101;5u") == [Keys.ControlE]---def test_ctrl_u_under_modify_other_keys():- """Ctrl+U (kill line) must still fire."""- assert _parse("\x1b[27;5;117~") == [Keys.ControlU]- assert _parse("\x1b[117;5u") == [Keys.ControlU]---def test_ctrl_k_under_modify_other_keys():- """Ctrl+K (kill to end) must still fire."""- assert _parse("\x1b[27;5;107~") == [Keys.ControlK]- assert _parse("\x1b[107;5u") == [Keys.ControlK]---def test_ctrl_r_under_modify_other_keys():- """Ctrl+R (reverse search) must still fire."""- assert _parse("\x1b[27;5;114~") == [Keys.ControlR]- assert _parse("\x1b[114;5u") == [Keys.ControlR]---def test_ctrl_d_under_modify_other_keys():- """Ctrl+D (EOF / delete) must still fire."""- assert _parse("\x1b[27;5;100~") == [Keys.ControlD]- assert _parse("\x1b[100;5u") == [Keys.ControlD]---def test_ctrl_w_under_modify_other_keys():- """Ctrl+W (delete word) must still fire."""- assert _parse("\x1b[27;5;119~") == [Keys.ControlW]- assert _parse("\x1b[119;5u") == [Keys.ControlW]---def test_ctrl_z_under_modify_other_keys():- """Ctrl+Z (suspend) must still fire."""- assert _parse("\x1b[27;5;122~") == [Keys.ControlZ]- assert _parse("\x1b[122;5u") == [Keys.ControlZ]---def test_ctrl_l_under_modify_other_keys():- """Ctrl+L (clear screen) must still fire."""- assert _parse("\x1b[27;5;108~") == [Keys.ControlL]- assert _parse("\x1b[108;5u") == [Keys.ControlL]-# ---------------------------------------------------------------------------# Ctrl+digit: 0-9@@ -324,16 +254,6 @@ def test_does_not_clobber_shift_enter_alias():assert ANSI_SEQUENCES["\x1b[13;2u"] == (Keys.Escape, Keys.ControlM)-def test_does_not_clobber_ctrl_enter_alias():- """install_modify_other_keys_aliases must not overwrite mappings- installed by install_ctrl_enter_alias (which maps Ctrl+Enter)."""- from hermes_cli.pt_input_extras import install_ctrl_enter_alias- install_ctrl_enter_alias()- # Ctrl+Enter (modifier=5, codepoint=13) is mapped to (Escape, ControlM)- assert ANSI_SEQUENCES["\x1b[27;5;13~"] == (Keys.Escape, Keys.ControlM)- assert ANSI_SEQUENCES["\x1b[13;5u"] == (Keys.Escape, Keys.ControlM)--def test_ctrl_enter_still_works_under_modify_other_keys():"""Ctrl+Enter must produce the Alt+Enter newline tuple, not plain Ctrl+M.This is the install_ctrl_enter_alias behavior — our new function must@@ -349,16 +269,6 @@ def test_ctrl_enter_still_works_under_modify_other_keys():assert ctrl_enter_csiu == alt_enter-def test_plain_enter_remains_distinct():- """Plain Enter must keep producing a single keypress (submit), not- the two-key Alt+Enter tuple."""- enter = _parse("\r")- alt_enter = _parse("\x1b\r")- assert enter != alt_enter- assert len(enter) == 1- assert len(alt_enter) == 2--# ---------------------------------------------------------------------------# Kitty keyboard protocol: the Esc KEY (disambiguate mode, #56684)# ---------------------------------------------------------------------------@@ -477,17 +387,6 @@ def test_keypad_digit_keypress_data_is_digit():)-def test_plain_space_keypress_data_unchanged():- """A plain space must keep data == ' ' — normalization must not break- the ordinary typing path."""- from hermes_cli.pt_input_extras import install_keypress_data_normalization-- install_keypress_data_normalization()- presses = _parse_presses(" ")- assert [kp.key for kp in presses] == [" "]- assert [kp.data for kp in presses] == [" "]--def test_buffer_level_shift_space_no_raw_csi():"""End-to-end: feeding Shift+Space through a real Application must puta space in the buffer, not raw CSI bytes (#88071).@@ -592,16 +491,6 @@ def test_buffer_level_shift_letter_no_raw_csi():)-def test_plain_letter_keypress_data_unchanged():- """The normalization predicate only fires on ESC-prefixed payloads —- ordinary ASCII typing must pass through untouched."""- from hermes_cli.pt_input_extras import install_keypress_data_normalization-- install_keypress_data_normalization()- presses = _parse_presses("M")- assert [(kp.key, kp.data) for kp in presses] == [("M", "M")]--# ---------------------------------------------------------------------------# Multi-modifier combos (Ctrl+Shift / Ctrl+Alt / Shift+Alt / Ctrl+Alt+Shift)# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_multiplex_host_topology_reporting.py b/tests/hermes_cli/test_multiplex_host_topology_reporting.pyindex 4b7db47e103..3fcbae28b95 100644--- a/tests/hermes_cli/test_multiplex_host_topology_reporting.py+++ b/tests/hermes_cli/test_multiplex_host_topology_reporting.py@@ -45,7 +45,7 @@ def test_cron_status_names_the_host_gateway_for_a_served_profile(served_host, cacron.cron_status()out = capsys.readouterr().out- assert f"the host gateway (PID {os.getpid()}) serving profiles default, served" in out+ assert f"PID {os.getpid()}" in out and "served" in outassert "not running" not in out.lower()# Never route the user to a SECOND host process: per-profile install is legacy-only remediation.assert "hermes gateway install" not in out@@ -84,7 +84,7 @@ def test_doctor_reports_the_single_host_gateway_not_per_profile_slots(served_hosout = capsys.readouterr().outassert "Per-profile gateways:" not in out- assert f"Host gateway: the host gateway (PID {os.getpid()}) serving profiles default, served" in out+ assert f"PID {os.getpid()}" in out and "served" in outassert "LEGACY per-profile gateway slots still supervised: legacy" in outassert any("migrate --multiplex" in i for i in issues)diff --git a/tests/hermes_cli/test_nebius_token_factory_provider.py b/tests/hermes_cli/test_nebius_token_factory_provider.pyindex 5fc12a0b68b..ab4bbf8aca5 100644--- a/tests/hermes_cli/test_nebius_token_factory_provider.py+++ b/tests/hermes_cli/test_nebius_token_factory_provider.py@@ -3,37 +3,16 @@from __future__ import annotationsfrom hermes_cli.auth import (- PROVIDER_REGISTRY,resolve_api_key_provider_credentials,resolve_provider,)from hermes_cli.model_normalize import normalize_model_for_providerfrom hermes_cli.models import (- CANONICAL_PROVIDERS,- _PROVIDER_ALIASES,- _PROVIDER_LABELS,normalize_provider,provider_model_ids,)-def test_nebius_provider_profile_loads():- from providers import get_provider_profile-- profile = get_provider_profile("nebius-token-factory")- assert profile is not None- assert profile.name == "nebius-token-factory"- assert profile.display_name == "Nebius Token Factory"- assert profile.base_url == "https://api.tokenfactory.nebius.com/v1"- assert profile.models_url == "https://api.tokenfactory.nebius.com/v1/models?verbose=true"- assert profile.env_vars[:2] == (- "NEBIUS_API_KEY",- "NEBIUS_TOKEN_FACTORY_API_KEY",- )- assert profile.default_aux_model == "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B"- assert "Qwen/Qwen3.5-397B-A17B-fast" in profile.fallback_models--def test_nebius_aliases_resolve(monkeypatch):monkeypatch.setenv("NEBIUS_API_KEY", "nebius-test-key")@@ -46,66 +25,18 @@ def test_nebius_aliases_resolve(monkeypatch):):assert resolve_provider(alias) == "nebius-token-factory"assert normalize_provider(alias) == "nebius-token-factory"- assert _PROVIDER_ALIASES[alias] == "nebius-token-factory"def test_nebius_provider_registry_and_credentials(monkeypatch):monkeypatch.setenv("NEBIUS_API_KEY", "nebius-secret")monkeypatch.setenv("NEBIUS_BASE_URL", "https://custom.nebius.example/v1")- pconfig = PROVIDER_REGISTRY["nebius-token-factory"]- assert pconfig.id == "nebius-token-factory"- assert pconfig.name == "Nebius Token Factory"- assert pconfig.auth_type == "api_key"- assert pconfig.inference_base_url == "https://api.tokenfactory.nebius.com/v1"- assert pconfig.api_key_env_vars == (- "NEBIUS_API_KEY",- "NEBIUS_TOKEN_FACTORY_API_KEY",- )- assert pconfig.base_url_env_var == "NEBIUS_BASE_URL"-creds = resolve_api_key_provider_credentials("nebius-token-factory")assert creds["provider"] == "nebius-token-factory"assert creds["api_key"] == "nebius-secret"assert creds["base_url"] == "https://custom.nebius.example/v1"-def test_nebius_canonical_provider_and_label():- slugs = [p.slug for p in CANONICAL_PROVIDERS]- assert "nebius-token-factory" in slugs- assert _PROVIDER_LABELS["nebius-token-factory"] == "Nebius Token Factory"---def test_nebius_provider_module_overlay():- from hermes_cli.providers import (- HERMES_OVERLAYS,- determine_api_mode,- get_label,- get_provider,- normalize_provider as normalize_provider_in_providers,- )-- overlay = HERMES_OVERLAYS["nebius-token-factory"]- assert overlay.transport == "openai_chat"- assert overlay.base_url_override == "https://api.tokenfactory.nebius.com/v1"- assert overlay.base_url_env_var == "NEBIUS_BASE_URL"-- provider = get_provider("nebius")- assert provider is not None- assert provider.id == "nebius-token-factory"- assert provider.api_key_env_vars == (- "NEBIUS_API_KEY",- "NEBIUS_TOKEN_FACTORY_API_KEY",- )- assert provider.base_url == "https://api.tokenfactory.nebius.com/v1"- assert normalize_provider_in_providers("token-factory") == "nebius-token-factory"- assert get_label("nebius-token-factory") == "Nebius Token Factory"- assert determine_api_mode(- "nebius-token-factory",- "https://api.tokenfactory.nebius.com/v1",- ) == "chat_completions"--def test_nebius_model_catalog_prefers_live_profile_fetch(monkeypatch):from providers import get_provider_profilediff --git a/tests/hermes_cli/test_non_ascii_credential.py b/tests/hermes_cli/test_non_ascii_credential.pyindex 45047ae3e5b..d0ca1feccd6 100644--- a/tests/hermes_cli/test_non_ascii_credential.py+++ b/tests/hermes_cli/test_non_ascii_credential.py@@ -74,19 +74,5 @@ class TestEnvLoaderSanitization:captured = capsys.readouterr()assert "GOOGLE_API_KEY" in captured.errassert "U+200B" in captured.err- assert "re-copy" in captured.err.lower()- def test_ascii_control_chars_not_stripped(self, monkeypatch, capsys):- """ASCII control bytes (e.g. ESC 0x1B from terminal paste) are NOT non-ASCII.-- This is intentional — they're valid ASCII for HTTP headers even if the- provider rejects them. Documents the scope of the sanitizer.- """- from hermes_cli.env_loader import _sanitize_loaded_credentials, _WARNED_KEYS-- _WARNED_KEYS.clear()- monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant\x1bapi-key")- _sanitize_loaded_credentials()- assert os.environ["ANTHROPIC_API_KEY"] == "sk-ant\x1bapi-key"- assert capsys.readouterr().err == ""diff --git a/tests/hermes_cli/test_noninteractive_config_guard.py b/tests/hermes_cli/test_noninteractive_config_guard.pyindex a6ea952ca51..dd4124ec2f9 100644--- a/tests/hermes_cli/test_noninteractive_config_guard.py+++ b/tests/hermes_cli/test_noninteractive_config_guard.py@@ -54,12 +54,8 @@ def test_noninteractive_guard_rejects_malformed_yaml(args, tmp_path, caplog, capmain_mod._guard_noninteractive_user_config(args)assert exc_info.value.code == 2- assert "Hermes stopped because your settings file" in capsys.readouterr().err- assert any(- record.levelno == logging.ERROR- and "Hermes stopped because your settings file" in record.getMessage()- for record in caplog.records- )+ assert capsys.readouterr().err.strip()+ assert any(record.levelno == logging.ERROR for record in caplog.records)assert config_path.read_text(encoding="utf-8") == brokenbackups = list((tmp_path / "backups" / "config").glob("config.yaml.corrupt.*"))assert len(backups) == 1@@ -112,7 +108,7 @@ def test_noninteractive_guard_rejects_non_mapping_yaml(tmp_path, capsys):main_mod._guard_noninteractive_user_config(_args())assert exc_info.value.code == 2- assert "top-level YAML value must be a mapping" in capsys.readouterr().err+ assert capsys.readouterr().err.strip()@pytest.mark.parametrize(@@ -195,11 +191,3 @@ def test_reused_args_can_retry_after_config_repair(tmp_path):assert args._noninteractive_config_validated is True-def test_ignore_user_config_is_applied_before_oneshot_startup(monkeypatch):- from hermes_cli import main as main_mod-- monkeypatch.delenv("HERMES_IGNORE_USER_CONFIG", raising=False)-- main_mod._apply_user_config_bypass(_args(ignore_user_config=True))-- assert os.environ["HERMES_IGNORE_USER_CONFIG"] == "1"diff --git a/tests/hermes_cli/test_noninteractive_git.py b/tests/hermes_cli/test_noninteractive_git.pyindex 9280990c7c9..6f0eedc248d 100644--- a/tests/hermes_cli/test_noninteractive_git.py+++ b/tests/hermes_cli/test_noninteractive_git.py@@ -48,7 +48,6 @@ class TestNoninteractiveGitEnv:assert env["HERMES_TEST_SENTINEL"] == "xyz"assert env["GIT_TERMINAL_PROMPT"] == "0"# Never mutates the live process environment.- assert os.environ.get("GIT_TERMINAL_PROMPT") != "0" or Trueassert "GCM_INTERACTIVE" not in os.environ or os.environ["GCM_INTERACTIVE"] == env["GCM_INTERACTIVE"]diff --git a/tests/hermes_cli/test_nous_auth_status_cache.py b/tests/hermes_cli/test_nous_auth_status_cache.pyindex 5f249ef73e6..dc2456a3189 100644--- a/tests/hermes_cli/test_nous_auth_status_cache.py+++ b/tests/hermes_cli/test_nous_auth_status_cache.py@@ -11,7 +11,6 @@ also call invalidate_nous_auth_status_cache().from __future__ import annotationsimport json-import osfrom unittest.mock import patch@@ -58,32 +57,3 @@ def test_get_nous_auth_status_caches_consecutive_calls(tmp_path, monkeypatch):auth_mod.invalidate_nous_auth_status_cache()-def test_get_nous_auth_status_caches_failure_path(tmp_path, monkeypatch):- """Logged-out snapshots are cached too — that's where the cost was.-- Teknium's case: ~31 cache misses per `hermes tools` "All Platforms"- menu paint, all returning logged_in=False after a failed refresh POST.- The whole point of the cache is to memoise that failure path too.- """- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- _seed_auth_file(tmp_path)-- from hermes_cli import auth as auth_mod-- auth_mod.invalidate_nous_auth_status_cache()-- call_count = {"n": 0}-- def fake_compute():- call_count["n"] += 1- return {"logged_in": False, "source": "auth_store", "error": "refresh failed"}-- with patch.object(auth_mod, "_compute_nous_auth_status", side_effect=fake_compute):- for _ in range(10):- auth_mod.get_nous_auth_status()-- assert call_count["n"] == 1, (- f"Logged-out snapshots must cache; got {call_count['n']} computes for 10 calls."- )-- auth_mod.invalidate_nous_auth_status_cache()diff --git a/tests/hermes_cli/test_nous_billing_request.py b/tests/hermes_cli/test_nous_billing_request.pyindex 2565c99da61..c19a7ed174c 100644--- a/tests/hermes_cli/test_nous_billing_request.py+++ b/tests/hermes_cli/test_nous_billing_request.py@@ -10,8 +10,6 @@ from __future__ import annotationsimport ioimport json-import socket-from contextlib import contextmanagerimport pytest@@ -73,53 +71,6 @@ def _sequence(monkeypatch, *outcomes, resolver=None):return seen-@contextmanager-def _stub(monkeypatch, body: bytes, status: int = 200):- # Bypass auth/token resolution entirely — we only exercise response parsing.- monkeypatch.setattr(nb, "_resolve_token_and_base", lambda **kw: ("tok", "https://portal.example"))- monkeypatch.setattr(nb, "_token_cache", {}, raising=False)- monkeypatch.setattr(nb.urllib.request, "urlopen", lambda req, timeout=None: _FakeResp(body, status))- yield---------# ----------------------------------------------------------------------------# Subscription change (V3): the request the client actually puts on the wire.-# ------------------------------------------------------------------------------@contextmanager-def _capture(monkeypatch, body: bytes = b"{}", status: int = 200):- """Stub urlopen, recording the urllib.request.Request the client built."""- seen: dict[str, object] = {}- monkeypatch.setattr(- nb, "_resolve_token_and_base", lambda **kw: ("tok", "https://portal.example")- )-- def _fake_urlopen(req, timeout=None):- seen["method"] = req.get_method()- seen["url"] = req.full_url- seen["data"] = json.loads(req.data.decode()) if req.data else None- seen["headers"] = {k.lower(): v for k, v in req.header_items()}- return _FakeResp(body, status)-- monkeypatch.setattr(nb.urllib.request, "urlopen", _fake_urlopen)- yield seen----------# ---------------------------------------------------------------------------# Wire-layer HTTP error mapping through _request.# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_nous_inference_url_validation.py b/tests/hermes_cli/test_nous_inference_url_validation.pyindex 7a20149ab8f..cf2da679a07 100644--- a/tests/hermes_cli/test_nous_inference_url_validation.py+++ b/tests/hermes_cli/test_nous_inference_url_validation.py@@ -25,7 +25,6 @@ import loggingfrom hermes_cli.auth import (DEFAULT_NOUS_INFERENCE_URL,- _ALLOWED_NOUS_INFERENCE_HOSTS,_validate_nous_inference_url_from_network,)@@ -85,48 +84,8 @@ class TestCallSiteWiring:Path(m.__file__).read_text(encoding="utf-8") for m in (_auth_mod, _nous_mod))- def test_no_unvalidated_inference_base_url_assignments_remain(self):- """No remaining ``_optional_base_url(...inference_base_url...)`` reads- from Portal payloads. If you see a failure here, you've either- added a new NETWORK site that needs validation, or downgraded an- existing one back to the unsafe helper."""- source = self._read_auth_source()- for needle in (- '_optional_base_url(refreshed.get("inference_base_url"))',- '_optional_base_url(mint_payload.get("inference_base_url"))',- ):- assert needle not in source, (- f"Found unvalidated network read: {needle!r}. "- f"Use _validate_nous_inference_url_from_network() instead."- )- def test_validator_wired_at_all_known_call_sites(self):- """All 2 known auth.py NETWORK refresh sites route the Portal-returned- inference URL through ``_healed_nous_inference_url`` (which applies the- validator and heals to the default). If this count drops, someone removed- protection; if it grows, audit the new site to be sure validation is- appropriate."""- source = self._read_auth_source()- assert (- source.count('_validate_nous_inference_url_from_network(refreshed.get("inference_base_url"))')- == 1- ), "the validator must be applied exactly once, inside _healed_nous_inference_url"- refresh_count = source.count("_healed_nous_inference_url(refreshed)")- mint_count = source.count(- '_validate_nous_inference_url_from_network(mint_payload.get("inference_base_url"))'- )- assert refresh_count == 2, f"expected 2 refresh sites, found {refresh_count}"- assert mint_count == 0, f"expected 0 mint sites, found {mint_count}"-- def test_proxy_adapter_also_validates(self):- """The Nous proxy adapter applies the validator as defense-in-depth- even though auth.py already validates at the source, so a future- bypass at the source layer still gets caught at the forward- boundary."""- from pathlib import Path- import hermes_cli.proxy.adapters.nous_portal as _nous_adapter- source = Path(_nous_adapter.__file__).read_text(encoding="utf-8")- assert "_validate_nous_inference_url_from_network" in source+class TestEnvOverrideNotGated:@@ -140,21 +99,6 @@ class TestEnvOverrideNotGated:inadvertently broken by this fix."""- def test_env_override_path_does_not_call_validator(self):- """In resolve_nous_runtime_credentials, the env override is- read via os.getenv directly, not via the validator. Grep the- source to confirm: the env line should NOT mention the- validator."""- import hermes_cli.auth as _auth_mod- from pathlib import Path- source = Path(_auth_mod.__file__).read_text(encoding="utf-8")- # Find the env-override read line.- for line in source.splitlines():- if "NOUS_INFERENCE_BASE_URL" in line and "os.getenv" in line:- assert "_validate_nous_inference_url_from_network" not in line, (- "env override path must not gate through the network "- "validator — it would break documented dev/staging use."- )class TestHealsPoisonedStoredValue:@@ -322,17 +266,3 @@ class TestProxyAdapterEnvOverride:NOUS_INFERENCE_BASE_URL staging override."""- def test_proxy_adapter_consults_env_override(self):- """Grep contract: the proxy adapter's forward-boundary base_url- resolution consults the env override before the network validator,- so a staging override survives the defense-in-depth re-validation."""- from pathlib import Path- import hermes_cli.proxy.adapters.nous_portal as _nous_adapter-- source = Path(_nous_adapter.__file__).read_text(encoding="utf-8")- assert "_nous_inference_env_override()" in source, (- "proxy adapter must layer the env override on top of the network "- "validator, else a staging override is rejected at the forward boundary"- )- # The validator must still be present (defense-in-depth preserved).- assert "_validate_nous_inference_url_from_network" in sourcediff --git a/tests/hermes_cli/test_nous_policy_filter.py b/tests/hermes_cli/test_nous_policy_filter.pyindex 9dd1f8a2d03..126b94e3cfb 100644--- a/tests/hermes_cli/test_nous_policy_filter.py+++ b/tests/hermes_cli/test_nous_policy_filter.py@@ -11,7 +11,6 @@ import jsonimport pytest-import hermes_cli.models as models_modfrom hermes_cli import models_pricingimport hermes_cli.nous_account as account_modfrom hermes_cli.models_pricing import _NOUS_POLICY_APPEND_MAX, nous_policy_allowed_ids, restrict_to_nous_policy@@ -157,7 +156,7 @@ class TestNousPolicyNotice:def test_shows_a_line_for_a_governed_org(self, monkeypatch):self._patch(monkeypatch, True)- assert "restricts which models" in account_mod.nous_policy_notice(removed=True)+ assert account_mod.nous_policy_notice(removed=True).strip()@pytest.mark.parametrize("present", [False, None])def test_silent_otherwise(self, monkeypatch, present):@@ -171,12 +170,6 @@ class TestNousPolicyNotice:self._patch(monkeypatch, True)assert account_mod.nous_policy_notice(removed=False) == ""- def test_names_no_models(self, monkeypatch):- """The blocked set is most of the catalog under an allowlist."""- self._patch(monkeypatch, True)- notice = account_mod.nous_policy_notice(removed=True)- assert "/" not in notice, f"looks like it names a model: {notice}"- assert len(notice.splitlines()) == 1class TestAllowlistOutsideTheCuratedList:@@ -206,8 +199,6 @@ class TestAllowlistOutsideTheCuratedList:class TestRescueIsOptIn:"""The rescue is meaningful only for the list a user picks from."""- def test_rescue_only_when_asked(self):- assert restrict_to_nous_policy([], {"a/one"}, rescue_empty=True) == ["a/one"]def test_an_already_empty_unavailable_list_is_never_filled(self):"""A paid tier has no gated models, so this list is legitimatelydiff --git a/tests/hermes_cli/test_nous_policy_surfaces.py b/tests/hermes_cli/test_nous_policy_surfaces.pyindex d15f8e03334..c276bf50486 100644--- a/tests/hermes_cli/test_nous_policy_surfaces.py+++ b/tests/hermes_cli/test_nous_policy_surfaces.py@@ -191,10 +191,6 @@ class TestAuxiliaryFastModel:picked = aux._fast_model_from_catalog("nous")return picked, seen- def test_reads_the_catalog_with_nous_oauth_credentials(self, monkeypatch, no_policy):- """The api-key resolver raises for OAuth providers."""- _, seen = self._pick(monkeypatch, catalog=["vendor/haiku-fast"])- assert seen["api_key"] == "sk-nous"def test_hidden_model_is_not_selected(self, monkeypatch, policy):import agent.auxiliary_client as aux@@ -214,16 +210,6 @@ class TestNousPrefetch:"""The nous disk-cache entry is write-only, so prefetching it is a roundtrip for nothing."""- def test_nous_is_not_collected_for_prefetch(self, monkeypatch):- import hermes_cli.auth as auth_mod- import hermes_cli.model_switch_providers as ms-- monkeypatch.setattr(- auth_mod, "_load_auth_store",- lambda *a, **k: {"providers": {"nous": {"access_token": "tok"}}},- )- slugs = ms._collect_authed_provider_slugs({}, {"nous": list(CURATED)}, [])- assert "nous" not in slugsclass TestPolicyNoticeIsShown:@@ -233,16 +219,8 @@ class TestPolicyNoticeIsShown:monkeypatch.setattr(account_mod, "nous_policy_present", lambda: True)TestLoginNous()._run(monkeypatch, tmp_path)- assert "restricts which models" in capsys.readouterr().out+ assert account_mod.nous_policy_notice(removed=True) in capsys.readouterr().out- def test_login_silent_for_an_ungoverned_org(- self, monkeypatch, tmp_path, no_policy, capsys- ):- import hermes_cli.nous_account as account_mod-- monkeypatch.setattr(account_mod, "nous_policy_present", lambda: False)- TestLoginNous()._run(monkeypatch, tmp_path)- assert "restricts which models" not in capsys.readouterr().outclass TestAuxFallbackRespectsPolicy:@@ -300,24 +278,3 @@ class TestAuxFallbackRespectsPolicy:)-def test_titling_seeds_the_shared_catalog_entry_like_the_pickers(monkeypatch):- """The aux catalog read shares the pickers' cache entry, so seeding it- without the Nous-only arguments costs the picker its sale chrome and leaves- the policy catalog with no expiry."""- import agent.auxiliary_client as aux-- monkeypatch.setattr(- models_pricing, "_resolve_nous_pricing_credentials",- lambda: ("tok", "https://inference.example.com"),- )- seen: dict = {}-- def _fake_fetch(**kwargs):- seen.update(kwargs)- return {"vendor/haiku": {}}-- monkeypatch.setattr(models_pricing, "fetch_models_with_pricing", _fake_fetch)- aux._fast_model_from_catalog("nous")-- assert seen.get("include_sale_original") is True- assert seen.get("cache_ttl_seconds") == models_pricing._NOUS_CATALOG_TTL_SECONDSdiff --git a/tests/hermes_cli/test_nous_portal_staging_allowlist.py b/tests/hermes_cli/test_nous_portal_staging_allowlist.pyindex 5462ed6176b..0553d69ddb0 100644--- a/tests/hermes_cli/test_nous_portal_staging_allowlist.py+++ b/tests/hermes_cli/test_nous_portal_staging_allowlist.py@@ -33,31 +33,9 @@ import loggingfrom hermes_cli.auth import (DEFAULT_NOUS_PORTAL_URL,- _NOUS_PORTAL_ALLOWED_HOSTS,- _nous_portal_env_override,)-class TestPortalEnvOverrideHelper:- def test_none_when_unset(self, monkeypatch):- monkeypatch.delenv("HERMES_PORTAL_BASE_URL", raising=False)- monkeypatch.delenv("NOUS_PORTAL_BASE_URL", raising=False)- assert _nous_portal_env_override() is None--- def test_env_override_not_gated_by_allowlist(self, monkeypatch):- """The whole point: an env-set staging host is NOT in- _NOUS_PORTAL_ALLOWED_HOSTS, and the helper must return it anyway —- gating happens only for network-provenance values."""- monkeypatch.setenv(- "HERMES_PORTAL_BASE_URL", "https://portal.staging-nousresearch.com"- )- assert "portal.staging-nousresearch.com" not in _NOUS_PORTAL_ALLOWED_HOSTS- assert (- _nous_portal_env_override() == "https://portal.staging-nousresearch.com"- )--class TestResolveAccessTokenEnvOverrideWins:"""End-to-end: resolve_nous_access_token must use the env override forthe refresh call, bypassing the allowlist, even when state also has adiff --git a/tests/hermes_cli/test_nous_session_validity.py b/tests/hermes_cli/test_nous_session_validity.pyindex ff09cb77d88..27b77b2be2b 100644--- a/tests/hermes_cli/test_nous_session_validity.py+++ b/tests/hermes_cli/test_nous_session_validity.py@@ -6,12 +6,6 @@ import timeimport hermes_cli.auth as authimport hermes_cli.auth_nous as auth_nous-from hermes_cli.auth import (- NOUS_SESSION_TERMINAL,- NOUS_SESSION_UNKNOWN,- NOUS_SESSION_VALID,- get_nous_session_validity,-)def _invoke_jwt(*, seconds: int = 3600) -> str:diff --git a/tests/hermes_cli/test_nous_subscription.py b/tests/hermes_cli/test_nous_subscription.pyindex 2f82c8ba28c..732655bc44e 100644--- a/tests/hermes_cli/test_nous_subscription.py+++ b/tests/hermes_cli/test_nous_subscription.py@@ -1,7 +1,6 @@"""Tests for Nous subscription feature detection."""import shutil-import sysfrom hermes_cli.nous_account import NousPortalAccountInfo, NousToolAccessInfofrom hermes_cli import nous_subscription as ns@@ -222,8 +221,6 @@ def test_prompt_enable_tool_gateway_pool_offers_covered_tools_only(monkeypatch):blob = " ".join(captured["items"]).lower()assert "firecrawl" in blob # web offeredassert "video" not in blob # video NOT offered to a pool user- # Pool-aware framing, not "subscription".- assert "free" in captured["title"].lower() and "pool" in captured["title"].lower()def test_get_gateway_eligible_tools_treats_explicit_backend_as_configured(monkeypatch):@@ -272,17 +269,6 @@ def test_get_gateway_eligible_tools_treats_browser_use_selection_as_explicit(monassert "browser" not in already_managed-def test_get_gateway_eligible_tools_not_entitled_returns_four_empty_lists(monkeypatch):- """A logged-in Nous account with no paid access and no free tool pool- must fail closed with a 4-tuple, not a 3-tuple — regression for a crash- where the early 'not entitled' return still had the pre-refactor arity- while the happy path and every caller had moved to 4 values."""- monkeypatch.setattr(ns, "get_nous_portal_account_info", lambda **kw: _account(logged_in=True, paid=False))-- config = {"model": {"provider": "nous"}}- result = ns.get_gateway_eligible_tools(config)-- assert result == ([], [], [], [])def test_prompt_enable_tool_gateway_not_entitled_does_not_crash(monkeypatch):@@ -433,28 +419,6 @@ def test_apply_nous_managed_defaults_writes_video_gen_config(monkeypatch):-def _stt_features_stub(*, account_info):- return ns.NousSubscriptionFeatures(- subscribed=True,- nous_auth_present=True,- provider_is_nous=True,- account_info=account_info,- features={- key: ns.NousFeatureState(- key=key, label=key, included_by_default=True,- available=False, active=False, managed_by_nous=False,- direct_override=False, toolset_enabled=False,- explicit_configured=False,- )- for key in ("web", "image_gen", "video_gen", "tts", "stt", "browser", "modal")- },- )------def _block_legacy_agent_browser_checks(monkeypatch):"""Make the legacy checks (PATH lookup + local node_modules/.bin) find nothing."""real_which = shutil.which@@ -517,65 +481,7 @@ def test_has_agent_browser_false_when_nothing_resolvable(monkeypatch):assert ns._has_agent_browser() is False-def test_has_agent_browser_import_failure_falls_back_to_path_check(monkeypatch):- """If tools.browser_tool_install cannot be imported, the old PATH + node_modules- check must still answer (prior behaviour), not crash."""- monkeypatch.setitem(sys.modules, "tools.browser_tool_install", None)- real_which = shutil.which- monkeypatch.setattr(- shutil,- "which",- lambda cmd, *args, **kwargs: (- "/fake/bin/agent-browser"- if cmd == "agent-browser"- else real_which(cmd, *args, **kwargs)- ),- )- monkeypatch.setattr(- "hermes_constants.agent_browser_runnable",- lambda path: path == "/fake/bin/agent-browser",- )- assert ns._has_agent_browser() is True-def test_has_agent_browser_import_failure_falls_back_to_hermes_managed_node_path(- monkeypatch, tmp_path-):- """If tools.browser_tool_install cannot be imported, the managed-Node rung must- still find a runnable agent-browser under the Hermes Node dir even when- it's absent from the probe process's PATH — the Windows installer shape- where install succeeded but the GUI still said needs setup."""- monkeypatch.setitem(sys.modules, "tools.browser_tool_install", None)- managed_dir = tmp_path / "node"- managed_dir.mkdir()- managed_bin = managed_dir / "agent-browser"- managed_bin.write_text("#!/bin/sh\nexit 0\n")- managed_bin.chmod(0o755)- real_which = shutil.which- monkeypatch.setattr(- shutil,- "which",- lambda cmd, *args, **kwargs: (- None- if cmd == "agent-browser" and not kwargs.get("path")- else real_which(cmd, *args, **kwargs)- ),- )- monkeypatch.setattr(- "hermes_constants.with_hermes_node_path", lambda: {"PATH": str(managed_dir)}- )- monkeypatch.setattr(- "hermes_constants.agent_browser_runnable",- lambda p: bool(p) and str(p) == str(managed_bin),- )-- assert ns._has_agent_browser() is True---def test_has_agent_browser_import_failure_and_no_binary_is_false(monkeypatch):- monkeypatch.setitem(sys.modules, "tools.browser_tool_install", None)- _block_legacy_agent_browser_checks(monkeypatch)-- assert ns._has_agent_browser() is Falsediff --git a/tests/hermes_cli/test_npm_engine.py b/tests/hermes_cli/test_npm_engine.pyindex 56e6e7e4264..cff018d2a3b 100644--- a/tests/hermes_cli/test_npm_engine.py+++ b/tests/hermes_cli/test_npm_engine.py@@ -121,9 +121,6 @@ class TestManagedDetection:system_npm.write_text("#!/bin/sh\n", encoding="utf-8")assert managed_npm_prefix(system_npm) is None- def test_no_npm_is_not_managed(self, managed_tree):- assert managed_npm_prefix(None) is None- assert managed_npm_prefix("") is Noneclass TestInUseDeferral:@@ -141,23 +138,6 @@ class TestInUseDeferral:monkeypatch.setenv("HERMES_HOME", str(home))return npm- def test_in_use_managed_tree_defers_upgrade_without_running_npm(- self, managed_npm, monkeypatch- ):- monkeypatch.setattr(npm_engine, "managed_node_tree_in_use", lambda: True)-- def forbidden_run(cmd, **kwargs):- raise AssertionError(f"npm must not run while the tree is in use: {cmd}")-- monkeypatch.setattr(subprocess, "run", forbidden_run)-- result = npm_engine.upgrade_managed_npm(- str(managed_npm),- ">=11.0.0",- prefix=managed_npm.parent,- quiet=True,- )- assert result is Falsedef test_in_use_deferral_blocks_repair_retry(self, managed_npm, monkeypatch):"""End-to-end: an in-use tree means no npm subprocess runs and nodiff --git a/tests/hermes_cli/test_observational_sessiondb_modes.py b/tests/hermes_cli/test_observational_sessiondb_modes.pyindex c8d88215072..d0e90234ed0 100644--- a/tests/hermes_cli/test_observational_sessiondb_modes.py+++ b/tests/hermes_cli/test_observational_sessiondb_modes.py@@ -1,22 +1,11 @@"""Regression coverage for #110173: observational `hermes sessions` readers stay read-only."""from argparse import Namespace-from unittest.mock import MagicMock-import pytestimport hermes_cli.sessions_cmd as sessions_cmd[email protected]("action", ["list", "stats", "pinned"])-def test_observational_sessions_actions_open_a_read_only_store(monkeypatch, action):- factory = MagicMock()- monkeypatch.setattr("hermes_state.SessionDB", factory)- monkeypatch.setitem(sessions_cmd._DB_HANDLERS, action, lambda _db, _args: None)-- sessions_cmd.cmd_sessions(Namespace(sessions_action=action))-- factory.assert_called_once_with(read_only=True)def test_sessions_observational_commands_on_missing_store_stay_empty(monkeypatch, tmp_path, capsys):diff --git a/tests/hermes_cli/test_ollama_cloud_auth.py b/tests/hermes_cli/test_ollama_cloud_auth.pyindex 93cb6100679..56733adc05d 100644--- a/tests/hermes_cli/test_ollama_cloud_auth.py+++ b/tests/hermes_cli/test_ollama_cloud_auth.py@@ -9,8 +9,6 @@ Covers:- /model tab completion for model aliases"""-import os-# ---------------------------------------------------------------------------# OLLAMA_API_KEY credential resolution@@ -95,71 +93,6 @@ class TestDirectAliases:assert alias == "glm"-# ----------------------------------------------------------------------------# /model command persistence-# -----------------------------------------------------------------------------class TestModelSwitchPersistence:- """CLI /model command should update requested_provider for session persistence."""-- def test_model_switch_result_fields(self):- """ModelSwitchResult has all required fields for CLI state update."""- from hermes_cli.model_switch import ModelSwitchResult-- result = ModelSwitchResult(- success=True,- new_model="claude-opus-4-6",- target_provider="anthropic",- provider_changed=True,- api_key="test-key",- base_url="https://api.anthropic.com",- api_mode="anthropic_messages",- )-- assert result.success- assert result.new_model == "claude-opus-4-6"- assert result.target_provider == "anthropic"- assert result.api_key == "test-key"- assert result.base_url == "https://api.anthropic.com"---# ----------------------------------------------------------------------------# Fallback base_url passthrough-# -----------------------------------------------------------------------------class TestFallbackBaseUrlPassthrough:- """_try_activate_fallback should pass base_url from fallback config."""-- def test_fallback_config_has_base_url(self):- """Verify fallback_providers config structure supports base_url."""- # This tests the contract: fallback dicts can have base_url- fb = {- "provider": "custom",- "model": "qwen3.5:397b",- "base_url": "https://ollama.com/v1",- }- assert fb.get("base_url") == "https://ollama.com/v1"-- def test_ollama_key_lookup_for_fallback(self, monkeypatch):- """When fallback base_url is ollama.com and no api_key, OLLAMA_API_KEY is used."""- monkeypatch.setenv("OLLAMA_API_KEY", "fb-ollama-key")-- fb = {- "provider": "custom",- "model": "qwen3.5:397b",- "base_url": "https://ollama.com/v1",- }-- fb_base_url_hint = (fb.get("base_url") or "").strip() or None- fb_api_key_hint = (fb.get("api_key") or "").strip() or None-- if fb_base_url_hint and "ollama.com" in fb_base_url_hint.lower() and not fb_api_key_hint:- fb_api_key_hint = os.getenv("OLLAMA_API_KEY") or None-- assert fb_api_key_hint == "fb-ollama-key"- assert fb_base_url_hint == "https://ollama.com/v1"--# ---------------------------------------------------------------------------# Edge cases: _load_direct_aliases# ---------------------------------------------------------------------------@@ -167,30 +100,6 @@ class TestFallbackBaseUrlPassthrough:class TestLoadDirectAliasesEdgeCases:"""Edge cases for _load_direct_aliases parsing."""- def test_empty_model_aliases_config(self, monkeypatch):- """Empty model_aliases dict returns only builtins (if any)."""- mock_config = {"model_aliases": {}}- monkeypatch.setattr(- "hermes_cli.config.load_config",- lambda: mock_config,- )-- from hermes_cli.model_switch import _load_direct_aliases- aliases = _load_direct_aliases()- assert isinstance(aliases, dict)--- def test_load_config_exception_returns_builtins(self, monkeypatch):- """If load_config raises, _load_direct_aliases returns builtins only."""- monkeypatch.setattr(- "hermes_cli.config.load_config",- lambda: (_ for _ in ()).throw(RuntimeError("config broken")),- )-- from hermes_cli.model_switch import _load_direct_aliases- aliases = _load_direct_aliases()- assert isinstance(aliases, dict)-def test_empty_model_string_skipped(self, monkeypatch):"""Entries with empty model string are skipped."""@@ -211,50 +120,6 @@ class TestLoadDirectAliasesEdgeCases:assert "good" in aliases-# ----------------------------------------------------------------------------# _ensure_direct_aliases idempotency-# -----------------------------------------------------------------------------class TestEnsureDirectAliases:- """_ensure_direct_aliases lazy-loading behavior."""-- def test_ensure_populates_on_first_call(self, monkeypatch):- """DIRECT_ALIASES is populated after _ensure_direct_aliases."""- import hermes_cli.model_switch as ms-- mock_config = {- "model_aliases": {- "test": {"model": "test-model", "provider": "custom"},- }- }- monkeypatch.setattr(- "hermes_cli.config.load_config",- lambda: mock_config,- )- monkeypatch.setattr(ms, "DIRECT_ALIASES", {})- ms._ensure_direct_aliases()- assert "test" in ms.DIRECT_ALIASES-- def test_ensure_no_reload_when_populated(self, monkeypatch):- """_ensure_direct_aliases does not reload if already populated."""- import hermes_cli.model_switch as ms- from hermes_cli.model_switch import DirectAlias-- existing = {"pre": DirectAlias("pre-model", "custom", "")}- monkeypatch.setattr(ms, "DIRECT_ALIASES", existing)-- call_count = [0]- original_load = ms._load_direct_aliases- def counting_load():- call_count[0] += 1- return original_load()- monkeypatch.setattr(ms, "_load_direct_aliases", counting_load)-- ms._ensure_direct_aliases()- assert call_count[0] == 0- assert "pre" in ms.DIRECT_ALIASES--# ---------------------------------------------------------------------------# resolve_alias: fallthrough and edge cases# ---------------------------------------------------------------------------@@ -358,7 +223,6 @@ class TestResolveAliasSorting:assert result.success is Falseassert "claude-opus-4-8" in result.error_messageassert "claude-opus-4-20250514" in result.error_message- assert "not switching automatically" in result.error_message# ---------------------------------------------------------------------------@@ -420,53 +284,3 @@ class TestSwitchModelDirectAliasOverride:assert result.successassert result.api_key == "no-key-required"assert result.base_url == "http://localhost:11434/v1"---# ----------------------------------------------------------------------------# CLI state update: requested_provider persistence-# -----------------------------------------------------------------------------class TestCLIStateUpdate:- """CLI /model handler should update requested_provider and explicit fields."""---# ----------------------------------------------------------------------------# Fallback: OLLAMA_API_KEY edge cases-# -----------------------------------------------------------------------------class TestFallbackEdgeCases:- """Edge cases for fallback OLLAMA_API_KEY logic."""-- def test_ollama_key_not_injected_for_localhost(self, monkeypatch):- """OLLAMA_API_KEY should not be injected for localhost URLs."""- monkeypatch.setenv("OLLAMA_API_KEY", "should-not-use")-- fb = {- "provider": "custom",- "model": "local-model",- "base_url": "http://localhost:11434/v1",- }-- fb_base_url_hint = (fb.get("base_url") or "").strip() or None- fb_api_key_hint = (fb.get("api_key") or "").strip() or None-- if fb_base_url_hint and "ollama.com" in fb_base_url_hint.lower() and not fb_api_key_hint:- fb_api_key_hint = os.getenv("OLLAMA_API_KEY") or None-- assert fb_api_key_hint is None--- def test_no_base_url_in_fallback(self, monkeypatch):- """Fallback with no base_url doesn't crash."""- monkeypatch.setenv("OLLAMA_API_KEY", "some-key")-- fb = {"provider": "openrouter", "model": "some-model"}-- fb_base_url_hint = (fb.get("base_url") or "").strip() or None- fb_api_key_hint = (fb.get("api_key") or "").strip() or None-- if fb_base_url_hint and "ollama.com" in fb_base_url_hint.lower() and not fb_api_key_hint:- fb_api_key_hint = os.getenv("OLLAMA_API_KEY") or None-- assert fb_base_url_hint is None- assert fb_api_key_hint is Nonediff --git a/tests/hermes_cli/test_ollama_cloud_provider.py b/tests/hermes_cli/test_ollama_cloud_provider.pyindex e27bf7482b1..1b2167e5074 100644--- a/tests/hermes_cli/test_ollama_cloud_provider.py+++ b/tests/hermes_cli/test_ollama_cloud_provider.py@@ -1,27 +1,10 @@"""Tests for Ollama Cloud provider integration."""import pytest-from unittest.mock import patch, MagicMock+from unittest.mock import patch-from hermes_cli.auth import PROVIDER_REGISTRY, resolve_provider, resolve_api_key_provider_credentials-from hermes_cli.models import _PROVIDER_MODELS, _PROVIDER_LABELS, _PROVIDER_ALIASES, normalize_provider-from hermes_cli.model_normalize import normalize_model_for_provider-from agent.model_metadata import _URL_TO_PROVIDER, _PROVIDER_PREFIXES-from agent.models_dev import PROVIDER_TO_MODELS_DEV, list_agentic_models---# ── Provider Registry ──--class TestOllamaCloudProviderRegistry:- def test_ollama_cloud_in_registry(self):- assert "ollama-cloud" in PROVIDER_REGISTRY-- def test_ollama_cloud_config(self):- pconfig = PROVIDER_REGISTRY["ollama-cloud"]- assert pconfig.id == "ollama-cloud"- assert pconfig.name == "Ollama Cloud"- assert pconfig.auth_type == "api_key"- assert pconfig.inference_base_url == "https://ollama.com/v1"+from hermes_cli.auth import resolve_provider, resolve_api_key_provider_credentials+from agent.models_dev import list_agentic_models# ── Provider Aliases ──@@ -46,12 +29,6 @@ class TestOllamaCloudAliases:assert resolve_provider("ollama_cloud") == "ollama-cloud"- def test_models_py_aliases(self):- assert _PROVIDER_ALIASES.get("ollama_cloud") == "ollama-cloud"- # bare "ollama" stays local- assert _PROVIDER_ALIASES.get("ollama") == "custom"--# ── Auto-detection ──class TestOllamaCloudAutoDetection:@@ -222,26 +199,9 @@ class TestOllamaCloudMergedDiscovery:assert live.called # the stale cache still triggers a probe on the next non-cache_only call----# ── Model Normalization ──--class TestOllamaCloudModelNormalization:--- def test_passthrough_no_tag(self):- assert normalize_model_for_provider("glm-5", "ollama-cloud") == "glm-5"---# ── URL-to-Provider Mapping ──--# ── models.dev Integration ──class TestOllamaCloudModelsDev:- def test_ollama_cloud_mapped(self):- assert PROVIDER_TO_MODELS_DEV.get("ollama-cloud") == "ollama-cloud"def test_list_agentic_models_with_mock_data(self):"""list_agentic_models filters correctly from mock models.dev data."""@@ -263,40 +223,9 @@ class TestOllamaCloudModelsDev:assert "some-embedding:latest" not in result # no tool_call-# ── Agent Init (no SyntaxError) ──--class TestOllamaCloudAgentInit:- def test_agent_imports_without_error(self):- """Verify run_agent.py has no SyntaxError."""- import importlib- import run_agent- importlib.reload(run_agent)-- def test_ollama_cloud_agent_uses_chat_completions(self, monkeypatch):- """Ollama Cloud falls through to chat_completions — no special elif needed."""- monkeypatch.setenv("OLLAMA_API_KEY", "test-key")- with patch("agent.process_bootstrap.OpenAI") as mock_openai:- mock_openai.return_value = MagicMock()- from run_agent import AIAgent- agent = AIAgent(- model="qwen3.5:397b",- provider="ollama-cloud",- api_key="test-key",- base_url="https://ollama.com/v1",- )- assert agent.api_mode == "chat_completions"- assert agent.provider == "ollama-cloud"--# ── providers.py New System ──class TestOllamaCloudProvidersNew:- def test_overlay_exists(self):- from hermes_cli.providers import HERMES_OVERLAYS- assert "ollama-cloud" in HERMES_OVERLAYS- overlay = HERMES_OVERLAYS["ollama-cloud"]- assert overlay.transport == "openai_chat"- assert overlay.base_url_env_var == "OLLAMA_BASE_URL"def test_alias_resolves(self):from hermes_cli.providers import normalize_provider as np@@ -304,14 +233,6 @@ class TestOllamaCloudProvidersNew:assert np("ollama-cloud") == "ollama-cloud"- def test_get_provider(self):- from hermes_cli.providers import get_provider- pdef = get_provider("ollama-cloud")- assert pdef is not None- assert pdef.id == "ollama-cloud"- assert pdef.transport == "openai_chat"--# ── Cloud Suffix Stripping ──class TestOllamaCloudSuffixStripping:@@ -346,22 +267,6 @@ class TestOllamaCloudSuffixStripping:assert "kimi-k2.6:cloud" not in resultassert "glm-5.1:cloud" not in result- def test_unsuffixed_model_id_unchanged(self, tmp_path, monkeypatch):- """Model IDs without :cloud / -cloud suffix are passed through unchanged."""- from hermes_cli.models import fetch_ollama_cloud_models-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.delenv("OLLAMA_API_KEY", raising=False)-- mock_mdev = {- "ollama-cloud": {- "models": {"nemotron-3-nano:30b": {"tool_call": True}}- }- }- with patch("agent.models_dev.fetch_models_dev", return_value=mock_mdev):- result = fetch_ollama_cloud_models(force_refresh=True)-- assert "nemotron-3-nano:30b" in resultdef test_strip_suffix_helper(self):"""Unit test for the _strip_ollama_cloud_suffix helper."""diff --git a/tests/hermes_cli/test_oneshot_fallback.py b/tests/hermes_cli/test_oneshot_fallback.pyindex 47ca0ed66c0..36607e67477 100644--- a/tests/hermes_cli/test_oneshot_fallback.py+++ b/tests/hermes_cli/test_oneshot_fallback.py@@ -63,7 +63,7 @@ class TestResolveRuntimeWithFallback:with caplog.at_level("WARNING", logger="hermes_cli.runtime_provider"):_, entry = resolve_runtime_with_fallback(_CFG, requested="openai-codex")assert entry["provider"] == "openai"- assert any("anthropic/claude-x is misconfigured" in r.getMessage() for r in caplog.records)+ assert any(r.levelname == "WARNING" and "anthropic" in r.getMessage() for r in caplog.records)def test_run_agent_falls_back_when_primary_resolution_raises_auth_error(monkeypatch):diff --git a/tests/hermes_cli/test_oneshot_resumed_session_persist.py b/tests/hermes_cli/test_oneshot_resumed_session_persist.pyindex f8a4f9b4b2e..c0094fc373e 100644--- a/tests/hermes_cli/test_oneshot_resumed_session_persist.py+++ b/tests/hermes_cli/test_oneshot_resumed_session_persist.py@@ -197,6 +197,3 @@ class TestOneShotDurableFlush:finally:db.close()- def test_flush_survives_missing_agent(self):- cli_mod._flush_one_shot_session_store(SimpleNamespace(agent=None))- cli_mod._flush_one_shot_session_store(SimpleNamespace())diff --git a/tests/hermes_cli/test_oneshot_skills.py b/tests/hermes_cli/test_oneshot_skills.pyindex 051dc4ffa16..0bc2d3ea8ba 100644--- a/tests/hermes_cli/test_oneshot_skills.py+++ b/tests/hermes_cli/test_oneshot_skills.py@@ -47,11 +47,3 @@ class TestBuildPreloadedSkillsPrompt:)assert _build_preloaded_skills_prompt(["good", "bad"]) == "PROMPT"- def test_loaded_prompt_returned(self, monkeypatch):- import agent.skill_commands as sc-- monkeypatch.setattr(- sc, "build_preloaded_skills_prompt",- lambda parsed, **kw: ("SKILL CONTENT", ["s"], []),- )- assert _build_preloaded_skills_prompt("s") == "SKILL CONTENT"diff --git a/tests/hermes_cli/test_oneshot_usage_file.py b/tests/hermes_cli/test_oneshot_usage_file.pyindex d582bc40d9f..b0d2df39e1a 100644--- a/tests/hermes_cli/test_oneshot_usage_file.py+++ b/tests/hermes_cli/test_oneshot_usage_file.py@@ -42,10 +42,6 @@ class TestWriteUsageFile:assert report["failed"] is Falseassert "failure" not in report- def test_none_path_is_noop(self, tmp_path):- # Must not raise and must not create a report file.- _write_usage_file(None, _result())- assert not (tmp_path / "usage.json").exists()def test_failure_marks_failed_and_records_message(self, tmp_path):path = tmp_path / "usage.json"@@ -57,8 +53,6 @@ class TestWriteUsageFile:assert report["estimated_cost_usd"] is None--class TestAuxiliaryLedger:"""#112848: auxiliary LLM spend (title generation, vision, ...) recorded in session_model_usagebelongs in the pipeline ledger, additively — the main-loop keys stay main-loop-only."""diff --git a/tests/hermes_cli/test_openai_codex_model_validation_fallback.py b/tests/hermes_cli/test_openai_codex_model_validation_fallback.pyindex 666ed4eaf17..2e2f79401bb 100644--- a/tests/hermes_cli/test_openai_codex_model_validation_fallback.py+++ b/tests/hermes_cli/test_openai_codex_model_validation_fallback.py@@ -35,8 +35,6 @@ def test_openai_codex_unknown_but_plausible_model_is_accepted_with_warning():assert result["persist"] is Trueassert result["recognized"] is Falseassert "gpt-5.3-codex-spark" in result["message"]- assert "OpenAI Codex model listing" in result["message"]- assert "Similar models" in result["message"]assert "gpt-5.3-codex" in result["message"]@@ -61,4 +59,3 @@ def test_switch_model_allows_openai_codex_model_missing_from_listing():assert result.new_model == "gpt-5.3-codex-spark"assert result.target_provider == "openai-codex"assert result.warning_message- assert "OpenAI Codex model listing" in result.warning_messagediff --git a/tests/hermes_cli/test_openai_discovery_endpoint.py b/tests/hermes_cli/test_openai_discovery_endpoint.pyindex 610ac039681..6f1cb540736 100644--- a/tests/hermes_cli/test_openai_discovery_endpoint.py+++ b/tests/hermes_cli/test_openai_discovery_endpoint.py@@ -134,14 +134,15 @@ class TestRegionalCatalogFiltering:def test_official_hosts_intersect_with_curated(self, monkeypatch, base):monkeypatch.setenv("OPENAI_API_KEY", "sk-test")monkeypatch.setenv("OPENAI_BASE_URL", base)+ curated = models_mod._PROVIDER_MODELS["openai-api"][0]with mock_patch.object(- models_mod, "fetch_api_models", return_value=list(self._RAW_DUMP)+ models_mod, "fetch_api_models", return_value=[curated, *self._RAW_DUMP]):ids = models_mod.provider_model_ids("openai-api", force_refresh=True)assert "whisper-1" not in idsassert "tts-1" not in idsassert "text-embedding-ada-002" not in ids- assert "gpt-5.6-terra" in ids+ assert curated in idsdef test_custom_proxy_keeps_live_list_verbatim(self, monkeypatch):monkeypatch.setenv("OPENAI_API_KEY", "sk-test")diff --git a/tests/hermes_cli/test_openai_listing_authority.py b/tests/hermes_cli/test_openai_listing_authority.pyindex e29156e17f9..c987df75eb6 100644--- a/tests/hermes_cli/test_openai_listing_authority.py+++ b/tests/hermes_cli/test_openai_listing_authority.py@@ -54,8 +54,8 @@ class TestOfficialHostAuthority:class TestCuratedFallbackPreserved:def test_custom_proxy_keeps_curated_fallback(self):- # gpt-5.5 is in the curated openai catalog; a custom proxy's listing- # may be incomplete, so the #46850 soft-accept stays.- result = _validate("gpt-5.5", "https://proxy.corp.test/v1", live=["some-other-model"])+ # A curated model absent from a custom proxy's (often incomplete)+ # listing keeps the #46850 soft-accept.+ curated = models_mod._PROVIDER_MODELS["openai-api"][0]+ result = _validate(curated, "https://proxy.corp.test/v1", live=["some-other-model"])assert result["accepted"] is True- assert "curated catalog" in (result.get("message") or "")diff --git a/tests/hermes_cli/test_openai_picker_curated.py b/tests/hermes_cli/test_openai_picker_curated.pyindex 64bea9640b4..e3d9d48eb8a 100644--- a/tests/hermes_cli/test_openai_picker_curated.py+++ b/tests/hermes_cli/test_openai_picker_curated.py@@ -18,20 +18,10 @@ Bug 2 — OpenRouter appeared authenticated whenever OPENAI_API_KEY was setin runtime_provider.py, independent of the overlay)."""-import osfrom unittest.mock import patch-import pytestfrom hermes_cli import models as M-from hermes_cli.providers import HERMES_OVERLAYS---# --- Bug 2: overlay no longer lists OPENAI_API_KEY ----------------------------def test_openrouter_overlay_does_not_list_openai_api_key():- overlay = HERMES_OVERLAYS["openrouter"]- assert "OPENAI_API_KEY" not in overlay.extra_env_vars# --- Bug 1: default OpenAI endpoint filters to curated agentic models -------diff --git a/tests/hermes_cli/test_opencode_go_in_model_list.py b/tests/hermes_cli/test_opencode_go_in_model_list.pyindex f784f75f31b..5af8e8218b6 100644--- a/tests/hermes_cli/test_opencode_go_in_model_list.py+++ b/tests/hermes_cli/test_opencode_go_in_model_list.py@@ -6,22 +6,6 @@ from unittest.mock import patchfrom hermes_cli.model_switch import list_authenticated_providers-# Minimum set of models that must be present for opencode-go no matter-# whether the picker sourced its list from curated-only or curated+models.dev.-# The curated list in hermes_cli/models.py defines the floor; models.dev only-# ever adds names on top of it via _merge_with_models_dev.-_OPENCODE_GO_REQUIRED = {- "kimi-k2.6",- "kimi-k2.5",- "glm-5.1",- "glm-5",- "mimo-v2-pro",- "mimo-v2-omni",- "minimax-m2.7",- "minimax-m2.5",-}--@patch.dict(os.environ, {"OPENCODE_GO_API_KEY": "test-key"}, clear=False)def test_opencode_go_appears_when_api_key_set():"""opencode-go should appear in list_authenticated_providers when OPENCODE_GO_API_KEY is set."""@@ -31,20 +15,7 @@ def test_opencode_go_appears_when_api_key_set():opencode_go = next((p for p in providers if p["slug"] == "opencode-go"), None)assert opencode_go is not None, "opencode-go should appear when OPENCODE_GO_API_KEY is set"- # Behavior check: the curated floor must be present. The list may also- # include extra models.dev entries (e.g. mimo-v2.5-pro) when the registry- # is reachable — that's the whole point of the models.dev-preferred merge- # introduced for opencode-go, so don't pin to an exact list here.- present = set(opencode_go["models"])- missing = _OPENCODE_GO_REQUIRED - present- assert not missing, (- f"opencode-go picker should include the curated floor; missing: {sorted(missing)}. "- f"Got: {opencode_go['models']}"- )- # opencode-go can appear as "built-in" (from PROVIDER_TO_MODELS_DEV when- # models.dev is reachable) or "hermes" (from HERMES_OVERLAYS fallback when- # the API is unavailable, e.g. in CI).- assert opencode_go["source"] in {"built-in", "hermes"}+ assert opencode_go["models"], "opencode-go picker must list models"def test_opencode_go_not_appears_when_no_creds():diff --git a/tests/hermes_cli/test_opencode_go_validation_fallback.py b/tests/hermes_cli/test_opencode_go_validation_fallback.pyindex b4168a75410..4afd5edd79c 100644--- a/tests/hermes_cli/test_opencode_go_validation_fallback.py+++ b/tests/hermes_cli/test_opencode_go_validation_fallback.py@@ -46,7 +46,9 @@ def _patched(func):def test_opencode_go_known_model_accepted():"""A model present in the opencode-go curated catalog must be acceptedeven when /models is unreachable."""- result = validate_requested_model("kimi-k2.6", "opencode-go")+ from hermes_cli.models import _PROVIDER_MODELS++ result = validate_requested_model(_PROVIDER_MODELS["opencode-go"][0], "opencode-go")assert result["accepted"] is Trueassert result["persist"] is Trueassert result["recognized"] is True@@ -62,9 +64,6 @@ def test_opencode_go_totally_unknown_model_still_accepted():assert result["accepted"] is Trueassert result["persist"] is Trueassert result["recognized"] is False- # No suggestion text (no close matches)- assert "Similar models" not in result["message"]- assert "opencode" in result["message"].lower() or "opencode go" in result["message"].lower()# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_openrouter_preset_validation.py b/tests/hermes_cli/test_openrouter_preset_validation.pyindex a5a19b005b5..657adebb77f 100644--- a/tests/hermes_cli/test_openrouter_preset_validation.py+++ b/tests/hermes_cli/test_openrouter_preset_validation.py@@ -42,7 +42,7 @@ def test_combined_openrouter_preset_reference_validates_base_model():with patch("hermes_cli.models.fetch_api_models",return_value=["openai/gpt-5.4"],- ) as mock_fetch:+ ):result = validate_requested_model("openai/gpt-5.4@preset/email-copywriter","openrouter",@@ -50,7 +50,6 @@ def test_combined_openrouter_preset_reference_validates_base_model():base_url="https://openrouter.ai/api/v1",)- mock_fetch.assert_called_once_with("key", "https://openrouter.ai/api/v1")assert result == {"accepted": True,"persist": True,@@ -71,7 +70,6 @@ def test_combined_openrouter_preset_reference_rejects_unknown_base_model():assert result["accepted"] is Falseassert result["persist"] is Falseassert result["recognized"] is False- assert "Similar models" in result["message"]assert "openai/gpt-5.4" in result["message"]@@ -119,7 +117,6 @@ def test_openrouter_preset_reference_requires_a_url_safe_slug(model_name):assert result["accepted"] is Falseassert result["persist"] is Falseassert result["recognized"] is False- assert "URL-safe" in result["message"]def test_preset_reference_does_not_bypass_other_provider_validation():@@ -154,7 +151,6 @@ def test_preset_reference_does_not_bypass_custom_endpoint_validation():mock_probe.assert_called_once()assert result["accepted"] is Trueassert result["recognized"] is False- assert "custom endpoint's model listing" in result["message"]def test_configured_alias_switches_preset_through_real_resolution_chain(tmp_path):diff --git a/tests/hermes_cli/test_openrouter_reasoning_metadata.py b/tests/hermes_cli/test_openrouter_reasoning_metadata.pyindex 96499ce6ffb..6004489ff70 100644--- a/tests/hermes_cli/test_openrouter_reasoning_metadata.py+++ b/tests/hermes_cli/test_openrouter_reasoning_metadata.py@@ -118,17 +118,6 @@ class TestOpenRouterModelReasoningCapabilities:monkeypatch.setattr(models_mod, "_openrouter_reasoning_caps_cache", caps_by_id)monkeypatch.setattr(models_mod, "_openrouter_reasoning_caps_failed_at", None)- def test_known_model(self, monkeypatch):- from hermes_cli.models_reasoning_caps import openrouter_model_reasoning_capabilities- self._prime_cache(monkeypatch, {- "nvidia/nemotron-3-ultra": {- "supports_reasoning": True,- "supported_efforts": ["low", "high"],- "mandatory": False,- },- })- caps = openrouter_model_reasoning_capabilities("nvidia/nemotron-3-ultra")- assert caps["supports_reasoning"] is Truedef test_unlisted_model_returns_none(self, monkeypatch):from hermes_cli.models_reasoning_caps import openrouter_model_reasoning_capabilitiesdiff --git a/tests/hermes_cli/test_orphan_desktop_serve_reap.py b/tests/hermes_cli/test_orphan_desktop_serve_reap.pyindex d0dc26b61e7..dfff501b94c 100644--- a/tests/hermes_cli/test_orphan_desktop_serve_reap.py+++ b/tests/hermes_cli/test_orphan_desktop_serve_reap.py@@ -78,7 +78,6 @@ def test_reap_only_kills_ppid1_local_serves():side_effect=lambda pid: ppids.get(pid),),patch("os.kill", side_effect=fake_kill),- patch("sys.platform", "darwin"),):os.environ.pop("HERMES_DESKTOP_CHILD_PID", None)result = _reap_orphaned_desktop_local_serves(@@ -101,7 +100,6 @@ def test_reap_passes_child_pid_exclude_to_scan():"hermes_cli.dashboard_procs._scan_dashboard_processes",return_value=[],) as scan,- patch("sys.platform", "darwin"),patch.dict(os.environ, {"HERMES_DESKTOP_CHILD_PID": "999,111"}, clear=False),):result = _reap_orphaned_desktop_local_serves(sleep_fn=lambda _s: None)@@ -250,7 +248,6 @@ def test_reap_spare_lock_owned_ssh_remote_backend_of_foreign_client():side_effect=lambda pid: ppids.get(pid),),patch("os.kill", side_effect=fake_kill),- patch("sys.platform", "darwin"),):os.environ.pop("HERMES_DESKTOP_CHILD_PID", None)result = _reap_orphaned_desktop_local_serves(@@ -287,7 +284,6 @@ def test_reap_spares_young_backend_until_desktop_can_write_lock():),patch("hermes_cli.dashboard_procs._process_ppid", return_value=1),patch("os.kill", side_effect=fake_kill),- patch("sys.platform", "darwin"),):result = _reap_orphaned_desktop_local_serves(sleep_fn=lambda _s: None,@@ -315,7 +311,6 @@ def test_reap_spares_backend_when_process_age_is_unknown():),patch("hermes_cli.dashboard_procs._process_ppid", return_value=1),patch("os.kill", side_effect=lambda pid, sig: terms.append(pid) if sig == 15 else None),- patch("sys.platform", "darwin"),):result = _reap_orphaned_desktop_local_serves(sleep_fn=lambda _s: None,@@ -355,7 +350,6 @@ def test_reap_age_boundary_makes_180_second_orphan_eligible():),patch("hermes_cli.dashboard_procs._process_ppid", return_value=1),patch("os.kill", side_effect=fake_kill),- patch("sys.platform", "darwin"),):result = _reap_orphaned_desktop_local_serves(sleep_fn=lambda _s: None,@@ -399,7 +393,6 @@ def test_reap_spare_lock_owned_backend_even_without_exclude_match(tmp_path):return_value=1,),patch("os.kill", side_effect=fake_kill),- patch("sys.platform", "darwin"),):os.environ.pop("HERMES_DESKTOP_CHILD_PID", None)result = _reap_orphaned_desktop_local_serves(@@ -437,7 +430,6 @@ def test_reap_kills_descendants_of_killed_roots_but_spares_a_failed_roots_subtrepatch("gateway.status.get_process_start_time", side_effect=start_times.get),patch("psutil.pid_exists", return_value=True),patch("os.kill", side_effect=fake_kill),- patch("sys.platform", "darwin"),):os.environ.pop("HERMES_DESKTOP_CHILD_PID", None)result = _reap_orphaned_desktop_local_serves(diff --git a/tests/hermes_cli/test_parser_epilogue_gateway_profile.py b/tests/hermes_cli/test_parser_epilogue_gateway_profile.pydeleted file mode 100644index e5c650f67d2..00000000000--- a/tests/hermes_cli/test_parser_epilogue_gateway_profile.py+++ /dev/null@@ -1,30 +0,0 @@-"""The ``--help`` epilogue must cover the profile-scoped gateway lifecycle.--``-p/--profile`` is consumed before argparse (``main._apply_profile_override``), so it never-appears among the parser's option rows — the epilogue examples are the only place ``--help``-can teach the ``hermes -p <profile> gateway <action>`` form that generated service units and-user-facing copy already rely on. Contract, not snapshot: assert the verbs and the profile flag-are named in the RENDERED help (the wiring, not just the constant), not the exact wording.-"""--from hermes_cli._parser import PRE_ARGPARSE_INHERITED_FLAGS, build_top_level_parser---def _rendered_help() -> str:- return build_top_level_parser()[0].format_help()---def test_rendered_help_documents_the_profile_scoped_command_form():- help_text = _rendered_help()- assert "hermes -p <profile>" in help_text- assert "--profile" in help_text- assert "hermes -p coder gateway stop" in help_text- # The flag stays pre-argparse: documented in the epilogue, never registered as an option.- assert ("-p", True) in PRE_ARGPARSE_INHERITED_FLAGS- assert "-p PROFILE" not in help_text and "--profile PROFILE" not in help_text---def test_rendered_help_documents_the_gateway_service_verbs():- help_text = _rendered_help()- for verb in ("install", "start", "stop", "status"):- assert f"hermes gateway {verb}" in help_text, verbdiff --git a/tests/hermes_cli/test_partial_compress.py b/tests/hermes_cli/test_partial_compress.pyindex ca9c840c7ed..dc0db6f12a9 100644--- a/tests/hermes_cli/test_partial_compress.py+++ b/tests/hermes_cli/test_partial_compress.py@@ -5,7 +5,6 @@ Inspired by Claude Code's Rewind "Summarize up to here" action."""from hermes_cli.partial_compress import (- DEFAULT_KEEP_LAST,MAX_KEEP_LAST,parse_partial_compress_args,rejoin_compressed_head_and_tail,@@ -13,15 +12,6 @@ from hermes_cli.partial_compress import ()-def _history(n_pairs: int) -> list[dict[str, str]]:- """Build n_pairs of (user, assistant) exchanges."""- h: list[dict[str, str]] = []- for i in range(n_pairs):- h.append({"role": "user", "content": f"u{i}"})- h.append({"role": "assistant", "content": f"a{i}"})- return h--# ── parse_partial_compress_args ──────────────────────────────────────@@ -86,10 +76,6 @@ def test_split_tail_always_starts_on_user():-def test_split_rejoin_preserves_all_messages():- h = _history(6)- head, tail = split_history_for_partial_compress(h, keep_last=3)- assert head + tail == h# ── rejoin_compressed_head_and_tail (seam-alternation guard) ─────────diff --git a/tests/hermes_cli/test_path_completion.py b/tests/hermes_cli/test_path_completion.pyindex 5ebd9163a0a..75435a77895 100644--- a/tests/hermes_cli/test_path_completion.py+++ b/tests/hermes_cli/test_path_completion.py@@ -110,10 +110,6 @@ class TestIntegration:class TestFileSizeLabel:- def test_bytes(self, tmp_path):- f = tmp_path / "small.txt"- f.write_text("hi")- assert _file_size_label(str(f)) == "2B"def test_nonexistent(self):diff --git a/tests/hermes_cli/test_peer_cmd.py b/tests/hermes_cli/test_peer_cmd.pyindex 0c3becabf38..6e524ae5e4a 100644--- a/tests/hermes_cli/test_peer_cmd.py+++ b/tests/hermes_cli/test_peer_cmd.py@@ -441,18 +441,6 @@ def test_dm_older_peer_hidden_duplicate_gives_clear_error(monkeypatch, capsys, oassert "Title already in use" in err-def test_dm_older_peer_with_visible_bot_chat_still_works(monkeypatch, capsys, fake_peer_server):- """Backward compat: an older peer ignores the new query params and returns- the plain visible listing — a visible Bot Chat must still resolve."""- _FakePeer.sessions = ["bc_visible"]- monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": fake_peer_server}})- monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")-- rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="ping", json=True))-- assert rc == 0- assert json.loads(capsys.readouterr().out)["reply"] == "reply from the other machine"- assert _FakePeer.sessions == ["bc_visible"]def test_run_starts_async_turn_with_canonical_session_and_idempotency(diff --git a/tests/hermes_cli/test_personality_none.py b/tests/hermes_cli/test_personality_none.pyindex 2d94015dfbe..f10f0d21fcb 100644--- a/tests/hermes_cli/test_personality_none.py+++ b/tests/hermes_cli/test_personality_none.py@@ -152,34 +152,7 @@ class TestGatewayPersonalityNone:assert runner._get_system_prompt_for_channel(None, "c") == "You are helpful."assert "helpful" in result.lower()- @pytest.mark.asyncio- async def test_unknown_shows_none_in_available(self, tmp_path):- runner = self._make_runner()- config_data = {"agent": {"personalities": {"helpful": "You are helpful."}}}- config_file = tmp_path / "config.yaml"- config_file.write_text(yaml.dump(config_data))-- p1, p2 = self._gateway_env(tmp_path)- with p1, p2:- event = self._make_event("nonexistent")- result = await runner._handle_personality_command(event)-- assert "none" in result.lower()-- @pytest.mark.asyncio- async def test_empty_personality_list_still_lists_builtins(self, tmp_path):- # Built-ins are always available — an empty agent.personalities no- # longer means "no personalities configured".- runner = self._make_runner(personalities={})- (tmp_path / "config.yaml").write_text(yaml.dump({"agent": {"personalities": {}}}))-- p1, p2 = self._gateway_env(tmp_path)- with p1, p2:- event = self._make_event("")- result = await runner._handle_personality_command(event)- assert "kawaii" in result.lower()- assert "pirate" in result.lower()class TestPersonalityDictFormat:@@ -210,19 +183,4 @@ class TestPersonalityDictFormat:cli._handle_personality_command("/personality coder")assert "You are an expert programmer." in cli.system_prompt- def test_dict_personality_includes_style(self):- cli = self._make_cli({- "coder": {- "system_prompt": "You are an expert programmer.",- "style": "use code examples",- }- })- with patch("hermes_cli.personality.persist_personality", return_value=True):- cli._handle_personality_command("/personality coder")- assert "Style: use code examples" in cli.system_prompt- def test_string_personality_still_works(self):- cli = self._make_cli({"helper": "You are helpful."})- with patch("hermes_cli.personality.persist_personality", return_value=True):- cli._handle_personality_command("/personality helper")- assert cli.system_prompt == "You are helpful."diff --git a/tests/hermes_cli/test_personality_single_owner.py b/tests/hermes_cli/test_personality_single_owner.pyindex 8d538aeb620..9d13866c6af 100644--- a/tests/hermes_cli/test_personality_single_owner.py+++ b/tests/hermes_cli/test_personality_single_owner.py@@ -18,7 +18,6 @@ from hermes_cli.personality import (BUILTIN_PERSONALITIES,available_personalities,active_personality_name,- describe_personality,normalize_personality_name,persist_personality,prompt_text,@@ -73,11 +72,9 @@ def test_resolve_personality_neutral_and_case_insensitive():assert prompt == KAWAII-def test_resolve_personality_unknown_raises_with_listing():- with pytest.raises(ValueError) as exc:+def test_resolve_personality_unknown_raises():+ with pytest.raises(ValueError):resolve_personality("doesnotexist", {})- assert "Available" in str(exc.value)- assert "`none`" in str(exc.value)def test_resolve_overlay_personality_wins_over_manual_prompt():@@ -121,10 +118,6 @@ def test_prompt_text_normalizes_none_str_list():assert prompt_text(["a", " b ", ""]) == "a\nb"-def test_describe_personality_truncates_and_flattens():- assert describe_personality("x" * 80) == "x" * 50 + "..."- assert "\n" not in describe_personality("a\nb")- assert describe_personality({"description": "short desc"}) == "short desc"# ── persistence (single write path) ──────────────────────────────────────────diff --git a/tests/hermes_cli/test_pet_toggle.py b/tests/hermes_cli/test_pet_toggle.pyindex c1b55f939f3..b9c14425017 100644--- a/tests/hermes_cli/test_pet_toggle.py+++ b/tests/hermes_cli/test_pet_toggle.py@@ -4,50 +4,6 @@ from __future__ import annotationsimport pytest-from agent.pet import store-from agent.pet.constants import FRAME_H, FRAME_W---def boba_installed(tmp_path, monkeypatch):- from PIL import Image-- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))-- sheet = Image.new("RGBA", (FRAME_W * 8, FRAME_H * 9), (0, 0, 0, 0))- pet_dir = store.pets_dir() / "boba"- pet_dir.mkdir(parents=True, exist_ok=True)- sheet.save(pet_dir / "spritesheet.webp")- (pet_dir / "pet.json").write_text(- '{"id":"boba","displayName":"Boba","description":"d","spritesheetPath":"spritesheet.webp"}'- )- return home---def _write_config(home, *, enabled: bool, slug: str = "") -> None:- import yaml-- cfg = {"display": {"pet": {"enabled": enabled, "slug": slug, "scale": 0.33}}}- (home / "config.yaml").write_text(yaml.dump(cfg), encoding="utf-8")-----def test_toggle_pet_display_errors_with_no_installed_pets(tmp_path, monkeypatch):- from hermes_cli.pets import toggle_pet_display-- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- _write_config(home, enabled=False, slug="")-- enabled, name, err = toggle_pet_display()-- assert enabled is False- assert name is None- assert err is not Nonedef test_pets_cli_quoted_false_disables_and_toggle_enables(tmp_path, monkeypatch):diff --git a/tests/hermes_cli/test_picker_prewarm.py b/tests/hermes_cli/test_picker_prewarm.pyindex 8f1c27a07b9..20ca8c1ae33 100644--- a/tests/hermes_cli/test_picker_prewarm.py+++ b/tests/hermes_cli/test_picker_prewarm.py@@ -19,17 +19,6 @@ def _reset_guard():model_switch_providers._picker_prewarm_done.clear()-def test_prewarm_runs_list_authenticated_providers_once():- """First call spawns a thread that calls list_authenticated_providers;- the warm side effect is delegated there (which disk-caches per provider)."""- _reset_guard()- with patch.object(ms, "list_authenticated_providers", return_value=[]) as mock_list:- t = model_switch_providers.prewarm_picker_cache_async()- assert t is not None, "first call must spawn a prewarm thread"- t.join(timeout=10)- assert not t.is_alive(), "prewarm thread should finish promptly"- mock_list.assert_called_once()- _reset_guard()def test_prewarm_guard_is_once_per_process():diff --git a/tests/hermes_cli/test_placeholder_usage.py b/tests/hermes_cli/test_placeholder_usage.pydeleted file mode 100644index 53c929ae551..00000000000--- a/tests/hermes_cli/test_placeholder_usage.py+++ /dev/null@@ -1,39 +0,0 @@-"""Tests for CLI placeholder text in config/setup output."""--import os-from argparse import Namespace-from unittest.mock import patch--import pytest--from hermes_cli.config import config_command, show_config-from hermes_cli.setup import _print_setup_summary---def test_config_set_usage_marks_placeholders(capsys):- args = Namespace(config_command="set", key=None, value=None)-- with pytest.raises(SystemExit) as exc:- config_command(args)-- assert exc.value.code == 1- out = capsys.readouterr().out- # The usage line documents the optional --force flag added in #34067- # (schema validation for unknown keys). Placeholder convention is preserved:- # the literal ``<key>`` and ``<value>`` markers must still be present so- # downstream tooling can detect placeholder syntax.- assert "Usage: hermes config set" in out- assert "<key>" in out- assert "<value>" in out- # --force escape hatch must be documented in the usage line.- assert "--force" in out---def test_show_config_marks_placeholders(tmp_path, capsys):- with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):- show_config()-- out = capsys.readouterr().out- assert "hermes config set <key> <value>" in out--diff --git a/tests/hermes_cli/test_plan_reconciliation_windows_live.py b/tests/hermes_cli/test_plan_reconciliation_windows_live.pydeleted file mode 100644index 86a8e768f8e..00000000000--- a/tests/hermes_cli/test_plan_reconciliation_windows_live.py+++ /dev/null@@ -1,95 +0,0 @@-"""LIVE Windows E2E for plan-reconciliation (#92902) on windows-latest.--Real processes with real Hermes-shaped argv, real inventory collection-(PID-file discovery + supervisor detection on REAL Windows), real-reconciliation. No mocks on the components under test.-- 1. Spawn a real process registered as a profile gateway (PID file + state- file in a temp HERMES_HOME) — real collect_runtime_inventory() must find- it, classify supervisor=manual, mechanism id 'manual'.- 2. Reconcile with bookkeeping that MISSES it -> unaccounted + escalation.- 3. Reconcile with it in killed_pids -> 'stopped', no escalation.- 4. Machine-id contract holds on Windows (no display strings leak in).-"""-import io, contextlib, json, os, subprocess, sys, tempfile, time-from pathlib import Path--WORKTREE = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(WORKTREE))--import pytest--pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="live Windows E2E")---def test_plan_reconciliation_live_windows(tmp_path, monkeypatch):- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))-- # Real live process standing in for a manual gateway- child = subprocess.Popen(- [sys.executable, "-c", "import time; time.sleep(120)"],- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,- )- try:- time.sleep(0.5)- assert child.poll() is None-- import psutil-- create_time = psutil.Process(child.pid).create_time()- (home / "gateway_state.json").write_text(json.dumps({- "pid": child.pid,- "create_time": create_time,- "gateway_state": "running",- "kind": "hermes-gateway",- "code_sha": "f" * 40,- "code_version": "0.20.5",- }), encoding="utf-8")-- import hermes_cli.profiles as profiles_mod- monkeypatch.setattr(profiles_mod, "_get_default_hermes_home", lambda: home)- monkeypatch.setattr(profiles_mod, "_get_profiles_root", lambda: tmp_path / "none")-- from hermes_cli.update_inventory import (- collect_runtime_inventory,- match_runtime_outcomes,- report_unaccounted_runtimes,- )-- plan = collect_runtime_inventory()- rows = [r for r in plan.runtimes if r.pid == child.pid]- assert rows, f"real inventory missed the live process: {plan.runtimes}"- rt = rows[0]- assert rt.supervisor == "manual"- assert rt.restart_via == "manual", "machine id, not display string"- assert rt.code_sha == "f" * 40-- # 2. bookkeeping misses it -> unaccounted + escalation- buf = io.StringIO()- with contextlib.redirect_stdout(buf):- outcomes = match_runtime_outcomes(- plan, restarted_services=[], relaunched_profiles=[],- externally_supervised_profiles=[], killed_pids=set(),- failed_units=[],- )- escalated = report_unaccounted_runtimes(outcomes)- mine = [o for o in outcomes if o["pid"] == child.pid]- assert mine and mine[0]["outcome"] == "unaccounted"- assert escalated is True- assert "never touched" in buf.getvalue()-- # 3. accounted as stopped -> clean- outcomes2 = match_runtime_outcomes(- plan, restarted_services=[], relaunched_profiles=[],- externally_supervised_profiles=[], killed_pids={child.pid},- failed_units=[],- )- mine2 = [o for o in outcomes2 if o["pid"] == child.pid]- assert mine2 and mine2[0]["outcome"] == "stopped"- assert report_unaccounted_runtimes(outcomes2) is False- finally:- if child.poll() is None:- child.kill()- child.wait()diff --git a/tests/hermes_cli/test_platform_actions.py b/tests/hermes_cli/test_platform_actions.pyindex 8a7d66e05a9..c9c400fad18 100644--- a/tests/hermes_cli/test_platform_actions.py+++ b/tests/hermes_cli/test_platform_actions.py@@ -22,8 +22,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom gateway.config import Platform-from hermes_cli.platform_actions import CAPABILITY_ID, PlatformActions-from hermes_cli.plugin_capabilities import CAPABILITY_REGISTRY+from hermes_cli.platform_actions import PlatformActionsdef _grant(granted: bool):@@ -67,17 +66,6 @@ def _discord_adapter(connected=True):return a-class TestCapabilityRegistry:- def test_gateway_platform_actions_registered(self):- spec = CAPABILITY_REGISTRY.get("gateway.platform_actions")- assert spec is not None- assert spec.legacy_path == ("allow_platform_actions",)- assert spec.description-- def test_facade_uses_registered_id(self):- assert CAPABILITY_ID == "gateway.platform_actions"--class TestGateDefaultOff:def test_no_grant_returns_structured_error(self):actions = PlatformActions("some-plugin")diff --git a/tests/hermes_cli/test_plugin_auxiliary_tasks.py b/tests/hermes_cli/test_plugin_auxiliary_tasks.pyindex e463cc58242..c60a80792a4 100644--- a/tests/hermes_cli/test_plugin_auxiliary_tasks.py+++ b/tests/hermes_cli/test_plugin_auxiliary_tasks.py@@ -1,13 +1,4 @@-"""Tests for the plugin auxiliary-task registration API.--Covers:- - PluginContext.register_auxiliary_task() validation- - PluginManager._aux_tasks storage + force-rediscovery clearing- - get_plugin_auxiliary_tasks() module-level helper- - _all_aux_tasks() merge of built-in + plugin tasks- - _reset_aux_to_auto() includes plugin tasks- - _get_auxiliary_task_config() layers plugin defaults under user config-"""+"""Plugin-registered auxiliary tasks merge into the built-in task list and ``_reset_aux_to_auto``."""from __future__ import annotations@@ -17,26 +8,12 @@ from hermes_cli.plugins import (PluginContext,PluginManager,PluginManifest,- get_plugin_auxiliary_tasks,)# ── Fixtures ─────────────────────────────────────────────────────────────────-def _make_ctx(name: str = "test_plugin") -> tuple[PluginContext, PluginManager]:- """Build a PluginContext + fresh PluginManager wired together.-- The manager skips discovery (no plugins.yaml, no scan) so the test- can exercise registration paths directly.- """- manager = PluginManager()- manager._discovered = True # skip auto-discovery on lookup- manifest = PluginManifest(name=name)- ctx = PluginContext(manifest, manager)- return ctx, manager--@pytest.fixturedef patched_manager(monkeypatch):"""Replace the module-level singleton with a fresh manager for the test.@@ -57,40 +34,6 @@ def patched_manager(monkeypatch):yield fresh-# ── PluginContext.register_auxiliary_task ────────────────────────────────────---def test_register_auxiliary_task_basic():- ctx, manager = _make_ctx("my_plugin")- ctx.register_auxiliary_task(- key="my_task",- display_name="My task",- description="a custom side task",- )- assert "my_task" in manager._aux_tasks- entry = manager._aux_tasks["my_task"]- assert entry["key"] == "my_task"- assert entry["display_name"] == "My task"- assert entry["description"] == "a custom side task"- assert entry["plugin"] == "my_plugin"- # Routing defaults populated- assert entry["defaults"]["provider"] == "auto"- assert entry["defaults"]["model"] == ""- assert entry["defaults"]["timeout"] == 60-----# ── PluginManager state lifecycle ────────────────────────────────────────────-----# ── Module-level helper ──────────────────────────────────────────────────────----# ── _all_aux_tasks merges built-in + plugin ──────────────────────────────────@@ -120,8 +63,6 @@ def test_all_aux_tasks_includes_plugin_registered(patched_manager):)--# ── _reset_aux_to_auto includes plugin tasks ─────────────────────────────────@@ -155,10 +96,3 @@ def test_reset_aux_to_auto_resets_plugin_tasks(tmp_path, monkeypatch, patched_macfg = load_config()assert cfg["auxiliary"]["my_aux"]["provider"] == "auto"assert cfg["auxiliary"]["my_aux"]["model"] == ""---# ── auxiliary_client._get_auxiliary_task_config defaults layering ────────────----diff --git a/tests/hermes_cli/test_plugin_call_mcp.py b/tests/hermes_cli/test_plugin_call_mcp.pyindex 95c1d42bfa5..92278a08eb5 100644--- a/tests/hermes_cli/test_plugin_call_mcp.py+++ b/tests/hermes_cli/test_plugin_call_mcp.py@@ -32,7 +32,6 @@ def _patch_config(monkeypatch, entries: dict) -> None:def _patch_handler(monkeypatch, response: str, captured: dict | None = None):"""Replace tools.mcp_tool_handlers._make_tool_handler with a transport mock."""- import tools.mcp_tool as mcp_modfrom tools import mcp_tool_handlers as _mcp_handlersdef _fake_make_handler(server_name, tool_name, tool_timeout):@@ -161,14 +160,6 @@ def test_structured_content_passthrough(monkeypatch):# ----------------------------------------------------------------------------def test_timeout_forwarded_to_handler(monkeypatch):- _patch_config(monkeypatch, {"my-plugin": {"mcp_allowlist": ["slow"]}})- captured = {}- _patch_handler(monkeypatch, '{"result": ""}', captured)-- ctx = _make_ctx()- ctx.call_mcp("slow", "long_op", timeout=120)- assert captured["timeout"] == 120.0def test_timeout_defaults_and_bounds(monkeypatch):diff --git a/tests/hermes_cli/test_plugin_capabilities.py b/tests/hermes_cli/test_plugin_capabilities.pyindex 2518b304fcc..33e7d0369ae 100644--- a/tests/hermes_cli/test_plugin_capabilities.py+++ b/tests/hermes_cli/test_plugin_capabilities.py@@ -15,7 +15,6 @@ import yamlfrom hermes_cli.plugin_capabilities import (CAPABILITY_REGISTRY,- VALID_CAPABILITY_IDS,capability_set_hash,consent_hash,declared_set_changed,@@ -48,18 +47,12 @@ class TestRegistry:assert spec.legacy_path, spec.idassert spec.description- def test_known_ids(self):- assert "tools.override" in VALID_CAPABILITY_IDS- assert "llm.model_override" in VALID_CAPABILITY_IDS# ── Declaration parsing ──────────────────────────────────────────────────────class TestDeclarationParsing:- def test_parses_known_ids(self):- got = parse_declared_capabilities(["tools.override", "llm.model_override"])- assert got == ["tools.override", "llm.model_override"]def test_drops_unknown_ids(self):got = parse_declared_capabilities(["tools.override", "root.everything"])@@ -175,9 +168,6 @@ class TestConsentPersistence:entry = _read_cfg(hermes_home)["plugins"]["entries"]["capplug"]assert entry["llm"]["allow_model_override"] is True- def test_granted_capabilities_roundtrip(self, hermes_home):- record_consent("capplug", ["tools.override"], ["tools.override"])- assert granted_capabilities("capplug") == frozenset({"tools.override"})def test_grant_is_union_with_previous(self, hermes_home):record_consent("capplug", ["tools.override"], ["tools.override"])@@ -190,9 +180,6 @@ class TestConsentPersistence:{"tools.override", "llm.model_override"})- def test_capability_granted_after_consent(self, hermes_home):- record_consent("capplug", ["tools.override"], ["tools.override"])- assert plugin_capability_granted("capplug", "tools.override") is Truedef test_declined_stays_off(self, hermes_home):# No record_consent call — nothing granted.diff --git a/tests/hermes_cli/test_plugin_cli_registration.py b/tests/hermes_cli/test_plugin_cli_registration.pyindex db0101eed2a..c3da8f93a9a 100644--- a/tests/hermes_cli/test_plugin_cli_registration.py+++ b/tests/hermes_cli/test_plugin_cli_registration.py@@ -1,57 +1,6 @@-"""Tests for plugin CLI registration system.--Covers:- - PluginContext.register_cli_command()- - PluginManager._cli_commands storage- - get_plugin_cli_commands() convenience function- - Memory plugin CLI discovery (discover_plugin_cli_commands)- - Honcho register_cli() builds correct argparse tree-"""+"""Memory plugin CLI discovery: only the active provider's ``cli.py`` commands are exposed."""import sys-from unittest.mock import MagicMock---from hermes_cli.plugins import (- PluginContext,- PluginManager,- PluginManifest,-)---# ── PluginContext.register_cli_command ─────────────────────────────────────---class TestRegisterCliCommand:- def _make_ctx(self):- mgr = PluginManager()- manifest = PluginManifest(name="test-plugin")- return PluginContext(manifest, mgr), mgr-- def test_registers_command(self):- ctx, mgr = self._make_ctx()- setup = MagicMock()- handler = MagicMock()- ctx.register_cli_command(- name="mycmd",- help="Do something",- setup_fn=setup,- handler_fn=handler,- description="Full description",- )- assert "mycmd" in mgr._cli_commands- entry = mgr._cli_commands["mycmd"]- assert entry["name"] == "mycmd"- assert entry["help"] == "Do something"- assert entry["setup_fn"] is setup- assert entry["handler_fn"] is handler- assert entry["plugin"] == "test-plugin"-- def test_overwrites_on_duplicate(self):- ctx, mgr = self._make_ctx()- ctx.register_cli_command("x", "first", MagicMock())- ctx.register_cli_command("x", "second", MagicMock())- assert mgr._cli_commands["x"]["help"] == "second"# ── Memory plugin CLI discovery ───────────────────────────────────────────@@ -123,22 +72,3 @@ class TestMemoryPluginCliDiscovery:monkeypatch.setattr(pm, "_MEMORY_PLUGINS_DIR", original_dir)assert len(cmds) == 0---# ── Honcho register_cli ──────────────────────────────────────────────────---# ── ProviderCollector no-op ──────────────────────────────────────────────---class TestProviderCollectorCliNoop:- def test_register_cli_command_is_noop(self):- """_ProviderCollector.register_cli_command is a no-op (doesn't crash)."""- from plugins.memory import _ProviderCollector-- collector = _ProviderCollector("test-provider")- collector.register_cli_command(- name="test", help="test", setup_fn=lambda s: None- )- # Should not store anything — CLI is discovered via file convention- assert not hasattr(collector, "_cli_commands")diff --git a/tests/hermes_cli/test_plugin_compat_notice.py b/tests/hermes_cli/test_plugin_compat_notice.pyindex f739e51154c..9fb0d3dc28f 100644--- a/tests/hermes_cli/test_plugin_compat_notice.py+++ b/tests/hermes_cli/test_plugin_compat_notice.py@@ -74,26 +74,6 @@ def test_disable_only_after_the_date_and_not_when_allowed(tmp_path, monkeypatch)assert pc.disable_reason(_manifest("good", good), today=after) is None-def test_summary_lines_name_plugins_and_the_date():- report = {"alpha": [pc.Hit("a.py", 1, "x.y", "z.y")], "beta": [pc.Hit("b.py", 2, "x.y", "z.y"), pc.Hit("b.py", 3, "x.q", "z.q")]}- before = pc.COMPAT_REMOVAL_DATE - dt.timedelta(days=3)- head, tail = pc.summary_lines(report, today=before)- assert "2 plugins" in head and "alpha (1)" in head and "beta (2)" in head and pc.COMPAT_REMOVAL in head and "3 days" in head- assert "hermes plugins compat" in tail- head_after, _ = pc.summary_lines(report, today=pc.COMPAT_REMOVAL_DATE)- assert "DISABLED" in head_after- assert pc.summary_lines({}) == []---def test_report_file_written_and_removed(tmp_path, monkeypatch):- monkeypatch.setattr(pc, "report_file_path", lambda: tmp_path / "r.json")- pc._write_report_file({"p": [pc.Hit("a.py", 1, "x.y", "z.y")]})- data = json.loads((tmp_path / "r.json").read_text())- assert data["plugins"]["p"][0]["old"] == "x.y" and data["removal_date"] == pc.COMPAT_REMOVAL and len(data["lines"]) == 2- pc._write_report_file({})- assert not (tmp_path / "r.json").exists()--def test_loader_skips_hitting_plugin_after_date(tmp_path, monkeypatch):"""PluginManager records the reason and never imports the plugin."""from hermes_cli.plugins import PluginManagerdiff --git a/tests/hermes_cli/test_plugin_dev.py b/tests/hermes_cli/test_plugin_dev.pyindex 094200ea1c0..472e0aaa642 100644--- a/tests/hermes_cli/test_plugin_dev.py+++ b/tests/hermes_cli/test_plugin_dev.py@@ -1,29 +1,7 @@from __future__ import annotations-import argparse--import pytestfrom pathlib import Path-from hermes_cli.subcommands.plugins import build_plugins_parser---def _parse_plugins_args(*argv: str):- parser = argparse.ArgumentParser()- subparsers = parser.add_subparsers(dest="command")- build_plugins_parser(subparsers, cmd_plugins=lambda args: None)- return parser.parse_args(["plugins", *argv])---def test_plugins_parser_exposes_doctor() -> None:- doctor = _parse_plugins_args("doctor", "sample", "--ci")-- assert (doctor.plugins_action, doctor.target, doctor.ci) == (- "doctor",- "sample",- True,- )-def test_doctor_uses_registration_to_reject_bad_hook_and_callback_signature(tmp_path: Path,@@ -138,20 +116,6 @@ def test_doctor_blocks_live_network(tmp_path: Path) -> None:assert "network access is disabled while Plugin Doctor runs" in report.format_text()-def test_resolve_rejects_directory_without_manifest(tmp_path: Path) -> None:- """A non-plugin directory must not resolve — Doctor copies what it resolves."""- from hermes_cli.plugin_dev import resolve_plugin_path-- not_a_plugin = tmp_path / "home"- (not_a_plugin / "Documents").mkdir(parents=True)- (not_a_plugin / "Documents" / "notes.txt").write_text("x", encoding="utf-8")-- with pytest.raises(FileNotFoundError) as excinfo:- resolve_plugin_path(not_a_plugin)-- assert "holds no plugin manifest" in str(excinfo.value)--def test_doctor_default_target_does_not_copy_cwd(tmp_path: Path, monkeypatch) -> None:@@ -226,7 +190,6 @@ def test_doctor_removes_temp_home_when_staging_copy_fails(import tempfile-from hermes_cli import plugin_devplugin = tmp_path / "sample"diff --git a/tests/hermes_cli/test_plugin_doctor_unload.py b/tests/hermes_cli/test_plugin_doctor_unload.pyindex b95c7f9b389..fc111e5fe89 100644--- a/tests/hermes_cli/test_plugin_doctor_unload.py+++ b/tests/hermes_cli/test_plugin_doctor_unload.py@@ -49,29 +49,3 @@ def test_doctor_runs_on_unload_during_teardown(tmp_path: Path) -> None:assert report.ok, report.format_text()assert marker.exists(), "ctx.on_unload must run before the temp home is removed"assert marker.read_text() == "unloaded"---def test_doctor_still_reports_and_cleans_up_for_unload_plugin(tmp_path: Path) -> None:- # The added unload must not disturb the existing teardown contract: registry- # entries restored, no hermes_plugins.* module leak.- import sys-- from hermes_cli.plugin_dev import doctor_plugin- from tools.registry import registry-- marker = tmp_path / "unloaded2.marker"- plugin = _write_plugin(tmp_path, marker)- before_modules = {- name for name in sys.modules- if name == "hermes_plugins" or name.startswith("hermes_plugins.")- }-- with patch.dict(os.environ, {"DOCTOR_UNLOAD_MARKER": str(marker)}, clear=False):- report = doctor_plugin(plugin)-- assert report.ok, report.format_text()- after_modules = {- name for name in sys.modules- if name == "hermes_plugins" or name.startswith("hermes_plugins.")- }- assert after_modules == before_modulesdiff --git a/tests/hermes_cli/test_plugin_event_bus.py b/tests/hermes_cli/test_plugin_event_bus.pyindex f02454bc1a4..a34617d8507 100644--- a/tests/hermes_cli/test_plugin_event_bus.py+++ b/tests/hermes_cli/test_plugin_event_bus.py@@ -70,12 +70,6 @@ def test_two_plugins_communicate():assert received == [{"n": 42}]-def test_emit_with_no_subscribers_returns_zero():- manager = _fresh_manager()- ctx_b = _make_ctx(manager, "plugin_b", key="b")- assert ctx_b.emit("ping", {"x": 1}) == 0--def test_emit_none_payload_delivers_empty_kwargs():manager = _fresh_manager()ctx_a = _make_ctx(manager, "plugin_a", key="a")@@ -110,8 +104,6 @@ def test_namespace_forced_to_emitter_key():# Delivered under the emitter's own key ("b"), never "a".assert delivered_events == ["b:ping"]- # Registry stores it under the forced full name.- assert "b:ping" in manager._subscriptionsdef test_namespace_falls_back_to_name_when_key_empty():@@ -162,18 +154,6 @@ def test_emit_rejects_empty_event():ctx_b.emit("")-def test_subscribe_is_unrestricted():- """Any plugin may subscribe to any event, including hermes: and foreign."""- manager = _fresh_manager()- ctx_a = _make_ctx(manager, "plugin_a", key="a")- got = []- # None of these raise — only emit is namespace-gated.- ctx_a.subscribe("hermes:core_event", lambda **p: got.append("hermes"))- ctx_a.subscribe("b:ping", lambda **p: got.append("b"))- assert "hermes:core_event" in manager._subscriptions- assert "b:ping" in manager._subscriptions--# ── 4. Per-callback isolation ────────────────────────────────────────────────@@ -376,23 +356,6 @@ def test_recursion_cap_terminates(caplog):# ── 6. Manifest emits/listens parsed as optional ─────────────────────────────-def test_manifest_emits_listens_default_empty():- m = PluginManifest(name="plain")- assert m.emits == []- assert m.listens == []---def test_manifest_emits_listens_present():- m = PluginManifest(- name="declar",- key="declar",- emits=["ping", "pong"],- listens=["other:ready"],- )- assert m.emits == ["ping", "pong"]- assert m.listens == ["other:ready"]--def test_manifest_parse_reads_emits_listens(tmp_path):"""parse_manifest_file picks up optional emits/listens from plugin.yaml."""import yaml@@ -419,24 +382,6 @@ def test_manifest_parse_reads_emits_listens(tmp_path):assert manifest.listens == ["other:evt"]-def test_manifest_parse_absent_emits_listens(tmp_path):- import yaml-- plugin_dir = tmp_path / "bare"- plugin_dir.mkdir()- manifest_file = plugin_dir / "plugin.yaml"- manifest_file.write_text(- yaml.safe_dump({"name": "bare"}), encoding="utf-8"- )-- from hermes_cli.plugins import parse_manifest_file-- manifest = parse_manifest_file(manifest_file, plugin_dir, "user", "")- assert manifest is not None- assert manifest.emits == []- assert manifest.listens == []--# ── 7. plugins show output includes emits/listens ────────────────────────────@@ -469,18 +414,15 @@ def test_plugins_show_includes_emits_listens(tmp_path, monkeypatch, capsys):out = capsys.readouterr().outassert "showplug" in out- assert "Emits:" in outassert "ping" in outassert "pong" in out- assert "Listens:" in outassert "other:ready" in out-def test_plugins_show_not_found_exits(monkeypatch, capsys):+def test_plugins_show_not_found_exits(monkeypatch):from hermes_cli import plugins_cmdmonkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: [])- with pytest.raises(SystemExit):+ with pytest.raises(SystemExit) as exc:plugins_cmd.cmd_show("nope")- out = capsys.readouterr().out- assert "not found" in out.lower()+ assert exc.value.code not in (0, None)diff --git a/tests/hermes_cli/test_plugin_install_ref.py b/tests/hermes_cli/test_plugin_install_ref.pyindex ece3d8ca2c0..2241959c696 100644--- a/tests/hermes_cli/test_plugin_install_ref.py+++ b/tests/hermes_cli/test_plugin_install_ref.py@@ -2,7 +2,6 @@from __future__ import annotations-import argparseimport jsonimport shutilimport subprocess@@ -11,8 +10,6 @@ from pathlib import Pathimport pytestimport yaml-from hermes_cli.subcommands.plugins import build_plugins_parser-def _git(repo: Path, *args: str) -> str:result = subprocess.run(@@ -46,16 +43,6 @@ def _metadata(home: Path) -> dict:return json.loads((home / "plugins" / ".install-metadata.json").read_text())-def test_parser_accepts_only_explicit_install_ref_option():- parser = argparse.ArgumentParser()- subparsers = parser.add_subparsers(dest="command")- build_plugins_parser(subparsers, cmd_plugins=lambda _args: None)-- args = parser.parse_args(["plugins", "install", "owner/repo", "--ref", "a" * 40])-- assert args.ref == "a" * 40--def test_canonical_source_never_persists_http_credentials():from hermes_cli.plugins_cmd import _canonical_sourcediff --git a/tests/hermes_cli/test_plugin_manifest_v2.py b/tests/hermes_cli/test_plugin_manifest_v2.pyindex df2d5e56679..ebf91fb3779 100644--- a/tests/hermes_cli/test_plugin_manifest_v2.py+++ b/tests/hermes_cli/test_plugin_manifest_v2.py@@ -54,22 +54,6 @@ def hermes_home(tmp_path, monkeypatch):class TestV1Regression:- def test_v1_manifest_parses_with_defaults(self, hermes_home):- _write_plugin(hermes_home / "plugins", "oldie")- _enable(hermes_home, ["oldie"])- mgr = PluginManager()- mgr.discover_and_load()- loaded = mgr._plugins["oldie"]- assert loaded.enabled- m = loaded.manifest- assert m.manifest_version == 1- assert m.api_version is None- assert m.requires_plugins == []- assert m.python_dependencies == []- assert m.config_schema == {}- assert m.license == ""- assert m.homepage == ""- assert m.tags == []def test_v1_unknown_fields_do_not_warn_loudly(self, hermes_home, caplog):_write_plugin(@@ -146,7 +130,7 @@ class TestV2Parsing:mgr = PluginManager()mgr.discover_and_load()assert mgr._plugins["fromfuture"].enabled- assert "newer than this Hermes" in caplog.text+ assert str(SUPPORTED_MANIFEST_VERSION + 5) in caplog.textdef test_malformed_v2_fields_warn_and_degrade(self, hermes_home, caplog):_write_plugin(@@ -366,7 +350,6 @@ class TestPythonDependenciesSeam:assert mgr._plugins["pipful"].enabledassert "definitely-not-a-real-package-64165" in caplog.textassert "pip install" in caplog.text- assert "hermes plugins enable pipful" in caplog.textassert calls == []def test_satisfied_pip_dep_is_quiet(self, hermes_home, caplog):@@ -500,12 +483,11 @@ class TestLoadIsolation:mgr.discover_and_load()assert mgr._plugins["c_after"].enabledassert not mgr._plugins["b_slow"].enabled- assert "load timed out after 0.3s" in (mgr._plugins["b_slow"].error or "")+ assert mgr._plugins["b_slow"].errorassert mgr._hooks.get("pre_tool_call", []) == [] # registered before the hang → disposedsys._deadline_gate.set() # release the abandoned worker; its late registration must bounceassert sys._deadline_done.wait(5)assert mgr._hooks.get("post_tool_call", []) == []- assert "called register_hook() after its load timed out; ignored" in caplog.textfinally:del sys._deadline_gate, sys._deadline_donediff --git a/tests/hermes_cli/test_plugin_message_injection.py b/tests/hermes_cli/test_plugin_message_injection.pyindex 209f6f3e6e3..a01ac4247e6 100644--- a/tests/hermes_cli/test_plugin_message_injection.py+++ b/tests/hermes_cli/test_plugin_message_injection.py@@ -164,27 +164,6 @@ def test_gateway_injection_passes_host_owned_plugin_identity(tmp_path, monkeypat)-def test_gateway_injection_returns_host_rejection(tmp_path, monkeypatch):- _write_plugin_config(- tmp_path,- monkeypatch,- {"allow_gateway_injection": True},- )- context, manager = _context()- manager.set_gateway_message_injector(- object(),- MagicMock(return_value=False),- )-- assert (- context.inject_message(- "wake up",- session_key="agent:main:telegram:dm:42",- )- is False- )--def test_gateway_injection_fails_closed_on_host_exception(tmp_path, monkeypatch):_write_plugin_config(tmp_path,diff --git a/tests/hermes_cli/test_plugin_packs.py b/tests/hermes_cli/test_plugin_packs.pyindex e1e5e06cb03..004c23db7f6 100644--- a/tests/hermes_cli/test_plugin_packs.py+++ b/tests/hermes_cli/test_plugin_packs.py@@ -6,9 +6,7 @@ No live network — index resolution and installs are mocked.from __future__ import annotations-import argparseimport json-from types import SimpleNamespacefrom unittest import mockimport pytest@@ -16,8 +14,6 @@ import yamlfrom hermes_cli.plugin_packs import (PackError,- PackPluginEntry,- PluginPack,ResolvedPackPlugin,_sanitized_entry_config as real_sanitized_entry_config,cmd_pack_install,@@ -28,7 +24,6 @@ from hermes_cli.plugin_packs import (resolve_pack_plugins,validate_config_seed,)-from hermes_cli.subcommands.plugins import build_plugins_parserSHA_A = "a" * 40SHA_B = "b" * 40@@ -184,11 +179,6 @@ def test_parse_pack_validates_config_section():assert ok.config["tts-plugin"] == {"voice": "nova"}-def test_parse_pack_collects_skills_as_declared_seam():- pack = parse_pack(_pack_yaml(skills=["hub/skill-a", "hub/skill-b"]))- assert pack.skills == ["hub/skill-a", "hub/skill-b"]--def test_load_pack_rejects_insecure_url_schemes(tmp_path):with pytest.raises(PackError) as exc:load_pack("http://example.com/pack.yaml")@@ -398,7 +388,6 @@ def test_pack_install_exits_nonzero_on_partial_failure(tmp_path, monkeypatch):with pytest.raises(SystemExit) as exc:cmd_pack_install(str(pack_file))assert exc.value.code == 1- assert "1 installed, 1 failed" in fake_console.textdef test_pack_install_refuses_noninteractive_sessions(tmp_path, monkeypatch):@@ -437,7 +426,6 @@ def test_pack_install_aborts_cleanly_on_decline(tmp_path, monkeypatch):with pytest.raises(SystemExit):cmd_pack_install(str(pack_file))installer.assert_not_called()- assert "Aborted" in fake_console.text# ---------------------------------------------------------------------------@@ -569,21 +557,3 @@ def test_export_enabled_only_filters(tmp_path, monkeypatch):# ---------------------------------------------------------------------------# Parser wiring# -----------------------------------------------------------------------------def test_parser_wires_pack_subcommands():- parser = argparse.ArgumentParser()- subparsers = parser.add_subparsers(dest="command")- build_plugins_parser(subparsers, cmd_plugins=lambda _args: None)-- args = parser.parse_args(["plugins", "pack", "install", "pack.yaml", "--force"])- assert args.plugins_action == "pack"- assert args.pack_action == "install"- assert args.source == "pack.yaml"- assert args.force is True-- args = parser.parse_args(["plugins", "pack", "export", "--enabled-only"])- assert args.pack_action == "export"- assert args.enabled_only is True-- args = parser.parse_args(["plugins", "pack", "show", "https://x/p.yaml"])- assert args.pack_action == "show"diff --git a/tests/hermes_cli/test_plugin_provider_picker_residue.py b/tests/hermes_cli/test_plugin_provider_picker_residue.pyindex 24593903fa0..7a4063e193b 100644--- a/tests/hermes_cli/test_plugin_provider_picker_residue.py+++ b/tests/hermes_cli/test_plugin_provider_picker_residue.py@@ -114,9 +114,6 @@ def test_oauth_plugin_status_follows_the_credential_pool(plugin):# the live entry still wins for example-oauthassert auth.get_auth_status("example-oauth")["logged_in"] is True- assert auth._STATUS_BY_AUTH_TYPE["oauth_external"] == auth._STATUS_BY_AUTH_TYPE["oauth_device_code"]- for builtin in ("nous", "openai-codex"):- assert builtin in auth._BESPOKE_STATUS_FUNCTIONS # bespoke status wins; plugin builder never consultedassert auth.get_plugin_oauth_auth_status("openai-codex") == {"logged_in": False}diff --git a/tests/hermes_cli/test_plugin_runtime_disable_gate.py b/tests/hermes_cli/test_plugin_runtime_disable_gate.pyindex 7ce807d580e..c1e9dc79340 100644--- a/tests/hermes_cli/test_plugin_runtime_disable_gate.py+++ b/tests/hermes_cli/test_plugin_runtime_disable_gate.py@@ -14,7 +14,6 @@ Covers two residual bypasses addressed in the PR:from __future__ import annotationsimport json-from pathlib import Pathfrom unittest.mock import patch, AsyncMockimport pytest@@ -53,21 +52,6 @@ def test_client(monkeypatch, tmp_path):# Helpers# ----------------------------------------------------------------------------def _make_user_plugin(tmp_path, name="hot"):- """Create a minimal user plugin with a JS asset."""- dashboard_dir = tmp_path / "plugins" / name / "dashboard"- dashboard_dir.mkdir(parents=True)- dist_dir = dashboard_dir / "dist"- dist_dir.mkdir()- (dist_dir / "index.js").write_text("console.log('hello');")- (dashboard_dir / "manifest.json").write_text(json.dumps({- "name": name,- "label": name.title(),- "entry": "dist/index.js",- }))- return dashboard_dir--def _make_bundled_plugin(tmp_path, name="bundledx"):"""Create a minimal bundled plugin with a JS asset."""dashboard_dir = tmp_path / "bundled" / name / "dashboard"@@ -223,24 +207,4 @@ class TestBundledPluginAssetGate:"Disabled bundled plugin asset must return 404")- def test_bundled_asset_served_when_not_disabled(self, test_client, tmp_path, monkeypatch):- """Bundled plugin assets are served normally when not in disabled set."""- plugin_dir = _make_bundled_plugin(tmp_path, "goodbundled")-- fake_plugin = {- "name": "goodbundled",- "label": "Good Bundled",- "source": "bundled",- "entry": "dist/index.js",- "_dir": str(plugin_dir),- }-- with patch.object(web_server, "_get_dashboard_plugins", return_value=[fake_plugin]):- with patch(- "hermes_cli.plugins_cmd._get_enabled_set", return_value=set()- ), patch(- "hermes_cli.plugins_cmd._get_disabled_set", return_value=set()- ):- resp = test_client.get("/dashboard-plugins/goodbundled/dist/index.js")- assert resp.status_code == 200diff --git a/tests/hermes_cli/test_plugin_scanner_recursion.py b/tests/hermes_cli/test_plugin_scanner_recursion.pyindex 8ac876f43d2..046fa3d7e1d 100644--- a/tests/hermes_cli/test_plugin_scanner_recursion.py+++ b/tests/hermes_cli/test_plugin_scanner_recursion.py@@ -12,7 +12,6 @@ import jsonfrom pathlib import Pathfrom typing import Any, Dict-import pytestimport yamlfrom hermes_cli.plugins import PluginManager@@ -182,40 +181,10 @@ class TestForeignHarnessManifestDirs:)-# ── Kind parsing ───────────────────────────────────────────────────────────class TestKindField:- def test_default_kind_is_standalone(self, tmp_path, monkeypatch):- import os- hermes_home = Path(os.environ["HERMES_HOME"]) # set by hermetic conftest fixture- _write_plugin(hermes_home / "plugins", ["p1"])- _enable(hermes_home, "p1")-- mgr = PluginManager()- mgr.discover_and_load()-- assert mgr._plugins["p1"].manifest.kind == "standalone"-- @pytest.mark.parametrize("kind", ["backend", "exclusive", "standalone"])- def test_valid_kinds_parsed(self, kind, tmp_path, monkeypatch):- import os- hermes_home = Path(os.environ["HERMES_HOME"]) # set by hermetic conftest fixture- _write_plugin(- hermes_home / "plugins",- ["p1"],- manifest_extra={"kind": kind},- )- # Not all kinds auto-load, but manifest should parse.- _enable(hermes_home, "p1")-- mgr = PluginManager()- mgr.discover_and_load()-- assert "p1" in mgr._plugins- assert mgr._plugins["p1"].manifest.kind == kind-def test_unknown_kind_falls_back_to_standalone(self, tmp_path, monkeypatch, caplog):import oshermes_home = Path(os.environ["HERMES_HOME"]) # set by hermetic conftest fixture@@ -289,9 +258,6 @@ class TestBundledBackendAutoLoad:def test_bundled_image_gen_openai_autoloads(self, tmp_path, monkeypatch):"""The bundled ``plugins/image_gen/openai/`` plugin loads withoutany opt-in — it's ``kind: backend`` and shipped in-repo."""- import os- hermes_home = Path(os.environ["HERMES_HOME"]) # set by hermetic conftest fixture-mgr = PluginManager()mgr.discover_and_load()@@ -322,7 +288,7 @@ class TestRegisterImageGenProvider:import oshermes_home = Path(os.environ["HERMES_HOME"]) # set by hermetic conftest fixture- plugin_dir = _write_plugin(+ _write_plugin(hermes_home / "plugins",["my-img-plugin"],register_body=(@@ -344,28 +310,3 @@ class TestRegisterImageGenProvider:assert image_gen_registry.get_provider("fake-ctx") is not Noneimage_gen_registry._reset_for_tests()-- def test_rejects_non_provider(self, tmp_path, monkeypatch, caplog):- from agent import image_gen_registry-- image_gen_registry._reset_for_tests()-- import os- hermes_home = Path(os.environ["HERMES_HOME"]) # set by hermetic conftest fixture- _write_plugin(- hermes_home / "plugins",- ["bad-img-plugin"],- register_body="ctx.register_image_gen_provider('not a provider')",- )- _enable(hermes_home, "bad-img-plugin")-- with caplog.at_level("WARNING"):- mgr = PluginManager()- mgr.discover_and_load()-- # Plugin loaded (register returned normally) but nothing was- # registered in the provider registry.- assert mgr._plugins["bad-img-plugin"].enabled is True- assert image_gen_registry.get_provider("not a provider") is None-- image_gen_registry._reset_for_tests()diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.pyindex 9bfac96ae1c..ecfd09db4ce 100644--- a/tests/hermes_cli/test_plugin_validate.py+++ b/tests/hermes_cli/test_plugin_validate.py@@ -84,7 +84,7 @@ def test_requires_hermes_spec_is_validated(tmp_path):report = validate_plugin_dir(d)assert report.ok, report.failures- assert ("requires_hermes", True, "spec '>=0.21' parses") in report.checks+ assert any(name == "requires_hermes" and ok for name, ok, _ in report.checks)def test_admission_runs_the_install_scanner(tmp_path):@@ -264,7 +264,7 @@ class TestDesktopSurface:"export default definePlugin({ id: 'desk', register(ctx) { ctx.storage.set('k', 1) } })\n"))report = validate_plugin_dir(d)- assert ("desktop surface", True, "stays inside the plugin SDK surface") in report.checks+ assert any(name == "desktop surface" and ok for name, ok, _ in report.checks)def test_script_regex_literal_is_not_injection_but_string_is(self, tmp_path):d = self._desktop_plugin(tmp_path, (diff --git a/tests/hermes_cli/test_plugins.py b/tests/hermes_cli/test_plugins.pyindex a78526ae5dc..b2fb578b268 100644--- a/tests/hermes_cli/test_plugins.py+++ b/tests/hermes_cli/test_plugins.py@@ -13,13 +13,10 @@ import yamlfrom hermes_cli.plugins import (ENTRY_POINTS_GROUP,- VALID_HOOKS,PluginContext,PluginManager,PluginManifest,_dispatch_pre_tool_call_hooks,- get_plugin_command_handler,- get_plugin_commands,get_pre_tool_call_block_message,get_pre_verify_continue_message,has_middleware,@@ -28,7 +25,6 @@ from hermes_cli.plugins import ()from hermes_cli.relay_plugin_cutover import RELAY_PLUGINS_CONFIG_ENVfrom hermes_cli.middleware import (- VALID_MIDDLEWARE,apply_llm_request_middleware,apply_tool_request_middleware,run_llm_execution_middleware,@@ -156,9 +152,7 @@ class TestPluginDiscovery:assert loaded == []assert not state.enabledassert state.error is not None- assert "Relay lifecycle is owned by Hermes core" in state.errorassert RELAY_PLUGINS_CONFIG_ENV in state.error- assert "Refusing to load removed Hermes Relay plugin" in caplog.textdef test_enabled_portable_plugin_registers_components(self, tmp_path, monkeypatch@@ -305,7 +299,6 @@ class TestPluginDiscovery:self, tmp_path, monkeypatch):from hermes_cli.agent_plugins import PLUGIN_SCHEMA_V1- from hermes_cli import plugins as plugins_modhome = tmp_path / "home"plugin = home / "plugins" / "portable"@@ -373,8 +366,6 @@ class TestPluginDiscovery:mgr = PluginManager()mgr.discover_and_load()- assert "llm_request" in VALID_MIDDLEWARE- assert "tool_request" in VALID_MIDDLEWAREassert set(mgr._plugins["mw_plugin"].middleware_registered) == {"llm_request", "tool_request"}assert mgr.invoke_middleware("llm_request", request={"messages": []}) == [{"request": {"messages": [], "mw": True}}@@ -407,13 +398,6 @@ class TestPluginDiscovery:assert has_middleware("tool_request") is False-------def test_failed_discovery_is_not_cached(self, tmp_path, monkeypatch):"""A sweep that raises must not cache 'discovered' with no plugins.@@ -449,7 +433,6 @@ class TestPluginDiscovery:assert len(non_bundled) == 1-def test_entry_point_function_form_registers(self, tmp_path, monkeypatch):"""Entry points declared as ``module:function`` register via the callable.@@ -550,21 +533,6 @@ class TestPluginLoading:"""Tests for plugin module loading."""-- def test_load_registers_namespace_module(self, tmp_path, monkeypatch):- """Directory plugins are importable under hermes_plugins.<name>."""- plugins_dir = tmp_path / "hermes_test" / "plugins"- _make_plugin_dir(plugins_dir, "ns_plugin")- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_test"))-- # Clean up any prior namespace module- sys.modules.pop("hermes_plugins.ns_plugin", None)-- mgr = PluginManager()- mgr.discover_and_load()-- assert "hermes_plugins.ns_plugin" in sys.modules-def test_user_memory_plugin_auto_coerced_to_exclusive(self, tmp_path, monkeypatch):"""User-installed memory plugins must NOT be loaded by the generalPluginManager — they belong to plugins/memory discovery.@@ -927,7 +895,6 @@ class TestPluginHooks:"""Tests for lifecycle hook registration and invocation."""-def test_pre_gateway_dispatch_collects_action_dicts(self, tmp_path, monkeypatch):"""pre_gateway_dispatch callbacks return action dicts (skip/rewrite/allow)."""plugins_dir = tmp_path / "hermes_test" / "plugins"@@ -953,9 +920,6 @@ class TestPluginHooks:assert results[0] == {"action": "skip", "reason": "test"}---def test_request_hooks_are_invokeable(self, tmp_path, monkeypatch):plugins_dir = tmp_path / "hermes_test" / "plugins"_make_plugin_dir(@@ -988,7 +952,6 @@ class TestPluginHooks:assert results == [{"seen": 2, "mc": 5, "tc": 3}]-class TestDeliveryParity:"""Hook/middleware delivery parity across surfaces (#64178).@@ -1062,16 +1025,6 @@ class TestDeliveryParity:assert plugins_mod.has_middleware("tool_request") is Trueassert mgr._discovered is True- def test_invoke_hook_tolerates_mock_managers(self, monkeypatch):- """Test doubles without _discovered are invoked untouched."""- import types-- import hermes_cli.plugins as plugins_mod-- stub = types.SimpleNamespace(invoke_hook=lambda name, **kw: ["stubbed"])- monkeypatch.setattr(plugins_mod, "get_plugin_manager", lambda: stub)-- assert plugins_mod.invoke_hook("anything") == ["stubbed"]def test_execution_chain_lazily_discovers(self, monkeypatch):"""Execution middleware must fire on cold surfaces too (#105827).@@ -1164,26 +1117,6 @@ class TestForceReloadSymmetry:shell_hooks_mod.reset_for_tests()- def test_force_reload_re_registers_shell_hooks(self, monkeypatch):- """config.yaml shell hooks are re-wired after force=True (#60036)."""- calls = []- import agent.shell_hooks as shell_hooks_mod-- monkeypatch.setattr(- shell_hooks_mod,- "re_register_config_hooks",- lambda: calls.append(True),- )- monkeypatch.setattr(- PluginManager, "_discover_and_load_inner", lambda self_inner: None- )-- mgr = PluginManager()- mgr.discover_and_load()- assert calls == [], "initial discovery must not re-register shell hooks"-- mgr.discover_and_load(force=True)- assert calls == [True]def test_shell_hook_re_register_failure_does_not_abort_reload(self, monkeypatch):import agent.shell_hooks as shell_hooks_mod@@ -1221,28 +1154,6 @@ class TestForceReloadSymmetry:assert not mgr._plugin_tool_namesassert mgr._discovered is False- def test_re_register_config_hooks_clears_idempotence_set(self, monkeypatch):- import agent.shell_hooks as shell_hooks_mod- from hermes_constants import get_hermes_home-- recorded = {}- monkeypatch.setattr(- shell_hooks_mod,- "register_from_config",- lambda cfg: recorded.setdefault("cfg", cfg) or [],- )- monkeypatch.setattr(- "hermes_cli.config.load_config", lambda: {"hooks": {}}- )- home_key = str(get_hermes_home().expanduser().resolve())- with shell_hooks_mod._registered_lock:- shell_hooks_mod._registered.add((home_key, "post_llm_call", None, "echo hi"))-- shell_hooks_mod.re_register_config_hooks()-- with shell_hooks_mod._registered_lock:- assert not shell_hooks_mod._registered- assert recorded["cfg"] == {"hooks": {}}def test_hook_timeout_does_not_block_caller(self, monkeypatch):"""A hung callback must be abandoned without joining the worker.@@ -1284,15 +1195,6 @@ class TestForceReloadSymmetry:assert elapsed < 5.0, f"caller blocked for {elapsed:.2f}s after timeout"hold.set()- def test_hook_callback_within_timeout_returns_value(self, monkeypatch):- monkeypatch.setattr(- "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 1.0- )- mgr = PluginManager()- mgr._hooks["pre_llm_call"] = [lambda **_kw: {"context": "hi"}]- assert mgr.invoke_hook("pre_llm_call", session_id="s1") == [- {"context": "hi"}- ]def test_hook_exception_still_isolated_under_timeout_path(self, monkeypatch):monkeypatch.setattr(@@ -1493,16 +1395,17 @@ class TestForceReloadSymmetry:def test_repeated_same_call_identity_still_deduplicated(self, monkeypatch):"""Negative control: the same call identity stays a duplicate while its workeris still running, so the running gate (not timeout suppression) dedupes it."""- import timemonkeypatch.setattr("hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 5.0)hold = threading.Event()+ started = threading.Event()starts = []def blocker(**_kwargs):starts.append(1)+ started.set()hold.wait(timeout=10.0)return "late"@@ -1514,7 +1417,7 @@ class TestForceReloadSymmetry:first = threading.Thread(target=fire, daemon=True)first.start()- time.sleep(0.1) # the first worker now holds the gate for this call identity+ assert started.wait(5.0) # the first worker now holds the gate for this call identitysecond = threading.Thread(target=fire, daemon=True)second.start()second.join(5.0)@@ -1745,7 +1648,7 @@ class TestForceReloadSymmetry:assert _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE in resulthold.set()- def test_force_reload_of_one_profile_does_not_orphan_another(self, monkeypatch):+ def test_force_reload_of_one_profile_does_not_orphan_another(self, monkeypatch, tmp_path):"""Real two-manager regression: force-reloading profile A's pluginmanager must leave profile B's shell hook registered exactly once —not duplicated, not dropped (#92682 review).@@ -1760,12 +1663,12 @@ class TestForceReloadSymmetry:PluginManager, "_discover_and_load_inner", lambda self_inner: None,)- monkeypatch.setenv("HERMES_HOME", "/tmp/profile-a")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profile-a"))mgr_a = PluginManager()plugins_mod._plugin_manager = mgr_ashell_hooks_mod.register_from_config(cfg, accept_hooks=True)- monkeypatch.setenv("HERMES_HOME", "/tmp/profile-b")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profile-b"))mgr_b = PluginManager()plugins_mod._plugin_manager = mgr_bshell_hooks_mod.register_from_config(cfg, accept_hooks=True)@@ -1783,7 +1686,7 @@ class TestForceReloadSymmetry:# B's later adapter reconnect re-runs register_from_config(); its# idempotence key must still be intact, so this must be a no-op# rather than appending a second callback to B's live manager.- monkeypatch.setenv("HERMES_HOME", "/tmp/profile-b")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profile-b"))second = shell_hooks_mod.register_from_config(cfg, accept_hooks=True)assert second == []@@ -1826,21 +1729,9 @@ class TestPreToolCallDirective:session_id="session-1",tool_call_id="call-1",) == (None, None)- assert observed == [- (- "pre_tool_call",- {- "tool_name": "write_file",- "args": {"path": "README.md"},- "task_id": "task-1",- "session_id": "session-1",- "tool_call_id": "call-1",- "turn_id": "",- "api_request_id": "",- "middleware_trace": [],- },- )- ]+ [(hook_name, payload)] = observed+ assert hook_name == "pre_tool_call"+ assert (payload["tool_name"], payload["args"], payload["tool_call_id"]) == ("write_file", {"path": "README.md"}, "call-1")def test_approve_directive_returned(self, monkeypatch):from hermes_cli.plugins import get_pre_tool_call_directive@@ -1905,7 +1796,6 @@ class TestResolvePreToolBlock:def test_approve_gate_receives_tool_observability_context(self, monkeypatch):from hermes_cli.plugins import resolve_pre_tool_block- from tools import approvalfrom tools import approval_contextseen = {}@@ -2192,8 +2082,6 @@ class TestPluginContext:"""Tests for the PluginContext facade."""--def test_register_tool_override_blocked_without_operator_opt_in(self, tmp_path, monkeypatch):"""override=True must be rejected when the operator hasn't opted in.@@ -2398,10 +2286,6 @@ class TestPluginToolVisibility:class TestPluginManagerList:"""Tests for PluginManager.list_plugins()."""- def test_list_empty(self):- """Empty manager returns empty list."""- mgr = PluginManager()- assert mgr.list_plugins() == []def test_list_returns_sorted(self, tmp_path, monkeypatch):"""list_plugins() returns results sorted by key."""@@ -2451,88 +2335,6 @@ class TestPluginManagerList:)-class TestPreLlmCallTargetRouting:- """Tests for pre_llm_call hook return format with target-aware routing.-- The routing logic lives in run_agent.py, but the return format is collected- by invoke_hook(). These tests verify the return format works correctly and- that downstream code can route based on the 'target' key.- """-- def _make_pre_llm_plugin(self, plugins_dir, name, return_expr):- """Create a plugin that returns a specific value from pre_llm_call."""- _make_plugin_dir(- plugins_dir, name,- register_body=(- f'ctx.register_hook("pre_llm_call", lambda **kw: {return_expr})'- ),- )-- def test_context_dict_returned(self, tmp_path, monkeypatch):- """Plugin returning a context dict is collected by invoke_hook."""- plugins_dir = tmp_path / "hermes_test" / "plugins"- self._make_pre_llm_plugin(- plugins_dir, "basic_plugin",- '{"context": "basic context"}',- )- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_test"))-- mgr = PluginManager()- mgr.discover_and_load()-- results = mgr.invoke_hook(- "pre_llm_call", session_id="s1", user_message="hi",- conversation_history=[], is_first_turn=True, model="test",- )- assert len(results) == 1- assert results[0]["context"] == "basic context"- assert "target" not in results[0]--- def test_routing_logic_all_to_user_message(self, tmp_path, monkeypatch):- """Simulate the routing logic from run_agent.py.-- All plugin context — dicts and plain strings — ends up in a single- user message context string. There is no system_prompt target.- """- plugins_dir = tmp_path / "hermes_test" / "plugins"- self._make_pre_llm_plugin(- plugins_dir, "aaa_mem",- '{"context": "memory A"}',- )- self._make_pre_llm_plugin(- plugins_dir, "bbb_guard",- '{"context": "rule B"}',- )- self._make_pre_llm_plugin(- plugins_dir, "ccc_plain",- '"plain text C"',- )- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_test"))-- mgr = PluginManager()- mgr.discover_and_load()-- results = mgr.invoke_hook(- "pre_llm_call", session_id="s1", user_message="hi",- conversation_history=[], is_first_turn=True, model="test",- )-- # Replicate run_agent.py routing logic — everything goes to user msg- _ctx_parts = []- for r in results:- if isinstance(r, dict) and r.get("context"):- _ctx_parts.append(str(r["context"]))- elif isinstance(r, str) and r.strip():- _ctx_parts.append(r)-- assert _ctx_parts == ["memory A", "rule B", "plain text C"]- _plugin_user_context = "\n\n".join(_ctx_parts)- assert "memory A" in _plugin_user_context- assert "rule B" in _plugin_user_context- assert "plain text C" in _plugin_user_context--# ── TestPluginCommands ────────────────────────────────────────────────────@@ -2540,7 +2342,6 @@ class TestPluginCommands:"""Tests for plugin slash command registration via register_command()."""-def test_register_command_empty_name_rejected(self, caplog):"""Empty name after normalization is rejected with a warning."""mgr = PluginManager()@@ -2550,7 +2351,6 @@ class TestPluginCommands:with caplog.at_level(logging.WARNING, logger="hermes_cli.plugins"):ctx.register_command("", lambda a: a)assert len(mgr._plugin_commands) == 0- assert "empty name" in caplog.textdef test_register_command_infers_text_argument_mode_from_args_hint(self):mgr = PluginManager()@@ -2564,8 +2364,6 @@ class TestPluginCommands:assert mgr._plugin_commands["ping"]["argument_mode"] is None--def test_get_plugin_context_engine_discovers_plugins_lazily(self, tmp_path, monkeypatch):"""Context engine lookup should work before any explicit discover_plugins() call."""hermes_home = tmp_path / "hermes_test"@@ -2768,10 +2566,6 @@ class TestPluginCommands:assert manager_a is not manager_b----class TestPluginCommandResultResolution:@@ -2809,22 +2603,6 @@ class TestPluginCommandResultResolution:class TestPluginDispatchTool:"""Tests for PluginContext.dispatch_tool() — tool dispatch with agent context."""- def test_dispatch_tool_calls_registry(self):- """dispatch_tool() delegates to registry.dispatch()."""- mgr = PluginManager()- manifest = PluginManifest(name="test-plugin", source="user")- ctx = PluginContext(manifest, mgr)-- mock_registry = MagicMock()- mock_registry.dispatch.return_value = '{"result": "ok"}'-- with patch("hermes_cli.plugins.PluginContext.dispatch_tool.__module__", "hermes_cli.plugins"):- with patch.dict("sys.modules", {}):- with patch("tools.registry.registry", mock_registry):- result = ctx.dispatch_tool("web_search", {"query": "test"})-- assert result == '{"result": "ok"}'-def test_dispatch_tool_respects_explicit_parent_agent(self):"""Explicit parent_agent kwarg is not overwritten by _cli_ref.agent."""@@ -2849,31 +2627,6 @@ class TestPluginDispatchTool:assert call_kwargs[1]["parent_agent"] is explicit_agent-class TestPluginDebugLogging:- """HERMES_PLUGINS_DEBUG opt-in stderr handler for plugin developers."""-- def test_debug_handler_not_installed_when_env_var_absent(self, monkeypatch):- """Without the env var, no stderr handler is attached."""- monkeypatch.delenv("HERMES_PLUGINS_DEBUG", raising=False)- from hermes_cli import plugins as plugins_mod-- # Snapshot, then force a re-evaluation.- original_installed = plugins_mod._DEBUG_HANDLER_INSTALLED- original_debug = plugins_mod._PLUGINS_DEBUG- original_handlers = list(plugins_mod.logger.handlers)- try:- plugins_mod._DEBUG_HANDLER_INSTALLED = False- plugins_mod._install_plugin_debug_handler(force=True)- assert plugins_mod._PLUGINS_DEBUG is False- assert plugins_mod._DEBUG_HANDLER_INSTALLED is False- # No new stderr handler was attached.- assert plugins_mod.logger.handlers == original_handlers- finally:- plugins_mod._DEBUG_HANDLER_INSTALLED = original_installed- plugins_mod._PLUGINS_DEBUG = original_debug- plugins_mod.logger.handlers = original_handlers--class TestPluginContextProfileName:"""ctx.profile_name resolves from HERMES_HOME in every context."""diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.pyindex 1c3bce1bb31..6d96be902c4 100644--- a/tests/hermes_cli/test_plugins_cmd.py+++ b/tests/hermes_cli/test_plugins_cmd.py@@ -18,7 +18,6 @@ from hermes_cli.plugins_cmd import (_read_manifest,_refuse_unavailable_portable_plugin,_repo_name_from_url,- _resolve_git_executable,_resolve_git_url,_resolve_subdir_within,_sanitize_plugin_name,@@ -147,72 +146,6 @@ class TestResolveSubdirWithin:# ── _resolve_git_executable ─────────────────────────────────────────────────-class TestResolveGitExecutable:- """Fallback resolution when bare ``git`` is not discoverable via ``PATH``."""-- def teardown_method(self):- _resolve_git_executable.cache_clear()-- def test_prefers_shutil_which(self):- import hermes_cli.plugins_cmd as pc-- _resolve_git_executable.cache_clear()- with patch.object(pc.shutil, "which", return_value="/usr/local/bin/git"):- assert pc._resolve_git_executable() == "/usr/local/bin/git"-- def test_fallback_posix_first_matching_path(self):- import hermes_cli.plugins_cmd as pc-- _resolve_git_executable.cache_clear()-- def _isfile(p: str) -> bool:- return p == "/usr/local/bin/git"-- with patch.object(pc.shutil, "which", return_value=None):- with patch.object(pc.os, "name", "posix"):- with patch.object(pc.os.path, "isfile", side_effect=_isfile):- assert pc._resolve_git_executable() == "/usr/local/bin/git"--- def test_git_pull_uses_resolved_executable(self, tmp_path):- import hermes_cli.plugins_cmd as pc-- _resolve_git_executable.cache_clear()- with patch.object(- pc,- "_resolve_git_executable",- return_value="/resolved/git",- ):- with patch.object(pc.subprocess, "run") as run:- # `git status --porcelain` (clean tree), `remote get-url origin`, then the pull.- run.side_effect = [- MagicMock(returncode=0, stdout="", stderr=""),- MagicMock(returncode=0, stdout="[email protected]:x.git\n", stderr=""),- MagicMock(returncode=0, stdout="Already up to date\n", stderr=""),- ]- ok, msg = pc._git_pull_plugin_dir(tmp_path)- assert ok is True- assert run.call_count == 3- for call in run.call_args_list:- assert call.args[0][0] == "/resolved/git"- assert run.call_args_list[2].args[0][1:] == ["pull", "--ff-only"]-- def test_git_pull_clean_tree_never_stashes(self, tmp_path):- import hermes_cli.plugins_cmd as pc-- _resolve_git_executable.cache_clear()- with patch.object(pc, "_resolve_git_executable", return_value="/g"):- with patch.object(pc.subprocess, "run") as run:- run.side_effect = [- MagicMock(returncode=0, stdout="", stderr=""), # status- MagicMock(returncode=0, stdout="[email protected]:x.git\n", stderr=""), # remote get-url- MagicMock(returncode=0, stdout="Updated\n", stderr=""), # pull- ]- ok, msg = pc._git_pull_plugin_dir(tmp_path)- assert ok is True- assert msg == "Updated"- commands = [c.args[0][1] for c in run.call_args_list]- assert "stash" not in commandsclass TestGitPullPluginDirAutostash:@@ -457,30 +390,6 @@ class TestCmdInstall:class TestCmdUpdate:"""Test the update command."""- @patch("hermes_cli.plugins_cmd._sanitize_plugin_name")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd.subprocess.run")- def test_update_git_pull_success(self, mock_run, mock_plugins_dir, mock_sanitize):- from hermes_cli.plugins_cmd import cmd_update-- mock_plugins_dir_val = MagicMock()- mock_plugins_dir.return_value = mock_plugins_dir_val- mock_target = MagicMock()- mock_target.exists.return_value = True- mock_target.__truediv__ = lambda self, x: MagicMock(- exists=MagicMock(return_value=True)- )- mock_sanitize.return_value = mock_target-- mock_run.side_effect = [- MagicMock(returncode=0, stdout="", stderr=""), # status: clean- MagicMock(returncode=0, stdout="[email protected]:x.git", stderr=""), # remote get-url- MagicMock(returncode=0, stdout="Updated", stderr=""), # pull- ]-- cmd_update("test-plugin")-- assert mock_run.call_count == 3@patch("hermes_cli.plugins_cmd._sanitize_plugin_name")@patch("hermes_cli.plugins_cmd._plugins_dir")@@ -506,22 +415,6 @@ class TestCmdUpdate:class TestCmdRemove:"""Test the remove command."""- @patch("hermes_cli.plugins_cmd._sanitize_plugin_name")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd.rmtree_readonly")- def test_remove_deletes_plugin(self, mock_rmtree, mock_plugins_dir, mock_sanitize):- from hermes_cli.plugins_cmd import cmd_remove-- mock_plugins_dir.return_value = MagicMock()- # ``plugins_dir / name`` is a real directory here, not a symlink (the link case unlinks only).- mock_plugins_dir.return_value.__truediv__.return_value.is_symlink.return_value = False- mock_target = MagicMock()- mock_target.exists.return_value = True- mock_sanitize.return_value = mock_target-- cmd_remove("test-plugin")-- mock_rmtree.assert_called_once_with(mock_target)@patch("hermes_cli.plugins_cmd._sanitize_plugin_name")@patch("hermes_cli.plugins_cmd._plugins_dir")@@ -560,36 +453,6 @@ class TestCmdRemove:# ── cmd_list tests ─────────────────────────────────────────────────────────-class TestCmdList:- """Test the list command."""-- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_list_empty_plugins_dir(self, mock_plugins_dir):- from hermes_cli.plugins_cmd import cmd_list-- mock_plugins_dir_val = MagicMock()- mock_plugins_dir_val.iterdir.return_value = []- mock_plugins_dir.return_value = mock_plugins_dir_val-- cmd_list()-- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._read_manifest")- def test_list_with_plugins(self, mock_read_manifest, mock_plugins_dir):- from hermes_cli.plugins_cmd import cmd_list-- mock_plugins_dir_val = MagicMock()- mock_plugin_dir = MagicMock()- mock_plugin_dir.name = "test-plugin"- mock_plugin_dir.is_dir.return_value = True- mock_plugin_dir.__truediv__ = lambda self, x: MagicMock(- exists=MagicMock(return_value=False)- )- mock_plugins_dir_val.iterdir.return_value = [mock_plugin_dir]- mock_plugins_dir.return_value = mock_plugins_dir_val- mock_read_manifest.return_value = {"name": "test-plugin", "version": "1.0.0"}-- cmd_list()# ── _copy_example_files tests ─────────────────────────────────────────────────@@ -733,19 +596,6 @@ class TestProviderDiscovery:# ── Auto-activation fix ──────────────────────────────────────────────────-class TestNoAutoActivation:- """Verify that plugin engines don't auto-activate when config says 'compressor'."""-- def test_compressor_default_ignores_plugin(self):- """When context.engine is 'compressor', a plugin-registered engine should NOT- be used — only explicit config triggers plugin engines."""- # This tests the run_agent.py logic indirectly by checking that the- # code path for default config doesn't call get_plugin_context_engine.- import run_agent as ra_module- source = Path(ra_module.__file__).read_text(encoding="utf-8")- # The old code had: "Even with default config, check if a plugin registered one"- # The fix removes this. Verify it's gone.- assert "Even with default config, check if a plugin registered one" not in source# ── End-to-end subdirectory install ──────────────────────────────────────────diff --git a/tests/hermes_cli/test_plugins_cmd_catalog.py b/tests/hermes_cli/test_plugins_cmd_catalog.pyindex 3c860627d0c..2f4a5f45eb1 100644--- a/tests/hermes_cli/test_plugins_cmd_catalog.py+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py@@ -64,14 +64,16 @@ def _head(path: Path) -> str:return sp.run(["git", "rev-parse", "HEAD"], cwd=path, capture_output=True, text=True).stdout.strip()-def test_catalog_platform_mismatch_refuses_before_install(world, monkeypatch):+def test_catalog_platform_mismatch_refuses_before_install(world):+ from hermes_platform.host.facts import os_family+ host = os_family()+ other = "linux" if host == "windows" else "windows"entry = pc_cat.PluginCatalogEntry(name="cat-plugin", repo=world["repo"].as_uri(), sha=world["sha1"],- description="d", maintainer="t", platforms=["windows"],+ description="d", maintainer="t", platforms=[other],)- monkeypatch.setattr("hermes_platform.host.facts.os_family", lambda: "darwin")- with pytest.raises(pc.PluginOperationError, match="cat-plugin.*darwin.*windows"):+ with pytest.raises(pc.PluginOperationError, match=f"cat-plugin.*{host}.*{other}"):cat.install_catalog_entry(entry, force=False)assert not (world["plugins_dir"] / "cat-plugin").exists()@@ -112,10 +114,6 @@ def test_kill_list_blocks_cli_dashboard_and_tui_paths(world, monkeypatch):cat.resolved_removed_entries()) == "malware"-def test_removed_annotation_requires_a_pre_resolved_kill_list(world):- """No on-demand fallback: callers must resolve the kill list once, never per row."""- with pytest.raises(TypeError):- cat.removed_annotation("cat-plugin", world["plugins_dir"] / "cat-plugin")def test_owner_repo_hash_subdir_shorthand_resolves_like_the_catalog_spelling():diff --git a/tests/hermes_cli/test_plugins_cmd_category_discovery.py b/tests/hermes_cli/test_plugins_cmd_category_discovery.pyindex 43c3a771560..43de2fe70ac 100644--- a/tests/hermes_cli/test_plugins_cmd_category_discovery.py+++ b/tests/hermes_cli/test_plugins_cmd_category_discovery.py@@ -6,11 +6,9 @@ and path-derived key against the enabled/disabled sets."""import json-import sysfrom pathlib import Pathfrom unittest.mock import MagicMock, patch-import pytest# ---------------------------------------------------------------------------@@ -81,20 +79,6 @@ class TestReadManifestInfo:class TestDiscoverAllPlugins:- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_flat_plugins_still_discovered(self, mock_user_dir, mock_bundled_dir, tmp_path):- from hermes_cli.plugins_cmd import _discover_all_plugins-- _make_plugin_dir(tmp_path, "disk-cleanup", {- "name": "disk-cleanup", "version": "1.0.0"- })- mock_user_dir.return_value = tmp_path- mock_bundled_dir.return_value = tmp_path / "nonexistent"-- entries = _discover_all_plugins()- keys = [e[5] for e in entries]- assert "disk-cleanup" in keys@patch("hermes_cli.plugins.get_bundled_plugins_dir")diff --git a/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py b/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.pyindex 50b78c07570..8a6117c07ad 100644--- a/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py+++ b/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py@@ -116,24 +116,6 @@ class TestEnableDisableNested:with pytest.raises(SystemExit):cmd_enable("does-not-exist")- @patch("hermes_cli.plugins.get_bundled_plugins_dir")- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._save_disabled_set")- @patch("hermes_cli.plugins_cmd._save_enabled_set")- @patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set())- @patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set())- def test_enable_flat_plugin_unchanged(- self, mock_en, mock_dis, mock_save_en, mock_save_dis,- mock_user, mock_bundled, nested_plugin_env,- ):- """Flat plugins keep writing their bare name (key == name) — no regression."""- from hermes_cli.plugins_cmd import cmd_enable- mock_user.return_value = nested_plugin_env- mock_bundled.return_value = nested_plugin_env / "nonexistent"-- cmd_enable("disk-cleanup", allow_tool_override=False)- saved = mock_save_en.call_args[0][0]- assert "disk-cleanup" in saved# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_plugins_hub_perf_guard.py b/tests/hermes_cli/test_plugins_hub_perf_guard.pyindex c78616e123a..2b85b5ff414 100644--- a/tests/hermes_cli/test_plugins_hub_perf_guard.py+++ b/tests/hermes_cli/test_plugins_hub_perf_guard.py@@ -124,27 +124,6 @@ def test_plugins_hub_uses_cached_failed_check_fn_verdict(monkeypatch):-def test_plugins_hub_short_ttl_cache_collapses_duplicate_fetches(monkeypatch):- tools_registry.invalidate_check_fn_cache()- _web_server_dashboard._invalidate_plugins_hub_cache()-- calls = {"discover": 0}-- def discover_all_plugins():- calls["discover"] += 1- return list(_PLUGIN_ROW)-- _patch_minimal_hub_dependencies(- monkeypatch,- check_fn=lambda: True,- discover_all_plugins=discover_all_plugins,- )-- first = _web_server_dashboard._merged_plugins_hub(force_refresh=True)- second = _web_server_dashboard._merged_plugins_hub()-- assert calls["discover"] == 1- assert first is seconddef test_plugins_hub_route_builds_catalog_annotations_off_event_loop(monkeypatch):diff --git a/tests/hermes_cli/test_plugins_transcription_registration.py b/tests/hermes_cli/test_plugins_transcription_registration.pyindex 5f6ab4a2f78..2bd48a2c634 100644--- a/tests/hermes_cli/test_plugins_transcription_registration.py+++ b/tests/hermes_cli/test_plugins_transcription_registration.py@@ -109,7 +109,6 @@ class TestRegisterTranscriptionProvider:assert mgr._plugins["bad-stt-plugin"].enabled is Trueassert transcription_registry.get_provider("not a provider") is Noneassert transcription_registry.list_providers() == []- assert "does not inherit from TranscriptionProvider" in caplog.texttranscription_registry._reset_for_tests()@@ -143,6 +142,5 @@ class TestRegisterTranscriptionProvider:# not an exception. The registry rejects the entry though.assert mgr._plugins["shadow-stt-plugin"].enabled is Trueassert transcription_registry.get_provider("openai") is None- assert "shadows a built-in name" in caplog.texttranscription_registry._reset_for_tests()diff --git a/tests/hermes_cli/test_plugins_tts_registration.py b/tests/hermes_cli/test_plugins_tts_registration.pyindex 81a6b6a0bd8..47a50f1b804 100644--- a/tests/hermes_cli/test_plugins_tts_registration.py+++ b/tests/hermes_cli/test_plugins_tts_registration.py@@ -113,7 +113,6 @@ class TestRegisterTTSProvider:assert mgr._plugins["bad-tts-plugin"].enabled is Trueassert tts_registry.get_provider("not a provider") is Noneassert tts_registry.list_providers() == []- assert "does not inherit from TTSProvider" in caplog.texttts_registry._reset_for_tests()@@ -151,6 +150,5 @@ class TestRegisterTTSProvider:# not an exception. The registry rejects the entry though.assert mgr._plugins["shadow-tts-plugin"].enabled is Trueassert tts_registry.get_provider("edge") is None- assert "shadows a built-in name" in caplog.texttts_registry._reset_for_tests()diff --git a/tests/hermes_cli/test_post_setup_gating.py b/tests/hermes_cli/test_post_setup_gating.pyindex 9f1826d080f..c061790a3f0 100644--- a/tests/hermes_cli/test_post_setup_gating.py+++ b/tests/hermes_cli/test_post_setup_gating.py@@ -66,12 +66,6 @@ class TestBrowserBackendPrompt:opened, even when Browser Use was already configured."""- def test_browser_backend_set_skips_provider_picker(self, monkeypatch, tmp_path):- from hermes_cli import tools_config-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- config = {"browser": {"backend": "browser-use"}}- assert tools_config._toolset_needs_configuration_prompt("browser", config) is Falsedef test_browser_cloud_provider_set_skips_provider_picker(self, monkeypatch, tmp_path):from hermes_cli import tools_config@@ -80,11 +74,6 @@ class TestBrowserBackendPrompt:config = {"browser": {"cloud_provider": "local"}}assert tools_config._toolset_needs_configuration_prompt("browser", config) is False- def test_browser_unconfigured_still_prompts(self, monkeypatch, tmp_path):- from hermes_cli import tools_config-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- assert tools_config._toolset_needs_configuration_prompt("browser", {}) is Truedef test_browser_empty_still_prompts(self, monkeypatch, tmp_path):from hermes_cli import tools_configdiff --git a/tests/hermes_cli/test_pre_command_hook.py b/tests/hermes_cli/test_pre_command_hook.pyindex 1504354ca8d..569ad0bfdb2 100644--- a/tests/hermes_cli/test_pre_command_hook.py+++ b/tests/hermes_cli/test_pre_command_hook.py@@ -22,10 +22,6 @@ import pytest# ----------------------------------------------------------------------------def test_pre_command_in_valid_hooks():- from hermes_cli.plugins import VALID_HOOKS-- assert "pre_command" in VALID_HOOKS# ---------------------------------------------------------------------------@@ -64,20 +60,6 @@ def test_fire_helper_is_observer_only_and_never_raises(monkeypatch):assert calls["kwargs"]["command"] == "model"-def test_fire_helper_skips_when_no_plugin_listens(monkeypatch):- from hermes_cli import plugins as plugins_mod-- class _FakeManager:- def has_hook(self, name):- return False-- def invoke_hook(self, name, **kwargs): # pragma: no cover- raise AssertionError("invoke_hook must not be called")-- monkeypatch.setattr(plugins_mod, "get_plugin_manager", _FakeManager)- plugins_mod.fire_pre_command_hook(- surface="cli", command="help", alias_used="help", args_raw="",- )def test_fire_helper_swallows_manager_errors(monkeypatch):diff --git a/tests/hermes_cli/test_process_dock.py b/tests/hermes_cli/test_process_dock.pyindex ae6be28bb52..496e956941e 100644--- a/tests/hermes_cli/test_process_dock.py+++ b/tests/hermes_cli/test_process_dock.py@@ -2,7 +2,6 @@import timefrom types import SimpleNamespace-from prompt_toolkit.utils import get_cwidthdef _wait(predicate, timeout=5.0):@@ -12,45 +11,6 @@ def _wait(predicate, timeout=5.0):time.sleep(0.05)-def test_dock_paints_processes_under_agents_and_retires_finished_rows(monkeypatch):- from hermes_cli import cli_process_dock- from hermes_cli.cli_subagent_monitor import SubagentMonitor- from tools import delegate_tool_registry as registry- from tools.process_registry import process_registry-- monkeypatch.setattr(registry, '_active_subagents', {})- owner = SimpleNamespace(session_id='owner')- registry._register_subagent(dict(subagent_id='a1', owner_agent_session_id='owner',- goal='Check module', started_at=time.time() - 5, status='running', last_tool='read_file'))- quick = process_registry.spawn_local(command="echo hello-dock; exit 3", cwd='.', task_id='t', owner_task_id='t', session_key='')- slow = process_registry.spawn_local(command="sleep 30", cwd='.', task_id='t', owner_task_id='t', session_key='')- quick_id, slow_id = quick.id, slow.id- try:- _wait(lambda: process_registry.get(quick_id).exited)- process_registry.list_sessions() # observes the exit → exited_at stamped- dock = SubagentMonitor(SimpleNamespace(agent=owner))- assert dock.refresh()- text = dock.dock_text(columns=100, rows=30)- lines = text.splitlines()- assert 'Subagents · 1 live' in lines[0]- agents_at = next(i for i, line in enumerate(lines) if 'Check module' in line)- procs_at = next(i for i, line in enumerate(lines) if 'Processes · 1 running · 1 done' in line)- assert agents_at < procs_at- assert any('⚙ sleep 30' in line and 'starting' in line for line in lines)- assert any('✘ echo hello-dock; exit 3 · exit 3' in line for line in lines)- assert all(get_cwidth(line) <= 100 for line in lines)- # Every viewport keeps at least one row of each block.- narrow = dock.dock_text(columns=40, rows=14).splitlines()- assert any('Check module' in line for line in narrow) and any('Processes' in line for line in narrow)- assert all(get_cwidth(line) <= 40 for line in narrow)- dock.collapsed = True- assert dock.dock_text(columns=100, rows=30).count('\n') == 0- assert '1 live · 1 proc' in dock.dock_text(columns=100, rows=30)- # Finished rows leave after the retention window; running ones stay.- later = cli_process_dock.process_rows(time.time() + cli_process_dock.RETAIN_SECONDS + 1)- assert [r['id'] for r in later] == [slow_id]- finally:- process_registry.kill_process(slow_id)def test_monitor_controls_stop_processes_and_never_steer_them():diff --git a/tests/hermes_cli/test_process_identity.py b/tests/hermes_cli/test_process_identity.pyindex dc627ab9ee4..df9fc548e18 100644--- a/tests/hermes_cli/test_process_identity.py+++ b/tests/hermes_cli/test_process_identity.py@@ -25,7 +25,6 @@ from unittest.mock import MagicMock, patchimport pytestfrom hermes_cli import process_identity as pi-from hermes_cli import update_cmdclass _FakeNoSuchProcess(Exception):@@ -262,11 +261,6 @@ def test_updater_reaps_ledger_proven_orphans():assert cli_main._ledger_reapable_backend_pids(_holders(200, 201, 202, 203)) == [200]-def test_updater_ledger_rung_empty_without_ledger():- from hermes_cli import main as cli_main-- with patch.object(pi, "ledger_entries", return_value=[]):- assert cli_main._ledger_reapable_backend_pids(_holders(200)) == []def test_updater_ledger_rung_never_raises():diff --git a/tests/hermes_cli/test_process_notification_display.py b/tests/hermes_cli/test_process_notification_display.pyindex 21d5dd09697..37611c5d541 100644--- a/tests/hermes_cli/test_process_notification_display.py+++ b/tests/hermes_cli/test_process_notification_display.py@@ -39,8 +39,8 @@ def test_process_completion_display_keeps_payload_separate_across_surfaces(monkesetattr(cli, attr, value)cli._tui_process_one_input(cli._pending_input.get_nowait())visible = capsys.readouterr().out- expected = "Background Process Finished: cd /tmp && bash long-build.sh"- assert expected in visible+ expected = process_completion_display_text(events)+ assert "long-build.sh" in expected and expected in visibleassert "[IMPORTANT" not in visible and "SECRET_OUTPUT_LINE" not in visiblequeued = cli.chat.call_args.args[0]assert queued == payload # the model still receives the full notification@@ -72,12 +72,3 @@ def test_process_completion_display_keeps_payload_separate_across_surfaces(monkeassert kwargs["display_metadata"] == {"display_text": expected}-def test_process_completion_titles_reflect_outcome_and_batch():- assert process_completion_display_text([_event("p", 1)]) == (- "Background Process Failed (exit 1): cd /tmp && bash long-build.sh")- killed = {**_event("p", -15), "completion_reason": "killed"}- assert process_completion_display_text([killed]).startswith("Background Process Terminated: ")- assert process_completion_display_text([_event("a", 0), _event("b", 2)]) == "2 Background Processes Finished"- long_cmd = "x" * 200- title = process_completion_display_text([_event("p", 0, command=long_cmd)])- assert title.endswith("...") and len(title) < 120diff --git a/tests/hermes_cli/test_profile_credential_collisions.py b/tests/hermes_cli/test_profile_credential_collisions.pyindex 46a1c0d42c2..0803583ee7b 100644--- a/tests/hermes_cli/test_profile_credential_collisions.py+++ b/tests/hermes_cli/test_profile_credential_collisions.py@@ -48,7 +48,7 @@ def test_duplicate_singleton_secret_named_identically_by_doctor_status_and_preflassert len(findings) == 1line = findings[0]assert "'default'" in line and "'worker'" in line and "TELEGRAM_BOT_TOKEN" in line- assert "only one gateway" in line and gm.MIGRATE_COMMAND in line+ assert gm.MIGRATE_COMMAND in line# Same helper, same words: the preflight blocker IS the doctor/status finding.assert gm.build_migration_plan().blockers == findingsout = _surfaces()diff --git a/tests/hermes_cli/test_profile_describer.py b/tests/hermes_cli/test_profile_describer.pyindex d01d9a31283..1bd91fdd4b3 100644--- a/tests/hermes_cli/test_profile_describer.py+++ b/tests/hermes_cli/test_profile_describer.py@@ -121,7 +121,6 @@ def test_describer_refuses_to_overwrite_user_authored(profile_env, monkeypatch):outcome = describer.describe_profile("myprof")assert outcome.ok is False- assert "already has a user-authored description" in outcome.reason# Description unchangedassert profiles_mod.read_profile_meta(profile_env)["description"] == "curated"diff --git a/tests/hermes_cli/test_profile_display_name.py b/tests/hermes_cli/test_profile_display_name.pyindex 37a8052fbbd..da9fb6c4ffd 100644--- a/tests/hermes_cli/test_profile_display_name.py+++ b/tests/hermes_cli/test_profile_display_name.py@@ -97,7 +97,6 @@ class TestRenameDefault:assert rename_profile("default", "Harumesu") == profile_envassert profile_env.is_dir() # directory untouchedassert read_profile_meta(profile_env)["display_name"] == "Harumesu"- assert "canonical id remains 'default'" in capsys.readouterr().outdef test_reflected_in_list_profiles(self, profile_env):rename_profile("default", "Harumesu")diff --git a/tests/hermes_cli/test_profile_distribution.py b/tests/hermes_cli/test_profile_distribution.pyindex a2cee719952..12354172ef1 100644--- a/tests/hermes_cli/test_profile_distribution.py+++ b/tests/hermes_cli/test_profile_distribution.py@@ -24,7 +24,6 @@ from hermes_cli.profile_distribution import (DistributionManifest,EnvRequirement,MANIFEST_FILENAME,- USER_OWNED_EXCLUDE,_env_template_from_manifest,_looks_like_git_url,_parse_semver,@@ -293,14 +292,6 @@ class TestInstall:# distribution.yaml is always written by write_manifestassert (plan.target_dir / "distribution.yaml").exists()- def test_install_default_owned_paths_preserved(self, profile_env):- """When distribution_owned is not set, all DEFAULT_DIST_OWNED paths are copied."""- staged = _make_staging_dir(profile_env, "default_owned")- plan = install_distribution(str(staged), name="default_owned")- for path in DEFAULT_DIST_OWNED:- full = plan.target_dir / path- assert full.exists() or full.is_dir(), \- f"DEFAULT_DIST_OWNED '{path}' not found in target"def test_install_omitted_allowlist_copies_everything(self, profile_env):"""Legacy contract: when distribution_owned is OMITTED, every staged@@ -570,12 +561,6 @@ class TestDescribe:class TestSecurity:- def test_user_owned_exclude_covers_credentials(self):- assert "auth.json" in USER_OWNED_EXCLUDE- assert ".env" in USER_OWNED_EXCLUDE- assert "memories" in USER_OWNED_EXCLUDE- assert "sessions" in USER_OWNED_EXCLUDE- assert "local" in USER_OWNED_EXCLUDEdef test_install_does_not_import_credentials_from_staging(self, profile_env):"""If an author accidentally ships auth.json or .env in their@@ -633,18 +618,6 @@ class TestNestedUserOwnedExcludeNotFiltered:assert (plan.target_dir / "tools" / "bin").is_dir(), "nested bin/ was dropped"assert (plan.target_dir / "tools" / "bin" / "tool.py").exists()- def test_nested_logs_dir_is_preserved(self, profile_env):- mf = DistributionManifest(- name="nested_logs",- version="0.1.0",- distribution_owned=list(DEFAULT_DIST_OWNED) + ["scripts"],- )- staged = _make_staging_dir(profile_env, "src", manifest=mf)- (staged / "scripts" / "logs").mkdir(parents=True)- (staged / "scripts" / "logs" / "run.log").write_text("ok\n")- plan = install_distribution(str(staged), name="nested_logs")- assert (plan.target_dir / "scripts" / "logs").is_dir()- assert (plan.target_dir / "scripts" / "logs" / "run.log").read_text() == "ok\n"def test_top_level_user_owned_still_skipped(self, profile_env):"""Top-level entries in USER_OWNED_EXCLUDE must still be skipped —@@ -668,22 +641,6 @@ class TestNestedUserOwnedExcludeNotFiltered:assert not (plan.target_dir / "logs" / "shipped.log").exists(), \"staged logs/ content should not leak into target"- def test_both_nested_and_top_level_coexist(self, profile_env):- """Top-level bin/ filtered, but tools/bin/ kept."""- mf = DistributionManifest(- name="coexist",- version="0.1.0",- distribution_owned=list(DEFAULT_DIST_OWNED) + ["tools"],- )- staged = _make_staging_dir(profile_env, "src", manifest=mf)- (staged / "bin").mkdir(exist_ok=True)- (staged / "bin" / "top.sh").write_text("# top\n")- (staged / "tools" / "bin").mkdir(parents=True)- (staged / "tools" / "bin" / "helper.py").write_text("# helper\n")-- plan = install_distribution(str(staged), name="coexist")- assert not (plan.target_dir / "bin").exists()- assert (plan.target_dir / "tools" / "bin" / "helper.py").exists()# ===========================================================================diff --git a/tests/hermes_cli/test_profile_export_default_path.py b/tests/hermes_cli/test_profile_export_default_path.pyindex 23092e7250e..0d86014968d 100644--- a/tests/hermes_cli/test_profile_export_default_path.py+++ b/tests/hermes_cli/test_profile_export_default_path.py@@ -154,25 +154,6 @@ def test_slash_export_uses_the_same_managed_destination(assert not (tmp_path / "default.tar.gz").exists()-async def test_profile_export_api_uses_the_shared_managed_destination(- tmp_path, monkeypatch, profiles-):- from hermes_cli.web_models import ProfileExport-- router_mod = importlib.import_module("hermes_cli.web_routers.profiles")-- managed = tmp_path / "profile-exports" / "default-20260823-120000.tar.gz"- monkeypatch.setattr(profiles, "get_profile_export_path", lambda name: managed)- monkeypatch.setattr(- profiles,- "export_profile",- lambda name, output, extra_files=None: output,- )-- result = await router_mod.export_profile_endpoint("default", ProfileExport())-- assert result == {"ok": True, "archive": str(managed)}def test_cwd_in_unrelated_checkout_does_not_prove_safety(diff --git a/tests/hermes_cli/test_profile_identity_purge_cmd.py b/tests/hermes_cli/test_profile_identity_purge_cmd.pyindex 66a669d98d2..191bde8864d 100644--- a/tests/hermes_cli/test_profile_identity_purge_cmd.py+++ b/tests/hermes_cli/test_profile_identity_purge_cmd.py@@ -10,7 +10,7 @@ from pathlib import Pathimport pytest-from hermes_cli import profile_cmd, profiles+from hermes_cli import profile_cmd@pytest.fixture()@@ -34,12 +34,6 @@ def test_every_profile_subcommand_has_a_dispatch_entry():assert set(groups[0].choices) == set(profile_cmd.PROFILE_ACTIONS) - {None}-def test_purge_identity_reports_success(profile_env, monkeypatch, capsys):- monkeypatch.setattr("hermes_cli.profile_identity.purge_profile_identity", lambda name: True)-- profile_cmd.cmd_profile(Namespace(profile_action="purge-identity", profile_name="gone"))-- assert "identity purged: gone" in capsys.readouterr().outdef test_purge_identity_exits_nonzero_when_settlement_stays_pending(@@ -78,7 +72,6 @@ def test_purge_identity_refuses_a_same_name_profile_created_after_the_delete(proprofile_cmd.cmd_profile(Namespace(profile_action="purge-identity", profile_name="gone"))assert exc.value.code not in (0, None)- assert "purge-identity only settles the identity of a delete" in capsys.readouterr().outcheck = SessionDB(profile_env / ".hermes" / "state.db")try:# The recreated profile still owns its routing key.diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.pyindex 9a77f5dd6a8..152042ad916 100644--- a/tests/hermes_cli/test_profiles.py+++ b/tests/hermes_cli/test_profiles.py@@ -6,7 +6,6 @@ and shell completion generation."""import json-import ioimport osimport shutilimport sys@@ -34,13 +33,9 @@ from hermes_cli.profiles import (check_alias_collision,create_wrapper_script,remove_wrapper_script,- validate_alias_name,rename_profile,export_profile,- import_profile,- _get_profiles_root,_get_default_hermes_home,- seed_profile_skills,NO_BUNDLED_SKILLS_MARKER,backfill_profile_envs,profiles_to_serve,@@ -358,42 +353,6 @@ class TestNoSkillsOptOut:- def test_delete_marker_re_enables_seeding(self, profile_env, monkeypatch):- """Deleting .no-bundled-skills opts the profile back into a full sync.-- The sync subprocess runs in BOTH states: with the marker present,- sync_skills() itself seeds only the essential skills and reports- ``skipped_opt_out``; without it, a normal full sync happens.- """- import subprocess as _sp-- profile_dir = create_profile("orchestrator", no_alias=True, no_skills=True)- assert (profile_dir / NO_BUNDLED_SKILLS_MARKER).is_file()-- # Marker present: the subprocess still runs (essential-only seeding- # happens inside sync_skills) and its skipped_opt_out flag surfaces.- called = []- stdout_by_call = [- '{"copied": ["hermes-agent"], "skipped_opt_out": true}',- '{"copied": []}',- ]- monkeypatch.setattr(- "subprocess.run",- lambda *a, **kw: (called.append(a), _sp.CompletedProcess(- args=a, returncode=0,- stdout=stdout_by_call[min(len(called) - 1, 1)], stderr="",- ))[1],- )- r1 = seed_profile_skills(profile_dir, quiet=True)- assert r1.get("skipped_opt_out") is True- assert r1.get("copied") == ["hermes-agent"]- assert len(called) == 1-- # Delete marker → next call is a normal full sync.- (profile_dir / NO_BUNDLED_SKILLS_MARKER).unlink()- r2 = seed_profile_skills(profile_dir, quiet=True)- assert r2 == {"copied": []}- assert len(called) == 2# ===================================================================@@ -965,7 +924,7 @@ class TestWrapperScript:@pytest.mark.windows_onlydef test_remove_finds_bat_on_windows(self, profile_env):- from hermes_cli.profiles import create_wrapper_script, remove_wrapper_script+ from hermes_cli.profiles import create_wrapper_scriptwrapper = create_wrapper_script("mybot")assert wrapper is not Noneassert wrapper.exists()@@ -1194,16 +1153,6 @@ class TestRenameProfile:acquire.assert_not_called()- def test_live_gateway_failure_does_not_rewrite_db_directly(self, profile_env, capsys):- create_profile("oldname", no_alias=True)- with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"), \- patch("hermes_cli.profiles._live_default_multiplexer", return_value=True), \- patch("hermes_cli.profiles._notify_multiplexer"), \- patch("gateway.control_socket.migrate_gateway_profile_identity", return_value=None), \- patch("hermes_state_registry.acquire") as acquire:- rename_profile("oldname", "newname")- acquire.assert_not_called()- assert "Restart the gateway" in capsys.readouterr().errdef test_migrate_identity_command_repairs_a_failed_live_migration(self, profile_env, capsys):"""The failed-live-migration end state must be recoverable: `hermes profile@@ -1260,19 +1209,6 @@ class TestRenameProfile:assert "agent:newname:feishu:dm:chatA" in routingroot_db2.close()- def test_rename_records_previous_name(self, profile_env):- create_profile("oldname", no_alias=True)-- # Mock alias collision to avoid subprocess calls- with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"):- new_dir = rename_profile("oldname", "newname")-- # The rename history is recorded in the new profile's metadata ...- assert profiles.read_profile_meta(new_dir)["previous_names"] == ["oldname"]- # ... and surfaces through list_profiles (the gateway's profiles.list- # source), so Bot Mode group chats can re-link stale member handles.- info = next(p for p in list_profiles() if p.name == "newname")- assert info.previous_names == ["oldname"]def test_rename_accumulates_previous_names(self, profile_env):create_profile("firstname", no_alias=True)@@ -1387,16 +1323,6 @@ class TestExportImport:# TestProfileIsolation# ===================================================================-class TestProfileIsolation:- """Verify that two profiles have completely separate paths."""-- def test_separate_config_paths(self, profile_env):- create_profile("alpha", no_alias=True)- create_profile("beta", no_alias=True)- alpha_dir = get_profile_dir("alpha")- beta_dir = get_profile_dir("beta")- assert alpha_dir / "config.yaml" != beta_dir / "config.yaml"- assert str(alpha_dir) not in str(beta_dir)# ===================================================================@@ -1408,14 +1334,6 @@ class TestInternalHelpers:- def test_default_hermes_home_docker(self, tmp_path, monkeypatch):- """In Docker, _get_default_hermes_home() returns HERMES_HOME itself."""- docker_home = tmp_path / "opt" / "data"- docker_home.mkdir(parents=True)- monkeypatch.setattr(Path, "home", lambda: tmp_path)- monkeypatch.setenv("HERMES_HOME", str(docker_home))- home = _get_default_hermes_home()- assert home == docker_home@@ -1821,14 +1739,6 @@ class TestCloneAllExcludesRuntimeTrees:(source / tree).mkdir()assert not _clone_all_copytree_ignore(source)(str(source), [*self.RUNTIME_TREES, "SOUL.md"])- def test_runtime_trio_is_one_constant_shared_with_backup(self):- """backup's exclusion list and the clone-all root gate must be built from the same- constant; two literals drifting apart is how the models/ copy of #111718 crept in."""- from hermes_cli import backup, profiles- from hermes_constants import LOCAL_RUNTIME_ROOT_DIRS- assert LOCAL_RUNTIME_ROOT_DIRS == frozenset(self.RUNTIME_TREES)- assert backup._EXCLUDED_ROOT_DIRS is LOCAL_RUNTIME_ROOT_DIRS- assert LOCAL_RUNTIME_ROOT_DIRS <= profiles._CLONE_ALL_DEFAULT_EXCLUDE_ROOTdef test_clone_all_from_default_skips_runtime_trees_but_keeps_the_rest(self, profile_env):default_home = profile_env / ".hermes"