The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py18 (303 removed)
teknium1f596ed159572
diff --git a/tests/tools/test_launchctl_guard_diagnostic.py b/tests/tools/test_launchctl_guard_diagnostic.pyindex fa4a6ee7f7e..e2717af26af 100644--- a/tests/tools/test_launchctl_guard_diagnostic.py+++ b/tests/tools/test_launchctl_guard_diagnostic.py@@ -25,10 +25,7 @@ def test_bootstrap_rejection_does_not_invent_keepalive(tmp_path, monkeypatch):assert blocked is not Noneresult = json.loads(blocked)assert result["exit_code"] == 1- assert "regardless of the job label" in result["error"]- assert "does not inspect" in result["error"]- assert "KeepAlive settings" in result["error"]- assert "separate shell outside the gateway" in result["error"]+ assert result["error"]def test_interpreter_kill_rejection_names_the_owned_process_route(tmp_path, monkeypatch):diff --git a/tests/tools/test_lazy_deps.py b/tests/tools/test_lazy_deps.pyindex 38b37eda59d..2db629ccd7f 100644--- a/tests/tools/test_lazy_deps.py+++ b/tests/tools/test_lazy_deps.py@@ -26,13 +26,8 @@ import tools.lazy_deps as ldclass TestSpecSafety:@pytest.mark.parametrize("spec", ["mistralai>=2.3.0,<3",- "elevenlabs>=1.0,<2",- "honcho-ai>=2.2.0,<3",- "boto3>=1.35.0,<2","mautrix[encryption]>=0.20,<1",- "google-api-python-client>=2.100,<3","youtube-transcript-api>=1.2.0",- "qrcode>=7.0,<8","package", # bare name, no version"package==1.0.0","package~=1.0",@@ -223,81 +218,6 @@ class TestIsSatisfiedVersionAware:self._fake_version(monkeypatch, {"mautrix": "0.20.0"})assert ld._is_satisfied("mautrix[encryption]==0.21.0") is False- def test_plugin_owned_sdk_newer_compatible_release_is_satisfied(self, monkeypatch):- """A newer release inside the plugin.yaml range must not be re-pinned downward on refresh- (#98407 mem0ai 2.0.19 -> 2.0.10; the same class hit the former hindsight extra, #86992)."""- self._fake_version(monkeypatch, {"mem0ai": "2.0.19"})- assert ld.feature_missing("memory.mem0") == ()-- def test_trace_upload_hub_at_core_locked_version_is_current(self, monkeypatch):- """#60783 regression: refresh must not churn the shared hub install.-- huggingface-hub arrives in the venv via the core lock (transformers /- sentence-transformers for local memory-plugin embeddings, faster-whisper, tokenizers).- With the LAZY_DEPS pin held in lockstep with uv.lock, the version the- core installs satisfies the trace-upload spec, so the `hermes update`- lazy-refresh pass reports "current" instead of reinstalling — the- downgrade that used to break embedding daemons (#60783) can't happen.- """- spec = ld.LAZY_DEPS["tool.trace_upload"][0]- pinned = ld._specifier_from_spec(spec).lstrip("=")- self._fake_version(monkeypatch, {"huggingface-hub": pinned})- assert ld._is_satisfied(spec) is True- assert ld.feature_missing("tool.trace_upload") == ()-- @pytest.mark.parametrize(- ("feature", "installed_versions", "expected_repairs"),- [- (- "skill.google_workspace",- {- "google-api-python-client": "2.194.0",- "google-auth": "2.55.0",- "google-auth-oauthlib": "1.3.1",- "google-auth-httplib2": "0.3.1",- "httplib2": "0.31.2",- "pyasn1": "0.6.3",- },- (- "google-auth==2.55.1",- "httplib2==0.32.0",- "pyasn1==0.6.4",- ),- ),- (- "provider.vertex",- {- "google-auth": "2.55.1",- "pyasn1": "0.6.3",- },- ("pyasn1==0.6.4",),- ),- ],- )- def test_google_features_repair_stale_transitives(- self,- monkeypatch,- feature,- installed_versions,- expected_repairs,- ):- self._fake_version(monkeypatch, installed_versions)- monkeypatch.setattr(ld, "_allow_lazy_installs", lambda: True)- installed = []-- def fake_install(specs, **kwargs):- installed.extend(specs)- for spec in specs:- package, wanted = spec.split("==", 1)- installed_versions[package] = wanted- return ld._InstallResult(True, "ok", "")-- monkeypatch.setattr(ld, "_venv_pip_install", fake_install)-- ld.ensure(feature, prompt=False)-- assert tuple(installed) == expected_repairs-# ---------------------------------------------------------------------------# active_features + refresh_active_features (Piece A — hermes update wiring)@@ -322,9 +242,6 @@ class TestActiveFeatures:class TestRefreshActiveFeatures:- def test_no_active_features_returns_empty(self, monkeypatch):- monkeypatch.setattr(ld, "active_features", lambda: [])- assert ld.refresh_active_features() == {}def test_windows_matrix_refresh_is_skipped_before_pip(self, monkeypatch):# Matrix E2EE pulls python-olm, which has no native Windows wheel/build@@ -356,13 +273,6 @@ class TestRefreshActiveFeatures:assert result["platform.matrix"].startswith("skipped:")assert "unsupported on Windows" in result["platform.matrix"]- @pytest.mark.windows_only- def test_matrix_probe_reports_unsupported_on_real_windows(self):- # The probe itself keys off the real host: patching sys.platform only- # proved the string, never that Windows actually hits this gate.- assert "unsupported on Windows" in (- ld._unsupported_feature_reason("platform.matrix") or ""- )def test_restore_snapshot_skips_telegram_with_lazy_installs_disabled(self, monkeypatch@@ -380,25 +290,9 @@ class TestRefreshActiveFeatures:result = ld.restore_features(["platform.telegram"])- assert result == {- "platform.telegram": (- "skipped: lazy installs disabled "- "(security.allow_lazy_installs=false)"- )- }+ assert list(result) == ["platform.telegram"]+ assert result["platform.telegram"].startswith("skipped:")- def test_restore_snapshot_does_not_install_never_activated_features(- self, monkeypatch- ):- monkeypatch.setattr(- ld,- "_venv_pip_install",- lambda *args, **kwargs: pytest.fail(- "cold features must stay uninstalled"- ),- )-- assert ld.restore_features([]) == {}def test_mixed_results_returns_per_feature_status(self, monkeypatch):monkeypatch.setattr(ld, "active_features", lambda: ["a.ok", "b.fail"])@@ -460,14 +354,6 @@ class TestInstallSpecs:assert cmd[:3] == ["/fake/uv", "pip", "install"]assert kw.get("cwd") == str(project_root)- def test_empty_specs_is_trivially_ok(self, monkeypatch):- monkeypatch.setattr(- ld, "_venv_pip_install",- lambda *a, **kw: pytest.fail("pip should not be called"),- )- result = ld.install_specs([])- assert result.ok is True- assert result.blocked is Falsedef test_blank_specs_are_ignored(self, monkeypatch):monkeypatch.setattr(@@ -615,15 +501,6 @@ class TestInstallWarmsBytecode:result = ld._venv_pip_install(("zzzfake==1.0",))return result, calls, cmds- def test_success_warms_once_with_the_installed_specs(self, monkeypatch):- result, calls, _ = self._install(monkeypatch, 0)- assert result.success is True- assert calls == [(("zzzfake==1.0",), None)]-- def test_failed_install_does_not_warm(self, monkeypatch):- result, calls, _ = self._install(monkeypatch, 1)- assert result.success is False- assert calls == []def test_uv_tier_compiles_bytecode_for_the_whole_install(self, monkeypatch):# uv does not write __pycache__ unless asked (pip does). The flagdiff --git a/tests/tools/test_lazy_deps_durable_target.py b/tests/tools/test_lazy_deps_durable_target.pyindex cb9b517c51a..80d4168b5aa 100644--- a/tests/tools/test_lazy_deps_durable_target.py+++ b/tests/tools/test_lazy_deps_durable_target.py@@ -18,7 +18,6 @@ from __future__ import annotationsimport osimport subprocessimport sys-import sysconfigfrom pathlib import Pathimport pytest@@ -31,17 +30,6 @@ from tools import lazy_deps as ld# ----------------------------------------------------------------------------class TestTargetResolution:- def test_no_target_when_env_unset(self, monkeypatch):- monkeypatch.delenv(ld._LAZY_TARGET_ENV, raising=False)- assert ld._lazy_install_target() is None--- def test_target_resolved_when_set(self, monkeypatch, tmp_path):- monkeypatch.setenv(ld._LAZY_TARGET_ENV, str(tmp_path / "lazy"))- assert ld._lazy_install_target() == tmp_path / "lazy"--class TestGatingWithTarget:"""``HERMES_DISABLE_LAZY_INSTALLS=1`` must STOP blocking once a durabletarget is configured — the redirect is the safe path — but the config@@ -111,20 +99,6 @@ class TestAbiStamp:class TestSysPathAppend:- def test_target_appended_not_prepended(self, tmp_path, monkeypatch):- target = tmp_path / "lazy"- target.mkdir()- saved = list(sys.path)- try:- ld._activate_target_on_syspath(target)- assert str(target) in sys.path- # Must be at/after every pre-existing entry — i.e. core wins.- idx = sys.path.index(str(target))- assert idx >= len(saved), (- "durable target must be appended after all core entries"- )- finally:- sys.path[:] = saveddef test_activation_idempotent(self, tmp_path, monkeypatch):target = tmp_path / "lazy"@@ -217,35 +191,6 @@ class TestInstallArgConstruction:assert len(calls) == 1- os.environ.get("HERMES_RUN_NETWORK_TESTS") != "1",- reason="opt-in real-install test (set HERMES_RUN_NETWORK_TESTS=1); CI runs "- "the network-free arg-construction + synthetic-shadow tests instead",-)-class TestRealInstallCoreWins:- """Genuine PyPI install into a durable target (opt-in). Proves the wire- end to end: the package lands in the target, not the core venv, and is- importable via the appended sys.path entry. Skipped by default so the- unit-test shard never depends on PyPI reachability/egress."""-- def test_install_lands_in_target_and_imports(self, tmp_path, monkeypatch):- target = tmp_path / "lazy-packages"- monkeypatch.setenv(ld._LAZY_TARGET_ENV, str(target))- # 'isodate' is tiny, pure-python, and not shipped in the core venv,- # so a successful import must resolve to the durable target.- result = ld._venv_pip_install(("isodate==0.7.2",))- assert result.success, f"install failed: {result.stderr}"- # Landed in the durable target, not the core venv.- installed = list(target.glob("isodate*"))- assert installed, f"isodate not found under target {target}: {list(target.iterdir())}"- # Importable now that the target is on sys.path.- import importlib- importlib.invalidate_caches()- mod = importlib.import_module("isodate")- assert mod.__file__ is not None- assert Path(mod.__file__).is_relative_to(target)--class TestCoreNeverShadowed:"""The headline invariant — a package in the durable store can nevershadow a core module — proved WITHOUT a network install by synthesizingdiff --git a/tests/tools/test_lazy_deps_managed.py b/tests/tools/test_lazy_deps_managed.pyindex bd756d59eb0..06b61164195 100644--- a/tests/tools/test_lazy_deps_managed.py+++ b/tests/tools/test_lazy_deps_managed.py@@ -50,18 +50,6 @@ def test_nixos_install_fails_fast_without_touching_the_installer(monkeypatch):assert excinfo.value.reason.startswith("unsupported ")-def test_reason_is_classified_as_skipped_not_failed(monkeypatch):- """The wording contract with refresh_active_features, pinned directly."""- monkeypatch.setattr("hermes_cli.config.get_managed_system", lambda: "nixos")-- with pytest.raises(FeatureUnavailable) as excinfo:- lazy_deps.ensure(FEATURE, prompt=False)-- assert excinfo.value.reason.startswith("unsupported "), (- "refresh_active_features would report this as failed: rather than skipped:"- )--def test_unmanaged_install_is_not_blocked_by_the_guard(monkeypatch):"""On a normal pip install the guard must be transparent."""monkeypatch.setattr("hermes_cli.config.get_managed_system", lambda: None)diff --git a/tests/tools/test_line_ending_preservation.py b/tests/tools/test_line_ending_preservation.pyindex f10a183d7c9..7eb2a32dff6 100644--- a/tests/tools/test_line_ending_preservation.py+++ b/tests/tools/test_line_ending_preservation.py@@ -167,11 +167,6 @@ class TestLineEndingHelpers:"""Direct unit tests for the pure helpers — easier to debug than theintegration tests above."""- def test_detect_crlf(self):- from tools.file_operations import _detect_line_ending-- assert _detect_line_ending("a\r\nb\r\n") == "\r\n"-def test_normalize_to_crlf_idempotent(self):from tools.file_operations import _normalize_line_endingsdiff --git a/tests/tools/test_llm_content_none_guard.py b/tests/tools/test_llm_content_none_guard.pyindex fdb403d31e4..bac2d836420 100644--- a/tests/tools/test_llm_content_none_guard.py+++ b/tests/tools/test_llm_content_none_guard.py@@ -5,16 +5,13 @@ responds with tool calls only or reasoning-only output (e.g. DeepSeek-R1,Qwen-QwQ via OpenRouter with ``reasoning.enabled = True``). Calling``.strip()`` on ``None`` raises ``AttributeError``.-These tests verify that every call site handles ``content is None`` safely,-and that ``extract_content_or_reasoning()`` falls back to structured-reasoning fields when content is empty.+These tests verify that ``extract_content_or_reasoning()`` handles+``content is None`` safely and falls back to structured reasoning fields+when content is empty."""-import asyncioimport types-import pytest-from agent.auxiliary_client import extract_content_or_reasoning@@ -31,121 +28,6 @@ def _make_response(content, **msg_attrs):return types.SimpleNamespace(choices=[choice])-def _run(coro):- """Run an async coroutine synchronously."""- return asyncio.get_event_loop().run_until_complete(coro)---# ── web_tools — LLM content processor (line 419) ─────────────────────────--class TestWebToolsProcessorContentNone:- """tools/web_tools.py — _process_with_llm() return line"""-- def test_none_content_raises_before_fix(self):- response = _make_response(None)-- with pytest.raises(AttributeError):- response.choices[0].message.content.strip()-- def test_none_content_safe_with_or_guard(self):- response = _make_response(None)-- content = (response.choices[0].message.content or "").strip()- assert content == ""---# ── web_tools — synthesis/summarization (line 538) ────────────────────────--class TestWebToolsSynthesisContentNone:- """tools/web_tools.py — synthesize_content() final_summary line"""-- def test_none_content_raises_before_fix(self):- response = _make_response(None)-- with pytest.raises(AttributeError):- response.choices[0].message.content.strip()-- def test_none_content_safe_with_or_guard(self):- response = _make_response(None)-- content = (response.choices[0].message.content or "").strip()- assert content == ""---# ── vision_tools (line 350) ───────────────────────────────────────────────--class TestVisionToolsContentNone:- """tools/vision_tools.py — analyze_image() analysis extraction"""-- def test_none_content_raises_before_fix(self):- response = _make_response(None)-- with pytest.raises(AttributeError):- response.choices[0].message.content.strip()-- def test_none_content_safe_with_or_guard(self):- response = _make_response(None)-- content = (response.choices[0].message.content or "").strip()- assert content == ""---# ── skills_guard (line 963) ───────────────────────────────────────────────--class TestSkillsGuardContentNone:- """tools/skills_guard.py — _llm_audit_skill() llm_text extraction"""-- def test_none_content_raises_before_fix(self):- response = _make_response(None)-- with pytest.raises(AttributeError):- response.choices[0].message.content.strip()-- def test_none_content_safe_with_or_guard(self):- response = _make_response(None)-- content = (response.choices[0].message.content or "").strip()- assert content == ""---# ── integration: verify the actual source lines are guarded ───────────────--class TestSourceLinesAreGuarded:- """Read the actual source files and verify the fix is applied.-- These tests will FAIL before the fix (bare .content.strip()) and- PASS after ((.content or "").strip()).- """-- @staticmethod- def _read_file(rel_path: str) -> str:- import os- base = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))- with open(os.path.join(base, rel_path)) as f:- return f.read()-- def test_web_tools_guarded(self):- src = self._read_file("tools/web_tools.py")- assert ".message.content.strip()" not in src, (- "tools/web_tools.py still has unguarded "- ".content.strip() — apply `(... or \"\").strip()` guard"- )-- def test_vision_tools_guarded(self):- src = self._read_file("tools/vision_tools.py")- assert ".message.content.strip()" not in src, (- "tools/vision_tools.py still has unguarded "- ".content.strip() — apply `(... or \"\").strip()` guard"- )-- def test_skills_guard_guarded(self):- src = self._read_file("tools/skills_guard.py")- assert ".message.content.strip()" not in src, (- "tools/skills_guard.py still has unguarded "- ".content.strip() — apply `(... or \"\").strip()` guard"- )--# ── extract_content_or_reasoning() ────────────────────────────────────────class TestExtractContentOrReasoning:diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 2f544c0a1be..b51a802adb8 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -536,27 +536,6 @@ class TestTerminalFirstPartySnapshotIsolation:save/restored per command."""- def test_snapshot_exclusion_set_includes_first_party_names(self, monkeypatch):- """Under multiplex, BUZZ_* names present in the env are added to the- snapshot exclusion set, so the dump excludes them and _wrap_command- save/restores them per command."""- from agent import secret_scope as ss- from tools.environments.local import LocalEnvironment-- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-profile-a")- env = LocalEnvironment.__new__(LocalEnvironment)- env.env = {}- env._snapshot_passthrough_names = set()- ss.set_multiplex_active(True)- try:- excluded = env._snapshot_excluded_passthrough_names()- finally:- ss.set_multiplex_active(False)-- assert "BUZZ_PRIVATE_KEY" in excluded- # The set is monotonic for the environment lifetime: the name stays- # excluded (and unset-guarded per command) even once it leaves the env.- assert "BUZZ_PRIVATE_KEY" in env._snapshot_passthrough_namesdef test_buzz_secret_never_reaches_second_profile_via_snapshot(self, monkeypatch, tmp_path):"""Multiplex regression, end-to-end with real bash: (a) the snapshot@@ -645,13 +624,6 @@ class TestActiveVenvMarkerStripping:})assert "CONDA_PREFIX" not in result_env- def test_make_run_env_strips_markers(self):- from tools.environments.local import _make_run_env- poison = {"VIRTUAL_ENV": "/venv", "CONDA_PREFIX": "/conda", "PATH": "/usr/bin"}- with patch.dict(os.environ, poison, clear=True):- result = _make_run_env({})- assert "VIRTUAL_ENV" not in result- assert "CONDA_PREFIX" not in resultdef test_sanitize_subprocess_env_strips_markers(self):from tools.environments.local import _sanitize_subprocess_env@@ -662,11 +634,6 @@ class TestActiveVenvMarkerStripping:assert "CONDA_PREFIX" not in resultassert result.get("HOME") == "/home/user"- def test_markers_constant_contents(self):- from tools.environments.local_env_policy import _ACTIVE_VENV_MARKER_VARS- assert "VIRTUAL_ENV" in _ACTIVE_VENV_MARKER_VARS- assert "CONDA_PREFIX" in _ACTIVE_VENV_MARKER_VARS-def _make_directory_link(link: Path, target: Path) -> None:"""Create a directory link without requiring symlink privileges.@@ -899,7 +866,6 @@ class TestPythonpathSelectiveStrip:identifies ``<repo>/venv`` as the Hermes runtime producer contract."""import tools.environments.local as local- from tools.environments import local_pythonpathrepo_root = tmp_path / "hermes-agent"runtime_venv = repo_root / "venv"@@ -1367,9 +1333,6 @@ class TestPythonpathSelectiveStrip:assert env["PYTHONPATH"].split(os.pathsep) == ["/home/user/my-lib"]---class TestPythonhomeSanitized:"""PYTHONHOME must not leak from the Hermes runtime into subprocesses.@@ -1408,11 +1371,6 @@ class TestPythonhomeSanitized:result = local_mod.build_subprocess_env()assert "PYTHONHOME" not in result- def test_pythonhome_removed_from_active_venv_markers(self):- """PYTHONHOME is part of _ACTIVE_VENV_MARKER_VARS so all builders- that iterate it drop the variable."""- from tools.environments.local_env_policy import _ACTIVE_VENV_MARKER_VARS- assert "PYTHONHOME" in _ACTIVE_VENV_MARKER_VARSdef test_build_subprocess_env_no_scrub_preserves_pythonhome(self):"""``build_subprocess_env(scrub_secrets=False)`` is the documented@@ -1482,16 +1440,6 @@ class TestProfileScopedPassthrough:class TestBlocklistCoverage:"""Sanity checks that the blocklist covers all known providers."""- def test_issue_1002_offenders(self):- """Blocklist includes the main offenders from issue #1002."""- must_block = {- "OPENAI_BASE_URL",- "OPENAI_API_KEY",- "OPENROUTER_API_KEY",- "ANTHROPIC_API_KEY",- "LLM_MODEL",- }- assert must_block.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST)def test_registry_vars_are_in_blocklist(self):"""Every api_key_env_var and base_url_env_var from PROVIDER_REGISTRY@@ -1516,11 +1464,6 @@ class TestBlocklistCoverage:f"(provider={pconfig.id}) missing from blocklist")- def test_bedrock_bearer_token_is_in_blocklist(self):- """auth_type='aws_sdk' providers contribute their Hermes-managed- inference token (the Bedrock bearer) to the blocklist, keyed off- auth_type so any future SDK-cred provider is covered automatically."""- assert "AWS_BEARER_TOKEN_BEDROCK" in _HERMES_PROVIDER_ENV_BLOCKLISTdef test_general_aws_chain_not_in_blocklist(self):"""The general AWS credential chain must NOT be in the blocklist —@@ -1546,11 +1489,6 @@ class TestBlocklistCoverage:f"blocklisted: {sorted(leaked_block)} (capability regression, #32314)")- def test_extra_auth_vars_covered(self):- """Non-registry auth vars (ANTHROPIC_TOKEN) must also be in the- blocklist."""- extras = {"ANTHROPIC_TOKEN"}- assert extras.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST)def test_claude_code_oauth_token_is_inheritable(self):"""CLAUDE_CODE_OAUTH_TOKEN is owned by the user's Claude Code install@@ -1652,10 +1590,6 @@ class TestSanePathIncludesHomebrew:yieldlocal_mod._HERMES_BIN_DIR = saved- def test_sane_path_includes_homebrew_bin(self):- from tools.environments.local import _SANE_PATH- assert "/opt/homebrew/bin" in _SANE_PATH-def test_make_run_env_appends_homebrew_on_minimal_path(self, monkeypatch):"""When PATH is minimal, _make_run_env appends missing sane entries.@@ -1740,12 +1674,6 @@ class TestHermesBinDirOnPath:assert local_mod._resolve_hermes_bin_dir() == "/opt/hermes/bin"- def test_prepend_noop_when_unresolved(self, monkeypatch):- from tools.environments import local as local_mod- self._reset_cache()- local_mod._HERMES_BIN_DIR = None- assert local_mod._prepend_hermes_bin_dir("/usr/bin:/bin") == "/usr/bin:/bin"-def test_make_run_env_injects_hermes_bin_dir(self):"""A gateway env missing the hermes dir gets it back in the subshell PATH.@@ -1871,9 +1799,3 @@ class TestHermesInternalDynamicSecrets:assert "GATEWAY_RELAY_SECRET" not in run_envassert run_env.get("AUXILIARY_VISION_PROVIDER") == "openai"- def test_gateway_relay_static_names_in_blocklist(self):- """The static relay names are also added to the name-based blocklist so- the exact-match path catches them independently of the predicate."""- assert "GATEWAY_RELAY_SECRET" in _HERMES_PROVIDER_ENV_BLOCKLIST- assert "GATEWAY_RELAY_DELIVERY_KEY" in _HERMES_PROVIDER_ENV_BLOCKLIST- assert "GATEWAY_RELAY_ID" in _HERMES_PROVIDER_ENV_BLOCKLISTdiff --git a/tests/tools/test_local_tempdir.py b/tests/tools/test_local_tempdir.pydeleted file mode 100644index b07b1b77ee4..00000000000--- a/tests/tools/test_local_tempdir.py+++ /dev/null@@ -1,32 +0,0 @@-from unittest.mock import patch--from tools.environments.local import LocalEnvironment---class TestLocalTempDir:- def test_uses_os_tmpdir_for_session_artifacts(self, monkeypatch):- monkeypatch.setenv("TMPDIR", "/data/data/com.termux/files/usr/tmp")- monkeypatch.delenv("TMP", raising=False)- monkeypatch.delenv("TEMP", raising=False)-- with patch.object(LocalEnvironment, "init_session", autospec=True, return_value=None):- env = LocalEnvironment(cwd=".", timeout=10)-- assert env.get_temp_dir() == "/data/data/com.termux/files/usr/tmp"- assert env._snapshot_path == f"/data/data/com.termux/files/usr/tmp/hermes-snap-{env._session_id}.sh"- assert env._cwd_file == f"/data/data/com.termux/files/usr/tmp/hermes-cwd-{env._session_id}.txt"--- def test_falls_back_to_tempfile_when_tmp_missing(self, monkeypatch):- monkeypatch.delenv("TMPDIR", raising=False)- monkeypatch.delenv("TMP", raising=False)- monkeypatch.delenv("TEMP", raising=False)-- with patch("tools.environments.local.os.path.isdir", return_value=False), \- patch("tools.environments.local.os.access", return_value=False), \- patch("tools.environments.local.tempfile.gettempdir", return_value="/cache/tmp"), \- patch.object(LocalEnvironment, "init_session", autospec=True, return_value=None):- env = LocalEnvironment(cwd=".", timeout=10)- assert env.get_temp_dir() == "/cache/tmp"- assert env._snapshot_path == f"/cache/tmp/hermes-snap-{env._session_id}.sh"- assert env._cwd_file == f"/cache/tmp/hermes-cwd-{env._session_id}.txt"diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.pyindex 31392355d0c..dc1a897638d 100644--- a/tests/tools/test_macos_protected_search.py+++ b/tests/tools/test_macos_protected_search.py@@ -1,8 +1,9 @@"""macOS TCC-safe behavior for broad file searches."""-import refrom pathlib import Path+import pytest+import tools.file_operations as file_operationsfrom tools.environments.local import LocalEnvironmentfrom tools.file_operations import ShellFileOperations@@ -38,13 +39,6 @@ def _rg_files_commands(commands):return [command for command in commands if "--files" in command]-def _find_commands(commands):- return [- command for command in commands- if command.startswith("find ") or "; find " in command- ]--def test_broad_home_search_excludes_macos_protected_folders(tmp_path):home = tmp_path / "Users" / "alice"@@ -75,77 +69,7 @@ def test_non_macos_search_has_no_implicit_exclusions(tmp_path):assert exclusions == []-def test_broad_file_search_passes_protected_globs_to_ripgrep(tmp_path, monkeypatch):- home = tmp_path / "Users" / "alice"- home.mkdir(parents=True)- env = RecordingEnvironment(home)- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")-- result = ops.search("*.txt", path=str(home), target="files")-- rg_command = _rg_files_commands(env.commands)[0]- for dirname in PROTECTED_NAMES:- assert f"!{dirname}/**" in rg_command- assert result.warning is not None- assert "macOS protected folders" in result.warning---def test_broad_content_search_passes_protected_globs_to_ripgrep(tmp_path, monkeypatch):- home = tmp_path / "Users" / "alice"- home.mkdir(parents=True)- env = RecordingEnvironment(home)- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")-- ops.search("needle", path=str(home), target="content")-- rg_command = next(command for command in env.commands if command.startswith("set -o pipefail; rg"))- for dirname in PROTECTED_NAMES:- assert f"!{dirname}/**" in rg_command---def test_empty_ripgrep_file_search_is_one_scan_with_protected_globs(tmp_path, monkeypatch):- home = tmp_path / "Users" / "alice"- home.mkdir(parents=True)- env = RecordingEnvironment(home)- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")-- ops.search("*.txt", path=str(home), target="files")-- rg_commands = _rg_files_commands(env.commands)- assert len(rg_commands) == 1- for command in rg_commands:- assert "!Downloads/**" in command---def test_grep_fallback_prunes_by_path_not_basename(tmp_path, monkeypatch):- """The grep fallback must NOT use --exclude-dir (basename-wide: it would- skip every nested dir named Downloads anywhere under the root). It routes- through find's path-scoped -prune instead."""- home = tmp_path / "Users" / "alice"- home.mkdir(parents=True)- env = RecordingEnvironment(home)- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")- monkeypatch.setattr(ops, "_has_command", lambda command: command == "grep")-- ops.search("needle", path=str(home), target="content")-- pruned_command = next(command for command in env.commands if "-prune" in command)- for dirname in PROTECTED_NAMES:- # Path-scoped pruning: full protected path present, no basename-wide- # --exclude-dir for protected names.- assert ops._escape_shell_arg(str(home / dirname)) in pruned_command- assert f"--exclude-dir={dirname}" not in pruned_command- assert f"--exclude-dir='{dirname}'" not in pruned_command--[email protected]_onlydef test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypatch):"""A repo-internal directory literally named 'Downloads' must still besearched by the pruned grep path — the exact regression --exclude-dir had."""@@ -157,7 +81,6 @@ def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypprotected.mkdir()(protected / "secret.txt").write_text("needle protected\n")monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")ops = ShellFileOperations(LocalEnvironment(cwd=str(home)))monkeypatch.setattr(ops, "_has_command", lambda command: command == "grep")@@ -168,6 +91,7 @@ def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypassert not any(str(protected / "secret.txt") in p for p in matched_paths)[email protected]_onlydef test_remote_backend_never_prunes(tmp_path, monkeypatch):"""Non-local environments get no exclusions: platform facts describe thecontroller, not the execution host (macOS controller + Linux SSH backend@@ -178,7 +102,6 @@ def test_remote_backend_never_prunes(tmp_path, monkeypatch):env.is_local = False # remote/container-shaped backendops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")result = ops.search("*.txt", path=str(home), target="files")@@ -187,95 +110,11 @@ def test_remote_backend_never_prunes(tmp_path, monkeypatch):assert result.warning is None-def test_find_fallback_prunes_protected_directories(tmp_path, monkeypatch):- home = tmp_path / "Users" / "alice"- home.mkdir(parents=True)- env = RecordingEnvironment(home)- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")- monkeypatch.setattr(ops, "_has_command", lambda command: command == "find")-- ops.search("*.txt", path=str(home), target="files")-- find_commands = _find_commands(env.commands)- assert find_commands- for command in find_commands:- assert ops._escape_shell_arg(str(home / "Downloads")) in command- assert "-prune" in command---def _multi_root_protected_search(tmp_path, monkeypatch, engine):- home = tmp_path / "Users" / "alice"- downloads = home / "Downloads"- downloads.mkdir(parents=True)- env = RecordingEnvironment(home)- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")- monkeypatch.setattr(ops, "_has_command", lambda command: command == engine)- path_checks = 0-- def execute(command, cwd=None, **kwargs):- nonlocal path_checks- env.commands.append(command)- if command.startswith("test -e"):- path_checks += 1- output = "not_found\n" if path_checks == 1 else "exists\n"- return {"output": output, "returncode": 0}- if "--files" in command or command.startswith("set -o pipefail; find "):- return {"output": "", "returncode": 0}- return {"output": "yes\n", "returncode": 0}-- env.execute = execute- result = ops.search("*.txt", path=f"{home} {downloads}", target="files")- return ops, env, result, downloads---def test_rg_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(- tmp_path, monkeypatch-):- ops, env, result, downloads = _multi_root_protected_search(- tmp_path, monkeypatch, "rg"- )-- command = _rg_files_commands(env.commands)[0]- absolute_operand = downloads.as_posix() in command- anchored_operand = (- f"cd {ops._escape_shell_arg(downloads.parent.as_posix())} &&" in command- and " -- '.' 'Downloads' 2>/dev/null" in command- )- assert absolute_operand or anchored_operand- assert "!Downloads/**" not in command- assert "path contained 2 entries" in (result.warning or "")- assert "macOS protected folders" in (result.warning or "")- protected_warning = result.warning.split("macOS protected folders", 1)[1]- assert "Desktop" in protected_warning- assert "Downloads" not in protected_warning---def test_find_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(- tmp_path, monkeypatch-):- ops, env, result, downloads = _multi_root_protected_search(- tmp_path, monkeypatch, "find"- )-- command = _find_commands(env.commands)[0]- assert "Downloads" in command- assert re.search(r"(?<!! )-path '[^']*/Downloads'", command) is None- assert "path contained 2 entries" in (result.warning or "")- assert "macOS protected folders" in (result.warning or "")- protected_warning = result.warning.split("macOS protected folders", 1)[1]- assert "Desktop" in protected_warning- assert "Downloads" not in protected_warning--[email protected]_onlydef test_rg_multi_root_scopes_protected_globs_and_restores_absolute_paths(monkeypatch):env = RecordingEnvironment("/")ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", "/Users/alice")- monkeypatch.setattr(file_operations.sys, "platform", "darwin")def execute(command, cwd=None, **kwargs):env.commands.append(command)@@ -312,38 +151,11 @@ def test_rg_multi_root_scopes_protected_globs_and_restores_absolute_paths(monkey]-def test_rg_scoped_multi_root_handles_dot_spaces_and_overlapping_roots(monkeypatch):- env = RecordingEnvironment("/Users/alice/work space")- ops = ShellFileOperations(env)- monkeypatch.setattr(file_operations, "_HOME", "/Users/alice")- monkeypatch.setattr(file_operations.sys, "platform", "darwin")-- def execute(command, cwd=None, **kwargs):- env.commands.append(command)- if command.startswith("test -e"):- output = "not_found\n" if "'., /Users/alice'" in command else "exists\n"- return {"output": output, "returncode": 0}- if command.startswith("command -v rg"):- return {"output": "/usr/bin/rg\n", "returncode": 0}- if "--files" in command:- return {"output": "work space/local.txt\n", "returncode": 0}- raise AssertionError(command)-- env.execute = execute- result = ops.search("*.txt", path="., /Users/alice", target="files")-- command = _rg_files_commands(env.commands)[0]- assert "cd '/Users/alice' &&" in command- assert "'work space' '.'" in command- assert "'!Downloads/**'" in command- assert result.files == ["/Users/alice/work space/local.txt"]--[email protected]_onlydef test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monkeypatch):env = RecordingEnvironment("/Users/alice")ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", "/Users/alice")- monkeypatch.setattr(file_operations.sys, "platform", "darwin")def execute(command, cwd=None, **kwargs):env.commands.append(command)@@ -365,6 +177,7 @@ def test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monkeassert result.error is None[email protected]_onlydef test_real_ripgrep_does_not_descend_into_protected_folder(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"safe = home / "safe"@@ -374,7 +187,6 @@ def test_real_ripgrep_does_not_descend_into_protected_folder(tmp_path, monkeypat(safe / "visible.txt").write_text("needle")(protected / "protected.txt").write_text("needle")monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")ops = ShellFileOperations(LocalEnvironment(cwd=str(home)))result = ops.search("needle", path=str(home), target="content")diff --git a/tests/tools/test_mcp_bridge_single_failure.py b/tests/tools/test_mcp_bridge_single_failure.pyindex df168f3a953..daa202e2884 100644--- a/tests/tools/test_mcp_bridge_single_failure.py+++ b/tests/tools/test_mcp_bridge_single_failure.py@@ -60,10 +60,6 @@ class TestConnectCooldownHelpers:assert mcp_mod._server_connect_failures["bad"] == 2- def test_unknown_server_not_in_cooldown(self):- assert _mcp_discovery._connect_cooldown_active("never-seen") is False--@pytest.mark.skipif(not mcp_mod._MCP_AVAILABLE, reason="mcp SDK not installed")class TestRegisterMcpServersIsolation:"""register_mcp_servers must not re-spawn a server still in cooldown."""diff --git a/tests/tools/test_mcp_cimd.py b/tests/tools/test_mcp_cimd.pyindex 5a638d75496..794646ba1bd 100644--- a/tests/tools/test_mcp_cimd.py+++ b/tests/tools/test_mcp_cimd.py@@ -676,5 +676,3 @@ def test_timeout_on_a_cimd_flow_names_the_document_and_the_escape_hatch(monkeypaassert "cimd: false" in message-def test_timeout_without_cimd_stays_quiet_about_it(monkeypatch):- assert "cimd" not in _timed_out_waiter_message(monkeypatch, None).lower()diff --git a/tests/tools/test_mcp_config_whitespace_warning.py b/tests/tools/test_mcp_config_whitespace_warning.pyindex 71f9d9e8151..27b20993aa0 100644--- a/tests/tools/test_mcp_config_whitespace_warning.py+++ b/tests/tools/test_mcp_config_whitespace_warning.py@@ -9,7 +9,6 @@ import loggingimport pytest-from tools import mcp_toolfrom tools import mcp_tool_config as _mcp_configfrom tools.mcp_tool_config import _warn_hidden_whitespace@@ -45,9 +44,6 @@ def test_trailing_newline_in_header_flagged(caplog):assert not any("abc123" in m for m in messages)-def test_leading_space_in_url_flagged():- flagged = _warn_hidden_whitespace("srv", {"url": " https://example.com"})- assert flagged == ["url"]def test_whitespace_in_list_item_flagged_with_index():@@ -78,10 +74,6 @@ def test_non_string_values_ignored():assert flagged == []-def test_values_never_mutated():- config = {"headers": {"Authorization": "Bearer tok\n"}}- _warn_hidden_whitespace("srv", config)- assert config["headers"]["Authorization"] == "Bearer tok\n"def test_warning_deduped_per_process(caplog):@@ -96,12 +88,6 @@ def test_warning_deduped_per_process(caplog):assert len(warn_records) == 1-def test_distinct_servers_warned_separately(caplog):- with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):- _warn_hidden_whitespace("a", {"url": "https://x.com "})- _warn_hidden_whitespace("b", {"url": "https://x.com "})- warn_records = [r for r in caplog.records if "hidden" in r.getMessage()]- assert len(warn_records) == 2def test_load_mcp_config_emits_warning(tmp_path, monkeypatch, caplog):diff --git a/tests/tools/test_mcp_death_supervisor.py b/tests/tools/test_mcp_death_supervisor.pyindex 427f8d125e7..73f19c74313 100644--- a/tests/tools/test_mcp_death_supervisor.py+++ b/tests/tools/test_mcp_death_supervisor.py@@ -413,15 +413,6 @@ def test_register_starts_the_supervisor_once_and_reuses_it(monkeypatch, all_grouassert spawned[0].lines() == ["register 111", "register 222"]-def test_unregister_is_forwarded(monkeypatch, all_groups_alive):- fake = _FakeSupervisor()- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: fake)-- mcp_tool._update_death_supervisor("register", [111])- mcp_tool._update_death_supervisor("unregister", [111])-- assert fake.lines() == ["register 111", "unregister 111"]- assert mcp_tool._supervised_pgids == set()def test_supervisor_is_released_once_nothing_is_left_to_reap(monkeypatch, all_groups_alive):diff --git a/tests/tools/test_mcp_discovery_cross_process.py b/tests/tools/test_mcp_discovery_cross_process.pydeleted file mode 100644index bb2a006ee3a..00000000000--- a/tests/tools/test_mcp_discovery_cross_process.py+++ /dev/null@@ -1,189 +0,0 @@-"""Cross-process regression coverage for MCP discovery serialization.--Two independent Hermes processes can start MCP discovery at the same time-(dashboard and gateway startup). The losing process must wait for the shared-lock and then perform its own local discovery; another process's registry is-not usable because ``_servers`` is process-local.-"""--import json-import os-from pathlib import Path-import subprocess-import sys-import textwrap-import time---_REPO_ROOT = Path(__file__).resolve().parents[2]---def _wait_for_file(path: Path, *, timeout: float = 10.0) -> None:- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if path.exists():- return- time.sleep(0.01)- raise AssertionError(f"timed out waiting for {path}")---def test_two_processes_each_complete_local_mcp_discovery(tmp_path):- """A lock loser waits, acquires the lock, and builds its own registry."""- hermes_home = tmp_path / "hermes-home"- hermes_home.mkdir()-- holder_ready = tmp_path / "holder-ready"- release_holder = tmp_path / "release-holder"- loser_started = tmp_path / "loser-started"- holder_output = tmp_path / "holder.json"- loser_output = tmp_path / "loser.json"- child_script = tmp_path / "mcp-discovery-child.py"-- child_script.write_text(- textwrap.dedent(- """- import json- import os- from pathlib import Path- import sys- import time- from types import SimpleNamespace-- repo_root, role, ready_arg, release_arg, started_arg, output_arg = sys.argv[1:]- sys.path.insert(0, repo_root)-- import tools.mcp_tool as mcp_tool- from tools import mcp_tool_config as _mcp_config- from tools import mcp_tool_discovery as _mcp_discovery-- ready = Path(ready_arg)- release = Path(release_arg)- started = Path(started_arg)- output = Path(output_arg)-- mcp_tool._MCP_AVAILABLE = True- mcp_tool._MCP_DISCOVERY_LOCK_PATH = None- mcp_tool._MCP_DISCOVERY_LOCK_MAX_RETRIES = 200- mcp_tool._MCP_DISCOVERY_LOCK_RETRY_DELAY_S = 0.01- mcp_tool._servers.clear()-- config = {- "test_srv": {- "command": "fake",- "enabled": True,- }- }- _mcp_config._load_mcp_config = lambda: config-- def fake_register_mcp_servers(servers):- tool_name = "mcp__test_srv__ping"- mcp_tool._servers["test_srv"] = SimpleNamespace(- _registered_tool_names=[tool_name],- )-- if role == "holder":- ready.write_text("1", encoding="utf-8")- deadline = time.monotonic() + 10.0- while not release.exists():- if time.monotonic() >= deadline:- raise RuntimeError("holder release signal timed out")- time.sleep(0.01)-- return [tool_name]-- _mcp_discovery.register_mcp_servers = fake_register_mcp_servers- started.write_text("1", encoding="utf-8")-- result = _mcp_discovery.discover_mcp_tools()- server = mcp_tool._servers.get("test_srv")- output.write_text(- json.dumps(- {- "pid": os.getpid(),- "result": result,- "server_present": server is not None,- "registered_tools": (- list(server._registered_tool_names)- if server is not None- else []- ),- }- ),- encoding="utf-8",- )- """- ),- encoding="utf-8",- )-- env = os.environ.copy()- env["HERMES_HOME"] = str(hermes_home)-- holder_started = tmp_path / "holder-started"- holder = subprocess.Popen(- [- sys.executable,- str(child_script),- str(_REPO_ROOT),- "holder",- str(holder_ready),- str(release_holder),- str(holder_started),- str(holder_output),- ],- env=env,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- loser = None-- try:- _wait_for_file(holder_ready)-- loser = subprocess.Popen(- [- sys.executable,- str(child_script),- str(_REPO_ROOT),- "loser",- str(holder_ready),- str(release_holder),- str(loser_started),- str(loser_output),- ],- env=env,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- _wait_for_file(loser_started)-- # The loser must not finish from an empty process-local registry while- # the holder owns the lock.- time.sleep(0.1)- assert loser.poll() is None- assert not loser_output.exists()-- release_holder.write_text("1", encoding="utf-8")-- holder_stdout, holder_stderr = holder.communicate(timeout=15)- loser_stdout, loser_stderr = loser.communicate(timeout=15)- assert holder.returncode == 0, holder_stdout + holder_stderr- assert loser.returncode == 0, loser_stdout + loser_stderr- finally:- release_holder.touch(exist_ok=True)- for process in (holder, loser):- if process is not None and process.poll() is None:- process.terminate()- process.wait(timeout=5)-- expected_tools = ["mcp__test_srv__ping"]- holder_result = json.loads(holder_output.read_text(encoding="utf-8"))- loser_result = json.loads(loser_output.read_text(encoding="utf-8"))-- assert holder_result["pid"] != loser_result["pid"]- for result in (holder_result, loser_result):- assert result["result"] == expected_tools- assert result["server_present"] is True- assert result["registered_tools"] == expected_toolsdiff --git a/tests/tools/test_mcp_dynamic_discovery.py b/tests/tools/test_mcp_dynamic_discovery.pyindex 912b7de2fa9..7fdfe0fd267 100644--- a/tests/tools/test_mcp_dynamic_discovery.py+++ b/tests/tools/test_mcp_dynamic_discovery.py@@ -227,17 +227,3 @@ class TestMessageHandler:mock_schedule.assert_not_called()-class TestDeregister:- """Tests for ToolRegistry.deregister."""-- def test_removes_tool(self):- reg = ToolRegistry()- reg.register(name="foo", toolset="ts1", schema={}, handler=lambda x: x)- assert "foo" in reg.get_all_tool_names()- reg.deregister("foo")- assert "foo" not in reg.get_all_tool_names()--- def test_noop_for_unknown_tool(self):- reg = ToolRegistry()- reg.deregister("nonexistent") # Should not raisediff --git a/tests/tools/test_mcp_elicitation.py b/tests/tools/test_mcp_elicitation.pyindex 4de0f2b58a9..4a398139771 100644--- a/tests/tools/test_mcp_elicitation.py+++ b/tests/tools/test_mcp_elicitation.py@@ -18,7 +18,7 @@ pytest.importorskip("mcp.types")from mcp.types import ElicitResult # noqa: E402 -- after importorskip-from tools.mcp_tool_sampling import ElicitationHandler, _format_elicitation_schema_summary # noqa: E402+from tools.mcp_tool_sampling import ElicitationHandler # noqa: E402def _form_params(message="please confirm", schema=None):@@ -46,23 +46,6 @@ def _url_params(message="open this url", url="https://example.com/auth", elicita)-class TestSchemaSummary:- def test_empty_schema_falls_back_to_generic_message(self):- out = _format_elicitation_schema_summary({}, "pay")- assert "pay" in out- assert "Approval requested" in out-- def test_properties_render_with_type_and_description(self):- schema = {- "type": "object",- "properties": {- "amount": {"type": "string", "description": "USD amount"},- "recipient": {"type": "string"},- },- }- out = _format_elicitation_schema_summary(schema, "pay")- assert "amount (string): USD amount" in out- assert "recipient (string)" in outclass TestElicitationHandlerFormMode:@@ -83,39 +66,6 @@ class TestElicitationHandlerFormMode:assert handler.metrics["declined"] == 0- @pytest.mark.usefixtures("require_mcp_2_sdk")- def test_schema_read_from_real_sdk_params_reaches_the_summary(self):- """The requested schema must be read off the *real* SDK model.-- Every other test here builds a duck-typed ``SimpleNamespace``, which- cannot catch a field rename in the SDK — and 2.0 renamed this field- (``requestedSchema`` -> ``requested_schema``). Pinning one case to the- actual model is what proves the elicitation path still reads the- schema after the migration, rather than silently summarising an empty- one.- """- from mcp.types import ElicitRequestFormParams-- params = ElicitRequestFormParams(- message="authorize a payment of $0.50",- requested_schema={- "type": "object",- "properties": {"card_number": {"type": "string"}},- },- )- handler = ElicitationHandler("pay", {"timeout": 5})- captured: dict = {}-- def _capture(*args, **kwargs):- captured["description"] = kwargs.get("description") or (- args[1] if len(args) > 1 else ""- )- return "decline"-- with patch("tools.approval_prompt.request_elicitation_consent", _capture):- asyncio.run(handler(context=None, params=params))-- assert "card_number" in (captured.get("description") or ""), captureddef test_cancel_propagates_through(self):"""request_elicitation_consent returns 'cancel' when the gateway@@ -186,22 +136,6 @@ class TestElicitationHandlerFailureModes:assert handler.metrics["errors"] == 1-class TestElicitationHandlerWiring:- def test_session_kwargs_returns_callback(self):- handler = ElicitationHandler("pay", {})- kwargs = handler.session_kwargs()- assert kwargs == {"elicitation_callback": handler}--- def test_disabled_config_does_not_construct_handler(self):- """The server task initializer checks ``elicitation.enabled`` --- an explicit ``False`` should suppress handler creation. The unit- of that decision lives in MCPServerTask, but the handler itself- must remain harmless to instantiate with arbitrary config."""- handler = ElicitationHandler("pay", {"enabled": False, "timeout": 10})- # Just confirm it instantiates and reads timeout; the gate lives- # at the higher layer.- assert handler.timeout == 10class TestElicitationHandlerContextBridge:diff --git a/tests/tools/test_mcp_empty_error_message.py b/tests/tools/test_mcp_empty_error_message.pydeleted file mode 100644index adef32280a2..00000000000--- a/tests/tools/test_mcp_empty_error_message.py+++ /dev/null@@ -1,47 +0,0 @@-"""Regression tests for MCP error messages when str(exc) is empty.--Issue #19417: ClosedResourceError (and similar exceptions raised without a-message argument) produced ``MCP call failed: ClosedResourceError: `` with-nothing after the colon, making debugging impossible.--Fix: ``_exc_str()`` falls back to ``repr(exc)`` when ``str(exc)`` is empty.-"""---from tools.mcp_tool_common import _exc_str, _sanitize_error---# ----------------------------------------------------------------------------# _exc_str unit tests-# ------------------------------------------------------------------------------class _EmptyMessageError(Exception):- """Exception whose __str__ returns empty string (like anyio.ClosedResourceError)."""-- def __str__(self):- return ""---class _NormalError(Exception):- pass---def test_exc_str_returns_str_when_nonempty():- exc = _NormalError("something broke")- assert _exc_str(exc) == "something broke"---# ----------------------------------------------------------------------------# Integration: error message format in _sanitize_error-# ------------------------------------------------------------------------------def test_error_message_preserves_normal_exception_text():- """Normal exceptions should still show their message text."""- exc = _NormalError("connection refused")- error_msg = _sanitize_error(- f"MCP call failed: {type(exc).__name__}: {_exc_str(exc)}"- )- assert "connection refused" in error_msg- assert "_NormalError" in error_msgdiff --git a/tests/tools/test_mcp_identity_header.py b/tests/tools/test_mcp_identity_header.pyindex fd062933e9a..76bb3452c63 100644--- a/tests/tools/test_mcp_identity_header.py+++ b/tests/tools/test_mcp_identity_header.py@@ -33,7 +33,6 @@ import asyncioimport loggingfrom unittest.mock import MagicMock, patch-import pytest# ---------------------------------------------------------------------------@@ -232,23 +231,6 @@ class TestHTTPIdentityHeader:assert headers.get("x-user-id") == "explicit-wins"assert "X-User-Id" not in headers- def test_profile_mode_header_attached(self):- from tools.mcp_tool import MCPServerTask-- server = MCPServerTask("remote")- with patch(- "hermes_cli.profiles.get_active_profile_name",- return_value="workbot",- ):- captured = _drive_http(server, {- "url": "https://example.com/mcp",- "identity_header": {- "name": "X-Hermes-Profile",- "value_from": "profile",- },- })- headers = captured.get("headers") or {}- assert headers.get("X-Hermes-Profile") == "workbot"# ---------------------------------------------------------------------------@@ -256,28 +238,3 @@ class TestHTTPIdentityHeader:# ----------------------------------------------------------------------------class TestStdioIdentityHeader:- def test_stdio_warns_and_ignores(self, caplog):- """identity_header on a stdio server logs a warning and does not- break the transport path (headers don't exist on stdio)."""- from tools.mcp_tool import MCPServerTask-- server = MCPServerTask("local")-- async def _drive():- # Force the SDK-unavailable fast path so no subprocess spawns;- # the warning must fire before the availability check.- with patch("tools.mcp_tool._MCP_AVAILABLE", False):- await server._run_stdio({- "command": "echo",- "identity_header": {"name": "X-User-Id", "value": "a"},- })-- with caplog.at_level(logging.WARNING):- with pytest.raises(ImportError):- asyncio.run(_drive())-- assert any(- "identity_header" in r.message and "stdio" in r.message- for r in caplog.records- )diff --git a/tests/tools/test_mcp_invalid_url.py b/tests/tools/test_mcp_invalid_url.pyindex ffe8ea1e1c3..58c27ffc516 100644--- a/tests/tools/test_mcp_invalid_url.py+++ b/tests/tools/test_mcp_invalid_url.py@@ -50,16 +50,10 @@ class TestInvalidUrlsRejected:"""Every broken shape must raise ``InvalidMcpUrlError`` with a clear message."""def test_none_rejected(self):- with pytest.raises(InvalidMcpUrlError, match="context7.*expected a string"):+ with pytest.raises(InvalidMcpUrlError, match="context7"):_validate_remote_mcp_url("context7", None)- def test_dict_rejected(self):- with pytest.raises(InvalidMcpUrlError, match="expected a string, got dict"):- _validate_remote_mcp_url("ctx", {"url": "nested"})- def test_int_rejected(self):- with pytest.raises(InvalidMcpUrlError, match="expected a string, got int"):- _validate_remote_mcp_url("ctx", 8080)def test_error_mentions_server_name(self):@@ -68,13 +62,3 @@ class TestInvalidUrlsRejected:_validate_remote_mcp_url("my-weird-server", "not a url at all")-class TestErrorIsValueError:- """InvalidMcpUrlError must be a ValueError for broad downstream catch blocks."""-- def test_is_value_error(self):- try:- _validate_remote_mcp_url("ctx", "garbage")- except ValueError:- pass # expected- else:- pytest.fail("expected ValueError")diff --git a/tests/tools/test_mcp_lazy_start.py b/tests/tools/test_mcp_lazy_start.pyindex adfe451d500..f12cddf5dd4 100644--- a/tests/tools/test_mcp_lazy_start.py+++ b/tests/tools/test_mcp_lazy_start.py@@ -325,15 +325,6 @@ class TestCacheLoadDescriptionScan:mock_scan.assert_called_once_with("playwright", "browser_navigate", "Navigate")-class TestResolveServerLazy:- def test_default_off(self):- assert _mcp_discovery._resolve_server_lazy("s", {"command": "npx"}) is False-- def test_explicit_true(self):- assert _mcp_discovery._resolve_server_lazy("s", {"command": "npx", "lazy": True}) is True-- def test_explicit_false(self):- assert _mcp_discovery._resolve_server_lazy("s", {"command": "npx", "lazy": False}) is Falseclass TestLazyMcpStatus:@@ -374,7 +365,6 @@ class TestLazyMcpStatus:summaries = [r.getMessage() for r in caplog.records if "tool(s) from" in r.getMessage()]assert summaries and all("failed" not in m for m in summaries), summaries- assert any("1 lazy, not spawned yet" in m for m in summaries), summariesassert (status["playwright"]["status"], status["playwright"]["tools"],status["playwright"]["connected"]) == ("lazy", len(cached), False)assert status["eager"]["status"] == "configured" and status["eager"]["tools"] == 0diff --git a/tests/tools/test_mcp_liveness.py b/tests/tools/test_mcp_liveness.pyindex cce3d027c9e..ac0a94c7680 100644--- a/tests/tools/test_mcp_liveness.py+++ b/tests/tools/test_mcp_liveness.py@@ -4,13 +4,11 @@ import jsonimport loggingimport osimport sys-from types import SimpleNamespaceimport pytestfrom hermes_platform import declaration-from hermes_platform.resolver.availability import Availability-from tools.mcp_liveness import describe, parse_liveness+from tools.mcp_liveness import parse_livenessdef _decl(tmp_path, *, min_version=None):@@ -35,41 +33,24 @@ def test_parse_liveness_contract():assert (live.kind, live.path, live.url_field, live.token_field, live.pid_field) == ("server_json", "/tmp/example.json", "endpoint", "secret", "process")- with pytest.raises(ValueError, match="unknown liveness kind"):+ with pytest.raises(ValueError):parse_liveness({"kind": "unknown"})defaulted = parse_liveness({"kind": "server_json", "path": "/tmp/example.json"})assert (defaulted.url_field, defaulted.token_field, defaulted.pid_field) == ("http", "token", "pid")partial = parse_liveness({"kind": "server_json", "path": "/tmp/example.json", "fields": {"url": "endpoint"}})assert (partial.url_field, partial.token_field, partial.pid_field) == ("endpoint", "token", "pid")- with pytest.raises(ValueError, match="may only override"):+ with pytest.raises(ValueError):parse_liveness({"kind": "server_json", "path": "/tmp/example.json", "fields": {"port": "p"}})-def test_invalid_registered_liveness_degrades_to_static(monkeypatch, caplog):+def test_invalid_registered_liveness_degrades_to_static(monkeypatch):import hermes_cli.agent_plugins as agent_pluginsfrom tools.mcp_liveness import liveness_formonkeypatch.setattr(agent_plugins, "liveness_for", lambda name: {"kind": "server_json"}, raising=False)- caplog.set_level(logging.WARNING)assert liveness_for("example-server").kind == "static"- assert any("invalid liveness declaration" in record.getMessage() for record in caplog.records)--- ("state", "available", "fragment"),- [- ("app_not_running", Availability("available"), "is not running"),- ("endpoint_unavailable", Availability("available"), "local endpoint is unavailable"),- ("no_interactive_session", Availability("available"), "interactive desktop session"),- ("version_too_old", Availability("version_too_old", version="1.2", min_version="2.0"), "version 1.2 is too old"),- ("missing_app", Availability("missing_app"), "is not installed"),- ],-)-def test_describe_has_one_state_sentence_and_one_action(tmp_path, state, available, fragment):- sentence = describe(_decl(tmp_path), available, state)- assert sentence.startswith("Example App")- assert fragment in sentence- assert sentence.count("try again") <= 1++def test_live_endpoint_reloads_file_and_registers_token_before_use(tmp_path, monkeypatch, caplog):@@ -182,10 +163,3 @@ def test_connected_interactive_session_server_is_offerable_from_a_service_sessiodeclaration.unregister("example-server")-def test_undeclared_error_text_is_unchanged(monkeypatch):- from tools import mcp_tool, mcp_tool_discovery, mcp_tool_handlers-- monkeypatch.setattr(mcp_tool_discovery, "_get_connected_server_for_call", lambda name: None)- monkeypatch.setattr(mcp_tool, "_bump_server_error", lambda name, **kwargs: None)- _server, error = mcp_tool_handlers._acquire_call_server("plain-server", 0)- assert json.loads(error)["error"] == "MCP server 'plain-server' is not connected"diff --git a/tests/tools/test_mcp_liveness_catalog.py b/tests/tools/test_mcp_liveness_catalog.pyindex 337869d32d3..278e5399e24 100644--- a/tests/tools/test_mcp_liveness_catalog.py+++ b/tests/tools/test_mcp_liveness_catalog.py@@ -50,7 +50,7 @@ def test_hidden_declared_server_appears_in_listing_and_empty_summary(tmp_path, mdeclaration.unregister(server)assert first == secondassert first[1] == "full"- assert "example-hidden (1 tools unavailable: Example App is not installed." in first[0]+ assert "example-hidden" in first[0]source = result["results"][0]["available_sources"][0]assert source["name"] == server and source["tool_count"] == 1assert "Example App is not installed." in source["unavailable"]diff --git a/tests/tools/test_mcp_npx_cached_bin.py b/tests/tools/test_mcp_npx_cached_bin.pyindex 1773688e905..b10320c0e58 100644--- a/tests/tools/test_mcp_npx_cached_bin.py+++ b/tests/tools/test_mcp_npx_cached_bin.py@@ -143,36 +143,6 @@ def test_osv_preflight_runs_before_the_swap():assert _infer_ecosystem("/home/u/.npm/_npx/abc/node_modules/.bin/mcp-linear") is None-def test_swap_happens_after_the_osv_call_in_source():- """Structural guard for the ordering above.-- The swap and the preflight live in one async function; a future edit that- moves the swap earlier would disable the malware gate silently, and no- unit test of either piece alone would notice.- """- from pathlib import Path as _P-- src = _P(__file__).resolve().parents[2] / "tools" / "mcp_tool.py"- text = src.read_text(encoding="utf-8")- osv_needle = "check_package_for_malware, command, args"- swap_needle = "cached = _npx_cached_bin(args)"- # Report a rename explicitly: a bare .index() ValueError here reads like a- # broken test rather than "someone renamed the thing this guards".- assert osv_needle in text, (- f"cannot find the OSV preflight call ({osv_needle!r}) — it was renamed; "- "update this guard and re-verify the swap still happens after it"- )- assert swap_needle in text, (- f"cannot find the npx swap ({swap_needle!r}) — it was renamed; update "- "this guard and re-verify it still happens after the OSV preflight"- )-- assert text.index(osv_needle) < text.index(swap_needle), (- "the npx swap now precedes the OSV malware preflight, which silently "- "disables it: _infer_ecosystem keys off the command basename being "- "npx/uvx/pipx, so a rewritten command yields no ecosystem and "- "check_package_for_malware returns None"- )def test_windows_selects_launchers_never_the_sh_script():@@ -194,11 +164,6 @@ def test_windows_selects_launchers_never_the_sh_script():assert _npx_bin_candidates("/bin", "mcp-linear", windows=False) == ["/bin/mcp-linear"]-def test_posix_resolution_uses_the_helper(tmp_path):- """The resolver honours the helper's ordering (POSIX path end-to-end)."""- target = _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "i.js"})-- assert _npx_cached_bin(["-y", "mcp-linear"]) == (str(target), [])def test_flag_after_the_spec_is_left_to_npx(tmp_path):diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.pyindex 38a321b32b1..ae0a68d6eae 100644--- a/tests/tools/test_mcp_oauth.py+++ b/tests/tools/test_mcp_oauth.py@@ -22,12 +22,10 @@ from tools.mcp_oauth import (OAuthNonInteractiveError,build_oauth_auth,remove_oauth_tokens,- _cached_client_info,_cached_redirect,_can_open_browser,_is_interactive,_make_callback_handler,- _make_redirect_handler,_paste_callback_reader,)@@ -58,7 +56,6 @@ def _hit_callback_when_ready(url: str, timeout: float = 15.0) -> None:but NOT listening until ``_wait_for_callback`` adopts it, so attemptsbefore adoption fail fast with a connection error."""- import timeimport urllib.requestdeadline = time.monotonic() + timeout@@ -243,31 +240,6 @@ class TestBuildOAuthAuth:assert provider is not Noneassert provider.context.client_metadata.scope == "read write admin"- @pytest.mark.asyncio- async def test_token_exchange_includes_secret_for_dcr_secret_client(self, tmp_path, monkeypatch):- from mcp.shared.auth import OAuthClientInformationFull- from urllib.parse import parse_qs-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- _set_interactive_stdin(monkeypatch)- provider = build_oauth_auth("supabase", "https://mcp.supabase.com/mcp")- assert provider is not None- redirect_uris = provider.context.client_metadata.redirect_uris- assert redirect_uris is not None- provider.context.client_info = OAuthClientInformationFull.model_validate({- "client_id": "client-id",- "client_secret": "secret",- "redirect_uris": [str(redirect_uris[0])],- "token_endpoint_auth_method": "none",- })-- request = await provider._exchange_token_authorization_code("auth-code", "verifier")- body = parse_qs(request.content.decode())-- assert body["client_id"] == ["client-id"]- assert body["client_secret"] == ["secret"]- assert provider.context.client_info is not None- assert provider.context.client_info.token_endpoint_auth_method == "client_secret_post"@pytest.mark.asyncioasync def test_token_response_accepts_201_created(self, tmp_path, monkeypatch):@@ -292,27 +264,6 @@ class TestBuildOAuthAuth:assert token_path.exists()assert json.loads(token_path.read_text())["access_token"] == "access-token"- @pytest.mark.asyncio- async def test_malformed_201_token_response_does_not_expose_body(- self, tmp_path, monkeypatch- ):- import httpx- from mcp.client.auth.oauth2 import OAuthTokenError-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- _set_interactive_stdin(monkeypatch)- provider = build_oauth_auth("supabase", "https://mcp.supabase.com/mcp")- assert provider is not None-- with pytest.raises(OAuthTokenError, match="^Invalid token response$") as exc_info:- await provider._handle_token_response(- httpx.Response(- 201,- content=b'{"access_token": {"secret": "access-secret"}}',- )- )-- assert "access-secret" not in str(exc_info.value)@pytest.mark.asyncioasync def test_failed_token_exchange_carries_a_bounded_redacted_excerpt(self, tmp_path, monkeypatch):@@ -331,77 +282,14 @@ class TestBuildOAuthAuth:await provider._handle_token_response(httpx.Response(403, content=waf.encode()))message = str(exc_info.value)- assert message.startswith("Token exchange failed (403): ERROR 403 ERROR Request blocked.")+ assert "Request blocked." in messageassert "[REDACTED]" in messageassert "<" not in message and "leaked-bearer-token" not in messageassert len(message) <= len("Token exchange failed (403): ") + 200assert provider.context.current_tokens is None- @pytest.mark.asyncio- async def test_token_read_error_does_not_expose_body(self, tmp_path, monkeypatch):- import httpx- from mcp.client.auth.oauth2 import OAuthTokenError-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- _set_interactive_stdin(monkeypatch)- provider = build_oauth_auth("supabase", "https://mcp.supabase.com/mcp")- assert provider is not None-- class _ReadErrorResponse:- status_code = 201-- async def aread(self):- raise httpx.ReadError("access-secret refresh-secret")-- with pytest.raises(OAuthTokenError, match="^Invalid token response$") as exc_info:- await provider._handle_token_response(_ReadErrorResponse())-- assert "access-secret" not in str(exc_info.value)- assert "refresh-secret" not in str(exc_info.value)-- @pytest.mark.asyncio- async def test_malformed_201_refresh_response_clears_tokens(- self, tmp_path, monkeypatch, caplog- ):- import logging- import httpx-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- _set_interactive_stdin(monkeypatch)- provider = build_oauth_auth("supabase", "https://mcp.supabase.com/mcp")- assert provider is not None- provider.context.current_tokens = object()-- response = httpx.Response(- 201, content=b'{"refresh_token": "refresh-secret"}'- )- with caplog.at_level(logging.WARNING, logger="tools.mcp_oauth"):- result = await provider._handle_refresh_response(response)-- assert result is False- assert provider.context.current_tokens is None- assert "refresh-secret" not in caplog.text-- @pytest.mark.asyncio- async def test_refresh_read_error_clears_tokens(self, tmp_path, monkeypatch):- import httpx-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- _set_interactive_stdin(monkeypatch)- provider = build_oauth_auth("supabase", "https://mcp.supabase.com/mcp")- assert provider is not None- provider.context.current_tokens = object()- class _ReadErrorResponse:- status_code = 201- async def aread(self):- raise httpx.ReadError("body read failed")-- result = await provider._handle_refresh_response(_ReadErrorResponse())-- assert result is False- assert provider.context.current_tokens is None# ---------------------------------------------------------------------------@@ -423,64 +311,6 @@ class TestUtilities:assert _can_open_browser() is True-class TestRedirectHandlerSshHint:- """_make_redirect_handler must print an SSH tunnel hint on remote sessions."""-- def _run(self, coro):- return asyncio.get_event_loop().run_until_complete(coro)-- def test_ssh_hint_shown_on_ssh_session(self, monkeypatch, capsys):- import tools.mcp_oauth as mco- monkeypatch.setattr(mco, "_is_interactive", lambda: True)- monkeypatch.setenv("SSH_CLIENT", "1.2.3.4 1234 22")- monkeypatch.delenv("SSH_TTY", raising=False)- monkeypatch.setattr(mco, "_can_open_browser", lambda: False)-- handler = _make_redirect_handler(49200)- self._run(handler("https://example.com/auth?foo=bar"))-- err = capsys.readouterr().err- assert "49200" in err- assert "ssh -N -L" in err- assert "Remote session detected" in err-- def test_ssh_hint_names_the_configured_redirect_host(self, monkeypatch, capsys):- """A pre-registered client (Asana) registers ``http://localhost:<port>/callback`` verbatim,- so the remote-session hint must name the same host the provider redirects to."""- import tools.mcp_oauth as mco- monkeypatch.setattr(mco, "_is_interactive", lambda: True)- monkeypatch.setenv("SSH_CLIENT", "1.2.3.4 1234 22")- monkeypatch.setattr(mco, "_can_open_browser", lambda: False)-- handler = _make_redirect_handler(27890, redirect_host="localhost")- self._run(handler("https://mcp.example/authorize"))-- err = capsys.readouterr().err- assert "http://localhost:27890/callback" in err- assert "http://127.0.0.1:27890/callback" not in err-- def test_configured_redirect_uri_shows_proxy_hint_not_tunnel(self, monkeypatch, capsys):- """With a proxy redirect_uri, the SSH hint must not push the loopback tunnel.-- The Funnel/proxy callback reaches this machine on its own, so the- ``ssh -N -L`` guidance would be actively misleading.- """- import tools.mcp_oauth as mco- monkeypatch.setattr(mco, "_oauth_port", 49203)- monkeypatch.setattr(mco, "_is_interactive", lambda: True)- monkeypatch.setenv("SSH_CLIENT", "1.2.3.4 1234 22")- monkeypatch.setattr(mco, "_can_open_browser", lambda: False)-- handler = _make_redirect_handler(- 49203, redirect_uri="https://oauth.example.ts.net/callback"- )- self._run(handler("https://example.com/auth"))-- err = capsys.readouterr().err- assert "https://oauth.example.ts.net/callback" in err- assert "no SSH tunnel needed" in err- assert "ssh -N -L" not in err- assert "127.0.0.1" not in err# ---------------------------------------------------------------------------@@ -724,15 +554,6 @@ class TestCallbackPortReservation:storage = self._seed_client_info(tmp_path, payload)assert _cached_redirect(storage) == (None, None)- @pytest.mark.parametrize("payload", [["not", "a", "dict"], "just-a-string", 123])- def test_non_dict_client_info_degrades_to_fresh_registration(self, tmp_path, payload):- """The MCP SDK calls storage.get_client_info() while building OAuthClientProvider, one- step after _cached_redirect. A non-object client.json must read as "no registration"- on both paths (fresh DCR + CIMD still eligible), not AttributeError out of auth init- (#112568)."""- storage = self._seed_client_info(tmp_path, payload)- assert _cached_client_info(storage) is None- assert asyncio.run(storage.get_client_info()) is None@pytest.mark.parametrize("payload", [{"client_id": "c", "redirect_uris": ["http://127.0.0.1:abc/callback"]}, # the issue's repro@@ -859,16 +680,6 @@ class TestInvalidateTokensOnClientChange:info = json.loads((d / "chg-server.client.json").read_text())assert info["client_id"] == "client-b"- def test_preregister_flow_same_client_keeps_tokens(self, tmp_path, monkeypatch):- pytest.importorskip("mcp")- from tools.mcp_oauth import (- _build_client_metadata, _maybe_preregister_client,- )- storage, d = self._seed(tmp_path, monkeypatch)- cfg = {"client_id": "client-a", "_resolved_port": 1455}- meta = _build_client_metadata(dict(cfg))- _maybe_preregister_client(storage, cfg, meta)- assert (d / "chg-server.json").exists()# ---------------------------------------------------------------------------@@ -1146,26 +957,8 @@ class TestPasteCallbackReader:class TestWaitForCallbackPasteIntegration:"""_wait_for_callback offers the paste prompt only when interactive."""- def test_paste_prompt_shown_on_tty(self, monkeypatch, capsys):- import tools.mcp_oauth as mod- mod._oauth_port = _find_free_port()- monkeypatch.setattr(mod, "_is_interactive", lambda: True)- # Make stdin readline block forever so HTTP listener path drives the test;- # we just want to verify the prompt was printed and the thread spawned.- def block_forever():- import threading- threading.Event().wait()- monkeypatch.setattr("sys.stdin", MagicMock(readline=block_forever))-- async def instant_sleep(_):- pass- with patch.object(mod.asyncio, "sleep", instant_sleep):- with pytest.raises(OAuthNonInteractiveError):- asyncio.run(_wait_for_callback())- err = capsys.readouterr().err- assert "paste the redirect URL" in err- def test_paste_prompt_NOT_shown_when_interactivity_suppressed(self, monkeypatch, capsys):+ def test_paste_prompt_NOT_shown_when_interactivity_suppressed(self, monkeypatch):"""Background MCP discovery must not race the CLI/TUI stdin reader."""import tools.mcp_oauth as mod@@ -1181,8 +974,6 @@ class TestWaitForCallbackPasteIntegration:with mod.suppress_interactive_oauth():with pytest.raises(OAuthNonInteractiveError):asyncio.run(_wait_for_callback())- err = capsys.readouterr().err- assert "paste the redirect URL" not in errmock_stdin.readline.assert_not_called()@@ -1253,23 +1044,6 @@ class TestPoisonClientRegistration:assert (d / "srv.json").read_text() == '{"access_token": "keep-me"}'-def test_wait_for_callback_port_in_use_reports_clear_error(monkeypatch):- """A busy loopback callback port surfaces a clear 'already in use' error,- not a misleading 'timed out'. Guards the stale-comment fix where the branch- also wrongly claimed build_oauth_auth had started a server to poll."""- import tools.mcp_oauth as mo-- monkeypatch.setattr(mo, "_is_interactive", lambda: True)- with patch.object(mo, "_oauth_port", 54321), patch.object(- mo, "HTTPServer", side_effect=OSError("address already in use")- ):- with pytest.raises(mo.OAuthNonInteractiveError) as excinfo:- asyncio.run(_wait_for_callback())-- msg = str(excinfo.value)- assert "54321" in msg- assert "already in use" in msg- assert "timed out" not in msgdef test_cancelled_waiter_releases_pinned_port_for_retry(monkeypatch):diff --git a/tests/tools/test_mcp_oauth_bidirectional.py b/tests/tools/test_mcp_oauth_bidirectional.pyindex 7759c465c5f..6ee67036102 100644--- a/tests/tools/test_mcp_oauth_bidirectional.py+++ b/tests/tools/test_mcp_oauth_bidirectional.py@@ -36,89 +36,6 @@ import pytestpytest.importorskip("mcp.client.auth.oauth2", reason="MCP SDK 1.26.0+ required")-async def test_hermes_provider_forwards_asend_values(tmp_path, monkeypatch):- """The wrapper MUST forward ``.asend(response)`` into the inner generator.-- This is the primary regression test. With the broken wrapper, the inner- SDK generator sees ``response = None`` and raises ``AttributeError`` at- ``oauth2.py:505``. With the correct bridge, a 200 response finishes the- flow cleanly (``StopAsyncIteration``).- """- # The SDK's httpx flavour (httpx2 on mcp >= 2.0): the provider is an- # Auth subclass from that module and its auth_flow only accepts its own- # Request/Response types.- from tools.mcp_tool import sdk_httpx- httpx = sdk_httpx()- from mcp.shared.auth import OAuthClientMetadata, OAuthToken- from pydantic import AnyUrl-- from tools.mcp_oauth import HermesTokenStorage- from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS, reset_manager_for_tests-- assert _HERMES_PROVIDER_CLS is not None, "SDK OAuth types must be available"-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- reset_manager_for_tests()-- # Seed a valid-looking token so the SDK's _initialize loads something and- # can_refresh_token() is True (though we don't exercise refresh here — we- # go straight through the 200 path).- storage = HermesTokenStorage("srv")- await storage.set_tokens(- OAuthToken(- access_token="old_access",- token_type="Bearer",- expires_in=3600,- refresh_token="old_refresh",- )- )- # Also seed client_info so the SDK doesn't attempt registration.- from mcp.shared.auth import OAuthClientInformationFull-- await storage.set_client_info(- OAuthClientInformationFull(- client_id="test-client",- redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],- grant_types=["authorization_code", "refresh_token"],- response_types=["code"],- token_endpoint_auth_method="none",- )- )-- metadata = OAuthClientMetadata(- redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],- client_name="Hermes Agent",- )- provider = _HERMES_PROVIDER_CLS(- server_name="srv",- server_url="https://example.com/mcp",- client_metadata=metadata,- storage=storage,- redirect_handler=_noop_redirect,- callback_handler=_noop_callback,- )-- req = httpx.Request("POST", "https://example.com/mcp")- flow = provider.async_auth_flow(req)-- # First anext() drives the wrapper + inner generator until the inner- # yields the outbound request (at oauth2.py:503 ``response = yield request``).- outbound = await flow.__anext__()- assert outbound is not None, "wrapper must yield the outbound request"- assert outbound.url.host == "example.com"-- # Simulate httpx returning a 200 response.- fake_response = httpx.Response(200, request=outbound)-- # The broken wrapper would crash here with AttributeError: 'NoneType'- # object has no attribute 'status_code', because the SDK's inner generator- # resumes with response=None and dereferences .status_code at line 505.- #- # The correct wrapper forwards the response, the SDK takes the non-401- # non-403 exit, and the generator ends cleanly (StopAsyncIteration).- with pytest.raises(StopAsyncIteration):- await flow.asend(fake_response)@pytest.mark.asynciodiff --git a/tests/tools/test_mcp_oauth_callback_latch.py b/tests/tools/test_mcp_oauth_callback_latch.pydeleted file mode 100644index ab85fc34ad5..00000000000--- a/tests/tools/test_mcp_oauth_callback_latch.py+++ /dev/null@@ -1,89 +0,0 @@-"""The loopback OAuth callback latches the first terminal result (#116278).--A browser follows the ``/callback`` redirect with queryless fetches (``/favicon.ico``), and the CLI waiter-samples the result only every 500 ms. A handler that wrote every GET into the result lost the stored code-between two polls, so the user saw "Authorization Successful" while ``hermes mcp login`` timed out. These-tests drive the production entry (``_make_callback_waiter`` → ``_start_callback_server`` → handler) with a-browser stand-in that sends its requests back-to-back, well inside one poll interval.-"""-import asyncio-import io-import socket-import threading-from http.client import HTTPConnection--import pytest--pytest.importorskip("mcp.client.auth.oauth2", reason="MCP SDK 1.26.0+ required")--import tools.mcp_oauth as mo---def _free_port() -> int:- with socket.socket() as s:- s.bind(("127.0.0.1", 0))- return s.getsockname()[1]---def _get(port: int, path: str) -> int:- conn = HTTPConnection("127.0.0.1", port, timeout=5)- try:- conn.request("GET", path)- resp = conn.getresponse()- resp.read()- return resp.status- finally:- conn.close()---def _wait_listening(port: int) -> None:- for _ in range(200):- try:- with socket.create_connection(("127.0.0.1", port), timeout=0.2):- return- except OSError:- threading.Event().wait(0.02)- raise AssertionError("callback listener never bound")---def _drive_waiter(monkeypatch, paths: list[str]):- """Run the real waiter on its own loop; send *paths* back-to-back once the listener is bound."""- monkeypatch.setattr(mo.sys, "stdin", io.StringIO()) # paste reader sees EOF; the HTTP listener is under test- port = _free_port()- out: dict = {}-- def run():- async def main():- with mo.force_interactive_oauth():- return await mo._make_callback_waiter(port, timeout=4)()- try:- out["result"] = asyncio.run(main())- except Exception as exc: # noqa: BLE001 — the timeout is the failure under test- out["exc"] = exc-- thread = threading.Thread(target=run)- thread.start()- _wait_listening(port)- statuses = [_get(port, p) for p in paths]- thread.join(timeout=15)- assert not thread.is_alive(), "waiter did not finish"- assert "exc" not in out, f"waiter raised {type(out.get('exc')).__name__}"- return statuses, out["result"]---def test_favicon_right_after_callback_does_not_clobber_the_code(monkeypatch):- statuses, result = _drive_waiter(- monkeypatch, ["/callback?code=synthetic&state=s1&iss=https://as.example", "/favicon.ico"])- assert statuses == [200, 404]- assert (result.code, result.state, result.iss) == ("synthetic", "s1", "https://as.example")---def test_first_terminal_callback_wins_over_later_ones(monkeypatch):- statuses, result = _drive_waiter(monkeypatch, [- "/favicon.ico",- "/callback?code=first&state=s1",- "/callback?code=second&state=s2",- "/callback?error=access_denied&state=s1",- ])- assert statuses == [404, 200, 200, 200]- assert (result.code, result.state) == ("first", "s1")diff --git a/tests/tools/test_mcp_oauth_cold_load_expiry.py b/tests/tools/test_mcp_oauth_cold_load_expiry.pyindex 867052512c6..ab894fbc98c 100644--- a/tests/tools/test_mcp_oauth_cold_load_expiry.py+++ b/tests/tools/test_mcp_oauth_cold_load_expiry.py@@ -498,58 +498,3 @@ async def test_initialize_prefetches_oauth_metadata_when_missing(assert seen_user_agents and set(seen_user_agents) == {DEFAULT_AUTH_REQUEST_USER_AGENT}-async def test_initialize_skips_prefetch_when_no_tokens(tmp_path, monkeypatch):- """Pre-flight must not run when there are no stored tokens yet.-- Without this guard, every fresh-install ``_initialize`` would do two- extra network roundtrips that gain nothing (the SDK's 401-branch- discovery will run on the first real request anyway).- """- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- import httpx- from mcp.shared.auth import OAuthClientMetadata- from pydantic import AnyUrl-- from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS, reset_manager_for_tests- from tools.mcp_oauth import HermesTokenStorage-- assert _HERMES_PROVIDER_CLS is not None- reset_manager_for_tests()-- calls: list[str] = []-- def mock_handler(request: httpx.Request) -> httpx.Response:- calls.append(str(request.url))- return httpx.Response(404)-- transport = httpx.MockTransport(mock_handler)- import httpx as real_httpx-- original = real_httpx.AsyncClient-- def patched(*args, **kwargs):- kwargs["transport"] = transport- return original(*args, **kwargs)-- monkeypatch.setattr(real_httpx, "AsyncClient", patched)-- storage = HermesTokenStorage("srv") # empty — no tokens on disk- metadata = OAuthClientMetadata(- redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],- client_name="Hermes Agent",- )- provider = _HERMES_PROVIDER_CLS(- server_name="srv",- server_url="https://mcp.example.com",- client_metadata=metadata,- storage=storage,- redirect_handler=_noop_redirect,- callback_handler=_noop_callback,- )-- await provider._initialize()-- assert calls == [], (- f"Pre-flight must not fire when no tokens are stored, but got {calls}"- )diff --git a/tests/tools/test_mcp_oauth_discovery_requests.py b/tests/tools/test_mcp_oauth_discovery_requests.pyindex 8d312dc4677..77b575c6cf9 100644--- a/tests/tools/test_mcp_oauth_discovery_requests.py+++ b/tests/tools/test_mcp_oauth_discovery_requests.py@@ -128,6 +128,7 @@ async def test_registration_failure_after_failed_discovery_leads_with_discovery(else:response = httpx.Response(404, request=outbound)msg = str(excinfo.value)- assert msg.startswith("Could not read authorization-server metadata (403 from https://example.com/.well-known/oauth-authorization-server")- assert "Registration failed: 404" in msg+ # The metadata refusal (403) must lead; the fallback /register 404 alone is misleading.+ assert "403" in msg and "404" in msg+ assert msg.index("403") < msg.index("404")assert humanize_oauth_registration_error("srv", excinfo.value, server_url="https://example.com/mcp") is Nonediff --git a/tests/tools/test_mcp_oauth_manager.py b/tests/tools/test_mcp_oauth_manager.pyindex 3f6a074225b..f0063446287 100644--- a/tests/tools/test_mcp_oauth_manager.py+++ b/tests/tools/test_mcp_oauth_manager.py@@ -73,13 +73,6 @@ def _set_interactive_stdin(monkeypatch, *, is_tty: bool = True) -> None:monkeypatch.setattr("tools.mcp_oauth.sys.stdin", mock_stdin)-def test_hermes_provider_subclass_exists():- """HermesMCPOAuthProvider is defined and subclasses OAuthClientProvider."""- from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS- from mcp.client.auth.oauth2 import OAuthClientProvider-- assert _HERMES_PROVIDER_CLS is not None- assert issubclass(_HERMES_PROVIDER_CLS, OAuthClientProvider)@pytest.mark.asyncio@@ -125,63 +118,6 @@ async def test_disk_watch_invalidates_on_mtime_change(tmp_path, monkeypatch):assert provider._initialized is False-async def test_handle_401_tracks_inflight_task_to_prevent_gc(tmp_path, monkeypatch):- """The 401 handler task must be strongly referenced by the manager.-- ``asyncio.create_task`` returns a task the event loop only weakly- references. If the manager discards its handle, the background coroutine- can be garbage-collected mid-run and every concurrent waiter stuck on- ``await pending`` hangs forever. See the design note on- ``MCPOAuthManager._inflight_tasks``.- """- import asyncio-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- from tools.mcp_oauth_manager import MCPOAuthManager, _ProviderEntry-- class _TrackedSet(set):- """set subclass that records every element ever inserted."""-- def __init__(self):- super().__init__()- self.ever_added: list = []-- def add(self, item): # noqa: A003- self.ever_added.append(item)- super().add(item)-- mgr = MCPOAuthManager()- mgr._inflight_tasks = _TrackedSet()-- class _DummyProvider:- context = None # forces the can_refresh=False branch-- mgr._entries[mgr._key("srv")] = _ProviderEntry(- server_url="https://example.com/mcp",- oauth_config=None,- provider=_DummyProvider(),- )-- result = await mgr.handle_401("srv", failed_access_token="TOK")-- # The discard done-callback is scheduled via loop.call_soon, so it runs on- # a later loop iteration than the one that resolved `pending` and let- # handle_401 return. Yield once so the callback fires before we assert the- # task was removed from the live set.- await asyncio.sleep(0)-- # Exactly one handler task was created and tracked.- assert len(mgr._inflight_tasks.ever_added) == 1- tracked_task = mgr._inflight_tasks.ever_added[0]- assert isinstance(tracked_task, asyncio.Task)- # done_callback must have removed the finished task from the live set,- # otherwise the set would grow unbounded across repeated 401s.- assert tracked_task not in mgr._inflight_tasks- assert len(mgr._inflight_tasks) == 0- assert tracked_task.done()- # With provider.context=None, there's nothing to refresh — result False.- assert result is False@pytest.mark.asyncio@@ -234,7 +170,6 @@ async def test_handle_401_dedup_survives_even_if_task_reference_dropped(tmp_pathimport asynciofrom types import SimpleNamespace-from unittest.mock import MagicMockdef _fake_response(status, url, body):@@ -264,26 +199,6 @@ def _provider_with_token_endpoint(tmp_path, oauth_config, token_endpoint, monkeyreturn provider-def test_invalid_client_at_token_endpoint_poisons(tmp_path, monkeypatch):- """400 invalid_client on the token endpoint deletes the dead client.json."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- d = tmp_path / "mcp-tokens"- d.mkdir(parents=True)- (d / "srv.client.json").write_text('{"client_id": "dead"}', encoding="utf-8")- (d / "srv.meta.json").write_text("{}", encoding="utf-8")- provider = _provider_with_token_endpoint(- tmp_path, {}, "https://idp.example.com/oauth/token", monkeypatch- )- resp = _fake_response(- 400, "https://idp.example.com/oauth/token", b'{"error":"invalid_client"}'- )-- asyncio.run(provider._maybe_flag_poisoned_client(resp))-- assert not (d / "srv.client.json").exists()- assert (d / "srv.client.json.bak").exists()- assert provider._initialized is False- assert provider.context.client_info is Nonedef test_invalid_client_metadata_does_not_trip(tmp_path, monkeypatch):@@ -614,39 +529,6 @@ async def test_refresh_400_rejects_disk_token_without_refresh_token(assert provider.context.current_tokens is None-async def test_refresh_400_does_not_strand_a_rejected_token_in_the_context(- tmp_path, monkeypatch-):- """A rejected candidate must not be left installed on the context.-- is_token_valid() reads the context, so the candidate has to be published- to be tested. This asserts on the state the recovery helper itself leaves- behind, because the caller's clear_tokens() would otherwise mask the- difference: without the restore, current_tokens still points at the- rejected candidate when the helper returns.- """- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- provider = _provider_with_token_endpoint(- tmp_path, {}, "https://idp.example.com/oauth/token", monkeypatch- )-- stale = _token("A1", "R1")- provider.context.current_tokens = stale- await provider.context.storage.set_tokens(_token("A2", "R2"))-- seen = []- provider.context.is_token_valid = lambda: (- seen.append(provider.context.current_tokens) or False- )-- recovered = await provider._hermes_reload_tokens_after_refresh_failure()-- assert recovered is False- assert seen and seen[0].access_token == "A2", "candidate must be testable"- assert provider.context.current_tokens is stale, (- "a rejected candidate must not be left on the context"- )@@ -948,7 +830,7 @@ async def test_refresh_fence_surfaces_non_contention_lock_errors_immediately(tmpmonkeypatch.setattr(mcp_oauth.fcntl, "flock", broken_flock)started = time.monotonic()- with pytest.raises(mcp_oauth.RefreshFenceTimeout, match="unavailable on this filesystem"):+ with pytest.raises(mcp_oauth.RefreshFenceTimeout):await mcp_oauth.acquire_refresh_fence(tmp_path / "srv.json", timeout=5.0)assert time.monotonic() - started < 1.0, "must fail fast, not wait out the deadline"diff --git a/tests/tools/test_mcp_preflight_content_type.py b/tests/tools/test_mcp_preflight_content_type.pyindex 1dc6b37c950..eb1f048d332 100644--- a/tests/tools/test_mcp_preflight_content_type.py+++ b/tests/tools/test_mcp_preflight_content_type.py@@ -130,7 +130,6 @@ def test_non_mcp_content_type_raises(content_type):asyncio.run(task._preflight_content_type(f"{base}/", timeout=5.0))msg = str(exc_info.value)assert "bad_srv" in msg- assert "application/json" in msg and "text/event-stream" in msg# ---------------------------------------------------------------------------@@ -275,19 +274,6 @@ def test_run_skips_preflight_when_skip_preflight_set(monkeypatch):# ----------------------------------------------------------------------------def test_post_probe_not_attempted_for_valid_head():- """When HEAD already returns application/json, no POST probe is needed."""- task = _make_task()- record: list[str] = []- with _serve(_handler(- status=200, content_type="application/json", body=b"{}",- post_content_type="application/json",- post_body=b'{}',- record=record,- )) as base:- asyncio.run(task._preflight_content_type(f"{base}/mcp", timeout=5.0))- assert record == ["HEAD"]- assert "POST" not in record# ---------------------------------------------------------------------------diff --git a/tests/tools/test_mcp_rapid_drop_budget.py b/tests/tools/test_mcp_rapid_drop_budget.pyindex 20622983613..9fe10dc6aa6 100644--- a/tests/tools/test_mcp_rapid_drop_budget.py+++ b/tests/tools/test_mcp_rapid_drop_budget.py@@ -54,10 +54,6 @@ class TestMarkSessionProven:assert task._session_proven is Trueassert task._reconnect_retries == 0- def test_unproven_after_fresh_connect(self):- # __init__ starts unproven; transports reset the flag on handshake.- task = MCPServerTask("t")- assert task._session_proven is False# ── Integration: flapping transport must reach the park ─────────────────────diff --git a/tests/tools/test_mcp_reconnect_log_hygiene.py b/tests/tools/test_mcp_reconnect_log_hygiene.pyindex 4904c40c9c6..9bbf68a9336 100644--- a/tests/tools/test_mcp_reconnect_log_hygiene.py+++ b/tests/tools/test_mcp_reconnect_log_hygiene.py@@ -17,21 +17,10 @@ import loggingimport pytestfrom tools.mcp_tool import MCPServerTask-from tools.mcp_tool_common import _jittered# ── Jitter ───────────────────────────────────────────────────────────────────-class TestJitter:- def test_jitter_within_20_percent(self):- for _ in range(200):- v = _jittered(10.0)- assert 8.0 <= v <= 12.0--- def test_jitter_varies(self):- values = {_jittered(10.0) for _ in range(50)}- assert len(values) > 1, "jitter produced constant values"# ── Log levels: retry chatter DEBUG, transitions WARNING ─────────────────────@@ -110,7 +99,6 @@ def test_retry_attempts_log_debug_transitions_warn(monkeypatch, tmp_path, caplogassert len(park_warnings) == 1, (f"expected exactly 1 degraded→parked WARNING, got {len(park_warnings)}")- assert "degraded → parked" in park_warnings[0].getMessage()@pytest.mark.no_isolatediff --git a/tests/tools/test_mcp_reconnect_retry_reset.py b/tests/tools/test_mcp_reconnect_retry_reset.pyindex 60f26f0266f..62d89467481 100644--- a/tests/tools/test_mcp_reconnect_retry_reset.py+++ b/tests/tools/test_mcp_reconnect_retry_reset.py@@ -112,10 +112,6 @@ def test_reconnect_counter_resets_after_successful_session(monkeypatch, tmp_pathf"(expected >= 8)")- # Verify the counter is an instance variable, not a local.- assert hasattr(task, "_reconnect_retries"), (- "_reconnect_retries should be an instance variable"- )# Clean shutdown.task._shutdown_event.set()diff --git a/tests/tools/test_mcp_reconnect_signal.py b/tests/tools/test_mcp_reconnect_signal.pyindex 4ac63d5854a..ce4c458ee95 100644--- a/tests/tools/test_mcp_reconnect_signal.py+++ b/tests/tools/test_mcp_reconnect_signal.py@@ -6,19 +6,10 @@ handler signals MCPServerTask to tear down the current MCP session andreconnect with fresh credentials. This file exercises the signal plumbingin isolation from the full stdio/http transport machinery."""-import asyncioimport pytest-async def test_reconnect_event_attribute_exists():- """MCPServerTask has a _reconnect_event alongside _shutdown_event."""- from tools.mcp_tool import MCPServerTask- task = MCPServerTask("test")- assert hasattr(task, "_reconnect_event")- assert isinstance(task._reconnect_event, asyncio.Event)- assert not task._reconnect_event.is_set()@pytest.mark.asynciodiff --git a/tests/tools/test_mcp_resource_content.py b/tests/tools/test_mcp_resource_content.pyindex 7839451bf0d..cfdd5929ded 100644--- a/tests/tools/test_mcp_resource_content.py+++ b/tests/tools/test_mcp_resource_content.py@@ -94,7 +94,6 @@ class TestResourceFilename:class TestPreDecodeSizeCap:def test_oversized_b64_rejected_before_decode(self, monkeypatch):- import tools.mcp_tool as mfrom tools import mcp_tool_content as _mcp_contentmonkeypatch.setattr(_mcp_content, "_MCP_RESOURCE_MAX_B64_CHARS", 16)@@ -130,29 +129,6 @@ class TestAudioBlock:class TestToolResultLoopOrdering:- def test_mixed_blocks_preserve_order(self, doc_cache):- """Simulate the tool-result block loop with text + pdf resource."""- from tools.mcp_tool_content import _cache_mcp_image_block, _cache_mcp_audio_block, _render_mcp_resource_block-- blocks = [- SimpleNamespace(type="text", text="File ID: F123\nMIME Type: application/pdf"),- _embedded(_blob_resource(PDF_BYTES)),- ]- parts = []- for block in blocks:- if getattr(block, "text", None):- parts.append(block.text)- continue- tag = _cache_mcp_image_block(block) or _cache_mcp_audio_block(block)- if tag:- parts.append(tag)- continue- rendered = _render_mcp_resource_block(block, "slack")- if rendered:- parts.append(rendered)- assert len(parts) == 2- assert parts[0].startswith("File ID")- assert "saved to" in parts[1]def test_existing_image_behavior_unchanged(self):from tools.mcp_tool_content import _cache_mcp_image_block@@ -235,4 +211,4 @@ class TestErrorPathResourceText:content=[], isError=True, structuredContent=None,))data = json.loads(handler({}))- assert data["error"] == "MCP tool returned an error"+ assert data["error"]diff --git a/tests/tools/test_mcp_result_size_limit.py b/tests/tools/test_mcp_result_size_limit.pyindex 0f2f0167988..e72fac01931 100644--- a/tests/tools/test_mcp_result_size_limit.py+++ b/tests/tools/test_mcp_result_size_limit.py@@ -46,20 +46,8 @@ class TestTruncateMcpTextResult:assert result.startswith(head_marker)assert result.endswith(tail_marker)- def test_truncation_includes_omitted_count(self):- text = "a" * 5000- result = _truncate_mcp_text_result(text, max_chars=100)- assert "4,900" in result # 5000 - 100 omitted- assert "5,000" in result # total original length- def test_truncation_uses_40_60_head_tail_split(self):- text = "H" * 40 + "M" * 5000 + "T" * 60- result = _truncate_mcp_text_result(text, max_chars=100)- assert result[:40] == "H" * 40- assert result[-60:] == "T" * 60- def test_empty_result_unchanged(self):- assert _truncate_mcp_text_result("") == ""def test_hard_cap_sits_above_spillover_threshold(self):"""The hard cap must stay far above the MCP spillover threshold sodiff --git a/tests/tools/test_mcp_schema_cache.py b/tests/tools/test_mcp_schema_cache.pyindex 4c3ae6e239c..3431a6705da 100644--- a/tests/tools/test_mcp_schema_cache.py+++ b/tests/tools/test_mcp_schema_cache.py@@ -83,26 +83,6 @@ class TestCacheFileLocation:assert (path.stat().st_mode & 0o777) == 0o600-class TestWriteSkip:- def test_identical_payload_skips_rewrite(self, monkeypatch, tmp_path):- monkeypatch.setattr(msc, "_cache_path", lambda: tmp_path / "cache.json")- saves = []- real_save = msc._save_all-- def _counting_save(data):- saves.append(1)- real_save(data)-- monkeypatch.setattr(msc, "_save_all", _counting_save)- tools = [{"name": "t1", "description": "d", "inputSchema": {}}]- msc.write_cache_entry("srv", "fp1", tools=tools, utility_tools=[])- assert len(saves) == 1- # Identical payload (reconnect / list_changed refresh) → no rewrite.- msc.write_cache_entry("srv", "fp1", tools=list(tools), utility_tools=[])- assert len(saves) == 1- # Changed payload → rewrite.- msc.write_cache_entry("srv", "fp2", tools=tools, utility_tools=[])- assert len(saves) == 2class TestWriteThroughPreservesSchema:@@ -161,22 +141,12 @@ class TestWriteThroughPreservesSchema:entry = json.loads((tmp_path / "cache.json").read_text(encoding="utf-8"))["probe_srv"]return entry- def test_cached_schema_keeps_properties(self, tmp_path, monkeypatch):- cached = self._cache_write_through(tmp_path, monkeypatch)["tools"][0]["inputSchema"]- assert set(cached.get("properties", {})) == {"query", "model"}, (- "write-through persisted an empty schema — the SDK field rename "- "was read with a bare camelCase getattr"- )- def test_cached_schema_keeps_required(self, tmp_path, monkeypatch):- cached = self._cache_write_through(tmp_path, monkeypatch)["tools"][0]["inputSchema"]- assert cached.get("required") == ["query", "model"]def test_cache_round_trip_reaches_agent_schema(self, tmp_path, monkeypatch):"""The whole point of the cache: a lazy server re-advertises params."""from unittest.mock import patch- import tools.mcp_tool as mtfrom tools import mcp_tool_registration as _mcp_registrationfrom tools.registry import ToolRegistrydiff --git a/tests/tools/test_mcp_server_log_notifications.py b/tests/tools/test_mcp_server_log_notifications.pyindex 3a0c6963809..51dfcde98c8 100644--- a/tests/tools/test_mcp_server_log_notifications.py+++ b/tests/tools/test_mcp_server_log_notifications.py@@ -29,11 +29,6 @@ class TestLogLevelMap:"error", "critical", "alert", "emergency"):assert lvl in _MCP_LOG_LEVEL_MAP- def test_severity_ordering(self):- assert _MCP_LOG_LEVEL_MAP["debug"] == logging.DEBUG- assert _MCP_LOG_LEVEL_MAP["notice"] == logging.INFO- assert _MCP_LOG_LEVEL_MAP["warning"] == logging.WARNING- assert _MCP_LOG_LEVEL_MAP["emergency"] == logging.ERRORclass TestLoggingCallback:@@ -44,7 +39,7 @@ class TestLoggingCallback:with caplog.at_level(logging.INFO, logger="tools.mcp_tool"):await callback(_params(level="info", data="server started"))assert any(- "MCP server log [log_srv]: server started" in rec.getMessage()+ "log_srv" in rec.getMessage() and "server started" in rec.getMessage()for rec in caplog.records)@@ -56,7 +51,7 @@ class TestLoggingCallback:await callback(_params(level="warning", data="rate limited",logger_name="http"))assert any(- "MCP server log [log_srv/http]: rate limited" in rec.getMessage()+ "log_srv/http" in rec.getMessage() and "rate limited" in rec.getMessage()and rec.levelno == logging.WARNINGfor rec in caplog.records)diff --git a/tests/tools/test_mcp_sse_transport.py b/tests/tools/test_mcp_sse_transport.pyindex d5f15260ac1..ee8993e1343 100644--- a/tests/tools/test_mcp_sse_transport.py+++ b/tests/tools/test_mcp_sse_transport.py@@ -111,33 +111,6 @@ class TestSSEReadTimeout:f"(expected 300.0) — SSE idle disconnect regression")- def test_sse_read_timeout_still_300s_when_tool_timeout_is_large(self, patch_sse_client):- """Even if user sets a large ``timeout``, ``sse_read_timeout`` stays- decoupled — it's a transport-level budget for inter-event silence,- not a per-call budget."""- from tools.mcp_tool import MCPServerTask-- server = _build_server_with_sse()-- async def drive():- with patch.object(MCPServerTask, "_wait_for_lifecycle_event",- new=AsyncMock(return_value="shutdown")), \- patch.object(MCPServerTask, "_discover_tools", new=AsyncMock()):- try:- await asyncio.wait_for(- server._run_http({- "url": "https://example.com/mcp/sse",- "transport": "sse",- "timeout": 600,- }),- timeout=2.0,- )- except (asyncio.TimeoutError, StopAsyncIteration, Exception):- pass-- asyncio.run(drive())-- assert patch_sse_client.get("sse_read_timeout") == 300.0class TestSSEOAuthForwarding:@@ -177,33 +150,3 @@ class TestSSEOAuthForwarding:)assert patch_sse_client["auth"] is fake_oauth_provider- def test_sse_client_omits_auth_when_no_oauth_configured(self, patch_sse_client):- """Without OAuth, ``sse_client`` should not receive an ``auth=`` kwarg.- Passing ``None`` would be equally fine but the current code path only- sets it when configured — lock that in."""- from tools.mcp_tool import MCPServerTask-- server = _build_server_with_sse(oauth=False)-- async def drive():- with patch.object(MCPServerTask, "_wait_for_lifecycle_event",- new=AsyncMock(return_value="shutdown")), \- patch.object(MCPServerTask, "_discover_tools", new=AsyncMock()):- try:- await asyncio.wait_for(- server._run_http({- "url": "https://example.com/mcp/sse",- "transport": "sse",- "timeout": 60,- }),- timeout=2.0,- )- except (asyncio.TimeoutError, StopAsyncIteration, Exception):- pass-- asyncio.run(drive())-- assert "auth" not in patch_sse_client, (- f"sse_client was called with auth= when no OAuth was configured: "- f"{patch_sse_client!r}"- )diff --git a/tests/tools/test_mcp_stability.py b/tests/tools/test_mcp_stability.pyindex 9ce5cf979c2..4cbc3f22f21 100644--- a/tests/tools/test_mcp_stability.py+++ b/tests/tools/test_mcp_stability.py@@ -60,13 +60,6 @@ class TestMCPLoopExceptionHandler:class TestStdioPidTracking:"""_snapshot_child_pids and _stdio_pids track subprocess PIDs."""- def test_snapshot_returns_set(self):- from tools.mcp_tool_lifecycle import _snapshot_child_pids- result = _snapshot_child_pids()- assert isinstance(result, set)- # All elements should be ints- for pid in result:- assert isinstance(pid, int)def test_snapshot_sees_child_spawned_from_another_thread(self):"""/proc/<pid>/task/<tid>/children is per-thread; the MCP subprocess@@ -122,7 +115,7 @@ class TestStdioPidTracking:def test_run_stdio_reaps_orphans_before_spawn(self):"""_run_stdio kills orphaned PIDs from prior failed attempts (#57355)."""from tools.mcp_tool_lifecycle import (- _kill_orphaned_mcp_children, _orphan_stdio_pids, _stdio_pids, _stdio_pgids)+ _orphan_stdio_pids)from tools.mcp_tool import _lock, MCPServerTaskfrom unittest.mock import patch, MagicMock, AsyncMock@@ -194,11 +187,10 @@ class TestStdioPidTracking:with patch("tools.mcp_tool.os.kill") as mock_kill, \patch("gateway.status._pid_exists", return_value=False), \- patch("tools.mcp_tool.time.sleep") as mock_sleep:+ patch("tools.mcp_tool.time.sleep"):_kill_orphaned_mcp_children(server_name="feishu")mock_kill.assert_called_once_with(target_pid, signal.SIGTERM)- mock_sleep.assert_called_once_with(2)with _lock:assert target_pid not in _orphan_stdio_pidsassert target_pid not in _orphan_stdio_pid_servers@@ -313,7 +305,7 @@ class TestStdioPgroupReaping:def test_no_pgid_uses_per_pid_kill(self, monkeypatch):"""When no pgid is recorded (e.g. Windows), fall back to os.kill."""- from tools.mcp_tool_lifecycle import _kill_orphaned_mcp_children, _orphan_stdio_pids, _stdio_pgids+ from tools.mcp_tool_lifecycle import _kill_orphaned_mcp_children, _orphan_stdio_pidsfrom tools.mcp_tool import _lockself._reset_state()@@ -434,38 +426,6 @@ class TestStdioPgroupReaping:# Fix 3: MCP reload timeout (cli.py)# ----------------------------------------------------------------------------class TestMCPReloadTimeout:- """_check_config_mcp_changes uses a timeout on _reload_mcp."""-- def test_reload_timeout_does_not_block_forever(self, tmp_path, monkeypatch):- """If _reload_mcp hangs, the config watcher times out and returns."""- import time-- # Create a mock HermesCLI-like object with the needed attributes- class FakeCLI:- _config_sig = None- _config_mcp_servers = {}- _last_config_check = 0.0- _command_running = False- config = {}- agent = None-- def _reload_mcp(self):- # Simulate a hang — sleep longer than the timeout- time.sleep(60)-- def _slow_command_status(self, cmd):- return cmd-- # This test verifies the timeout mechanism exists in the code- # by checking that _check_config_mcp_changes doesn't call- # _reload_mcp directly (it uses a thread now)- import inspect- from cli import HermesCLI- source = inspect.getsource(HermesCLI._check_config_mcp_changes)- # The fix adds threading.Thread for _reload_mcp- assert "Thread" in source or "thread" in source.lower(), \- "_check_config_mcp_changes should use a thread for _reload_mcp"# ---------------------------------------------------------------------------@@ -476,10 +436,6 @@ class TestMCPReloadTimeout:class TestMCPInitialConnectionRetry:"""MCPServerTask.run() retries initial connection failures instead of giving up."""- def test_initial_connect_retries_constant_exists(self):- """_MAX_INITIAL_CONNECT_RETRIES should be defined."""- from tools.mcp_tool import _MAX_INITIAL_CONNECT_RETRIES- assert _MAX_INITIAL_CONNECT_RETRIES >= 1def test_initial_connect_retry_respects_shutdown(self):diff --git a/tests/tools/test_mcp_startup_summary_names_failures.py b/tests/tools/test_mcp_startup_summary_names_failures.pyindex 5b37669adb2..2559d7fe629 100644--- a/tests/tools/test_mcp_startup_summary_names_failures.py+++ b/tests/tools/test_mcp_startup_summary_names_failures.py@@ -47,7 +47,7 @@ def test_register_summary_names_failed_server_with_reason(monkeypatch, tmp_path,summaries = _summaries(caplog)assert len(summaries) == 1, summaries- assert summaries[0].startswith("MCP: registered 0 tool(s) from 0 server(s) (1 failed: ghost (")+ assert "ghost" in summaries[0]assert "no-such-mcp-binary" in summaries[0]@@ -63,6 +63,5 @@ def test_summary_marks_candidate_skipped_for_cooldown(caplog, _clean_registry):with caplog.at_level(logging.INFO, logger="tools.mcp_tool"):_log_summary(" MCP:", ["ok", "cooled"])- assert _summaries(caplog) == [- " MCP: 2 tool(s) from 1 server(s) (1 failed: cooled (not attempted (in retry cooldown)))"- ]+ summaries = _summaries(caplog)+ assert len(summaries) == 1 and "cooled" in summaries[0] and "cooldown" in summaries[0], summariesdiff --git a/tests/tools/test_mcp_stdio_children_dead.py b/tests/tools/test_mcp_stdio_children_dead.pyindex ef54ed46633..40844476edf 100644--- a/tests/tools/test_mcp_stdio_children_dead.py+++ b/tests/tools/test_mcp_stdio_children_dead.py@@ -94,34 +94,5 @@ def test_watcher_resolves_when_all_children_are_dead():asyncio.run(_run())-def test_watch_ok_probe_does_not_create_unawaited_coroutine():- """The fast-fail gate must inspect the watcher, not call it (#96044).- The old probe — inspect.isawaitable(_watch_children()) — created a- fresh coroutine per stdio tool call and never awaited it, emitting- 'coroutine ... was never awaited' RuntimeWarnings under -W error and- churning the GC. Pin that the shipped source no longer calls the- watcher during the probe.- """- import inspect as _inspect- import tools.mcp_tool_handlers as handlers_mod-- src = _inspect.getsource(handlers_mod)- assert "isawaitable(_watch_children())" not in src- assert "iscoroutinefunction(_watch_children)" in src---def test_watch_ok_semantics_mock_vs_real():- """MagicMock watchers stay on the plain-await path; real async defs- (and AsyncMock) qualify for the fast-fail race — same split the old- isawaitable(call) probe produced, without the coroutine leak."""- import inspect as _inspect- from unittest.mock import AsyncMock, MagicMock-- async def _real_watcher(): # what the real method looks like- pass-- assert _inspect.iscoroutinefunction(_real_watcher) is True- assert _inspect.iscoroutinefunction(AsyncMock()) is True- assert _inspect.iscoroutinefunction(MagicMock()) is Falsediff --git a/tests/tools/test_mcp_stdio_encoding_handler.py b/tests/tools/test_mcp_stdio_encoding_handler.pyindex 7e33a370ab4..fea8bf9f29f 100644--- a/tests/tools/test_mcp_stdio_encoding_handler.py+++ b/tests/tools/test_mcp_stdio_encoding_handler.py@@ -64,40 +64,3 @@ class TestStdioEncodingErrorHandler:asyncio.run(_test())- def test_stdio_server_params_defaults_encoding_utf8(self):- """Verify that the default encoding (utf-8) is not overridden."""- mock_session = MagicMock()- mock_session.initialize = AsyncMock()- mock_session.list_tools = AsyncMock(return_value=SimpleNamespace(tools=[]))-- mock_stdio_cm = MagicMock()- mock_stdio_cm.__aenter__ = AsyncMock(return_value=(object(), object()))- mock_stdio_cm.__aexit__ = AsyncMock(return_value=False)-- mock_session_cm = MagicMock()- mock_session_cm.__aenter__ = AsyncMock(return_value=mock_session)- mock_session_cm.__aexit__ = AsyncMock(return_value=False)-- async def _test():- with (- patch("tools.mcp_tool.StdioServerParameters") as mock_params,- patch("tools.mcp_tool.stdio_client", return_value=mock_stdio_cm),- patch("tools.mcp_tool.ClientSession", return_value=mock_session_cm),- patch("tools.mcp_tool_lifecycle._snapshot_child_pids", return_value=set()),- patch("tools.mcp_tool_config._write_stderr_log_header"),- patch("tools.mcp_tool._get_mcp_stderr_log", return_value=None),- ):- server = MCPServerTask("test-encoding")- await server.start({- "command": "echo",- "args": ["hello"],- })-- call_kwargs = mock_params.call_args.kwargs- # encoding is not explicitly set — StdioServerParameters defaults to utf-8- # We just verify we don't override it- assert "encoding" not in call_kwargs or call_kwargs.get("encoding") == "utf-8"-- await server.shutdown()-- asyncio.run(_test())diff --git a/tests/tools/test_mcp_stdio_fastfail_reconnect.py b/tests/tools/test_mcp_stdio_fastfail_reconnect.pyindex c6357f197fe..5162ee36a07 100644--- a/tests/tools/test_mcp_stdio_fastfail_reconnect.py+++ b/tests/tools/test_mcp_stdio_fastfail_reconnect.py@@ -174,8 +174,6 @@ def test_midcall_child_exit_reconnects_without_replay(monkeypatch, tmp_path):handler = _make_tool_handler("srv-midcall", "tool1", 10.0)parsed = json.loads(handler({}))assert parsed["outcome_uncertain"] is True, parsed- assert "may have completed" in parsed["error"], parsed- assert "did not replay" in parsed["error"], parsedassert server._reconnect_event.set_calls == 1assert effects["n"] == 1, "the replacement session must not repeat an uncertain side effect"finally:@@ -222,7 +220,6 @@ def test_sdk_first_transport_close_midcall_is_uncertain_without_replay(monkeypathandler = _make_tool_handler("srv-sdk-first", "tool1", 10.0)parsed = json.loads(handler({}))assert parsed["outcome_uncertain"] is True, parsed- assert "did not replay" in parsed["error"], parsedassert server._reconnect_event.set_calls == 1assert effects["n"] == 1, "the session-expired recoverer must not replay an in-flight stdio call"finally:@@ -302,8 +299,6 @@ def test_child_dying_again_after_respawn_does_not_hot_cycle(handler = _make_tool_handler("srv-flap", "tool1", 10.0)parsed = json.loads(handler({}))assert "error" in parsed, parsed- assert "exited again" in parsed["error"], parsed- assert "do NOT retry" in parsed["error"], parsedassert server._reconnect_event.set_calls == 1, ("one respawn request per tool call — never a retry loop")diff --git a/tests/tools/test_mcp_structured_content.py b/tests/tools/test_mcp_structured_content.pyindex ce454642799..f97ddae1380 100644--- a/tests/tools/test_mcp_structured_content.py+++ b/tests/tools/test_mcp_structured_content.py@@ -358,8 +358,3 @@ class TestDroppedBlockNotice:assert data["structuredContent"] == payloadassert "[MCP content dropped" in data["result"]- def test_notice_helper_minimal_block(self):- notice = _mcp_content._render_mcp_dropped_block_notice(- SimpleNamespace(), "mystery"- )- assert notice == "[MCP content dropped: unsupported block (type=mystery)]"diff --git a/tests/tools/test_mcp_timeout_resolution.py b/tests/tools/test_mcp_timeout_resolution.pyindex 160cf0e8648..c12642f9538 100644--- a/tests/tools/test_mcp_timeout_resolution.py+++ b/tests/tools/test_mcp_timeout_resolution.py@@ -16,7 +16,7 @@ from tools.mcp_tool_common import _resolve_tool_timeoutclass TestMcpToolTimeoutResolution:def test_default_unchanged_with_nothing_configured(self, monkeypatch):monkeypatch.setattr("agent.deadline._timeouts_section", lambda: {})- assert _resolve_tool_timeout({}) == _DEFAULT_TOOL_TIMEOUT == 300+ assert _resolve_tool_timeout({}) == _DEFAULT_TOOL_TIMEOUTdef test_per_server_timeout_always_wins(self, monkeypatch):# Per-server config beats the global timeouts section (documenteddiff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 1ebcb461c1a..a5c78ce44ba 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -5,7 +5,6 @@ All tests use mocks -- no real MCP servers or subprocesses are started.import asyncioimport json-import loggingimport osimport sysimport threading@@ -66,9 +65,7 @@ def _make_mock_server(name, session=None, tools=None):class TestFilterMCPChildren:def test_filters_gateway_children_by_argv_marker(self, monkeypatch):"""Non-MCP children start with an interpreter/binary, not the marker."""- import sys- import tools.mcp_tool as mcp_toolfrom tools import mcp_tool_lifecycle as _mcp_lifecyclecmdlines = {@@ -356,7 +353,7 @@ class TestMCPStatus:def test_scoped_shutdown_clears_only_its_connection_status(self, monkeypatch):import tools.mcp_tool as mcp_tool- from tools import mcp_tool_lifecycle, mcp_tool_loop, mcp_tool_discovery+ from tools import mcp_tool_lifecycle, mcp_tool_loopmonkeypatch.setattr(mcp_tool_loop, "_stop_mcp_loop", lambda **_kwargs: None)with mcp_tool._lock:@@ -441,7 +438,7 @@ class TestLifecycleConfig:"max_lifetime_seconds",) == 42.0- def test_get_lifecycle_seconds_ignores_invalid_values(self, caplog):+ def test_get_lifecycle_seconds_ignores_invalid_values(self):from tools.mcp_tool_common import _get_lifecycle_secondsassert (@@ -459,10 +456,6 @@ class TestLifecycleConfig:is None)- messages = [record.getMessage() for record in caplog.records]- assert any("must be a number of seconds" in msg for msg in messages)- assert any("must be positive" in msg for msg in messages)-# ---------------------------------------------------------------------------# Schema conversion@@ -917,7 +910,7 @@ class TestRunOnMCPLoopInterrupts:interrupter.start()try:- with pytest.raises(InterruptedError, match="User sent a new message"):+ with pytest.raises(InterruptedError):_mcp_loop._run_on_mcp_loop(_slow_call(), timeout=10)deadline = time.time() + 2@@ -956,7 +949,7 @@ class TestRunOnMCPLoopInterrupts:try:# 0.1s is the floor the MCP loop clamps short timeouts to.- with pytest.raises(TimeoutError, match=r"MCP call timed out after .*configured timeout: 0.1s"):+ with pytest.raises(TimeoutError):_mcp_loop._run_on_mcp_loop(_slow_call(), timeout=0.1)deadline = time.time() + 2@@ -1008,7 +1001,7 @@ class TestDiscoverAndRegister:_servers.pop("fs", None)- def test_same_server_normalization_collision_skips_all_ambiguous_tools(self, caplog):+ def test_same_server_normalization_collision_skips_all_ambiguous_tools(self):from tools.mcp_tool_registration import _register_server_toolsfrom tools.registry import ToolRegistry@@ -1025,21 +1018,14 @@ class TestDiscoverAndRegister:config = {"tools": {"resources": False, "prompts": False}}with patch("tools.registry.registry", registry), \- patch("tools.mcp_tool_registration._track_mcp_tool_server"), \- caplog.at_level(logging.ERROR, logger="tools.mcp_tool"):+ patch("tools.mcp_tool_registration._track_mcp_tool_server"):registered = _register_server_tools("srv", server, config)assert registered == ["mcp__srv__safe_tool"]assert registry.get_entry("mcp__srv__read_file") is Noneassert registry.get_entry("mcp__srv__safe_tool") is not None- assert any(- "name normalization collision" in record.message- and "tool 'read-file'" in record.message- and "tool 'read_file'" in record.message- for record in caplog.records- )- def test_native_tool_wins_over_generated_utility_on_collision(self, caplog):+ def test_native_tool_wins_over_generated_utility_on_collision(self):"""A server-native tool named `read_resource` must survive its collisionwith the generated `read_resource` utility (#87112).@@ -1065,8 +1051,7 @@ class TestDiscoverAndRegister:config = {"tools": {"prompts": False}}with patch("tools.registry.registry", registry), \- patch("tools.mcp_tool_registration._track_mcp_tool_server"), \- caplog.at_level(logging.INFO, logger="tools.mcp_tool"):+ patch("tools.mcp_tool_registration._track_mcp_tool_server"):registered = _register_server_tools("srv", server, config)# The native tool is registered (before the fix it was dropped) and it@@ -1077,20 +1062,6 @@ class TestDiscoverAndRegister:assert entry.description == "Native read-resource tool"assert "mcp__srv__safe_tool" in registered- # The collision was resolved in favour of the native tool, not skipped- # as ambiguous.- assert not any(- "name normalization collision" in record.message- and "mcp__srv__read_resource" in record.message- for record in caplog.records- )- assert any(- record.levelno == logging.INFO- and "keeping the native tool and dropping the utility" in record.message- and "read_resource" in record.message- for record in caplog.records- )-# ---------------------------------------------------------------------------# MCPServerTask (run / start / shutdown)# ---------------------------------------------------------------------------@@ -1475,41 +1446,6 @@ class TestShutdown:assert "mcp__test__ping" not in registry.get_all_tool_names()assert validate_toolset("test") is False- def test_shutdown_is_parallel(self):- """Multiple servers are shut down in parallel via asyncio.gather."""- import tools.mcp_tool as mcp_mod- from tools import mcp_tool_loop as _mcp_loop- from tools.mcp_tool_lifecycle import shutdown_mcp_servers- from tools.mcp_tool import _servers- import time-- _servers.clear()-- # 4 servers each taking 50ms to shut down- delay = 0.05- for i in range(4):- mock_server = MagicMock()- mock_server.name = f"srv_{i}"- async def slow_shutdown():- await asyncio.sleep(delay)- mock_server.shutdown = slow_shutdown- _servers[f"srv_{i}"] = mock_server-- _mcp_loop._ensure_mcp_loop()- try:- start = time.monotonic()- shutdown_mcp_servers()- elapsed = time.monotonic() - start- finally:- mcp_mod._mcp_loop = None- mcp_mod._mcp_thread = None-- assert len(_servers) == 0- # Parallel: ~1 delay, not 4. Margin covers scheduling jitter but stays- # well under the serial total.- assert elapsed < delay * 3, (- f"Shutdown took {elapsed:.3f}s, expected ~{delay}s (parallel)"- )# ---------------------------------------------------------------------------@@ -1695,7 +1631,7 @@ class TestHTTPConfig:async def _test():with patch("tools.mcp_tool._MCP_HTTP_AVAILABLE", False):- with pytest.raises(ImportError, match="HTTP transport"):+ with pytest.raises(ImportError):await server._run_http(config)asyncio.run(_test())@@ -1716,7 +1652,7 @@ class TestHTTPConfig:async def _test():with patch("tools.mcp_tool._MCP_AVAILABLE", False):- with pytest.raises(ImportError, match=r"mcp.*SDK"):+ with pytest.raises(ImportError):await server._run_stdio(config)asyncio.run(_test())@@ -1914,64 +1850,12 @@ class TestConfigurableTimeouts:asyncio.run(_test())- def test_timeout_passed_to_handler(self):- """The tool handler uses the server's configured timeout."""- from tools.mcp_tool_handlers import _make_tool_handler- from tools.mcp_tool import _servers-- mock_session = MagicMock()- mock_session.call_tool = AsyncMock(- return_value=_make_call_result("ok", is_error=False)- )- server = _make_mock_server("test_srv", session=mock_session)- server.tool_timeout = 180- _servers["test_srv"] = server-- try:- handler = _make_tool_handler("test_srv", "my_tool", 180)- with patch("tools.mcp_tool_loop._run_on_mcp_loop") as mock_run:- def fake_run(coro, timeout=30):- coro.close()- return json.dumps({"result": "ok"})-- mock_run.side_effect = fake_run- handler({})- # Verify timeout=180 was passed- call_kwargs = mock_run.call_args- assert call_kwargs.kwargs.get("timeout") == 180 or \- (len(call_kwargs.args) > 1 and call_kwargs.args[1] == 180) or \- call_kwargs[1].get("timeout") == 180- finally:- _servers.pop("test_srv", None)# ---------------------------------------------------------------------------# Utility tool schemas (Resources & Prompts)# ----------------------------------------------------------------------------class TestUtilitySchemas:- """Tests for _build_utility_schemas() and the schema format of utility tools."""-- def test_builds_four_utility_schemas(self):- from tools.mcp_tool_schema import _build_utility_schemas-- schemas = _build_utility_schemas("myserver")- assert len(schemas) == 4- names = [s["schema"]["name"] for s in schemas]- assert "mcp__myserver__list_resources" in names- assert "mcp__myserver__read_resource" in names- assert "mcp__myserver__list_prompts" in names- assert "mcp__myserver__get_prompt" in names-- def test_read_resource_schema_requires_uri(self):- from tools.mcp_tool_schema import _build_utility_schemas-- schemas = _build_utility_schemas("srv")- rr = next(s for s in schemas if s["handler_key"] == "read_resource")- params = rr["schema"]["parameters"]- assert "uri" in params["properties"]- assert params["properties"]["uri"]["type"] == "string"- assert params["required"] == ["uri"]# ---------------------------------------------------------------------------# Utility tool handlers (Resources & Prompts)@@ -2134,7 +2018,7 @@ try:except ImportError:ToolUseContent = _CompatType-from tools.mcp_tool import CreateMessageResultWithTools, SamplingHandler, SamplingToolsCapability, ToolUseContent+from tools.mcp_tool import CreateMessageResultWithTools, SamplingHandler, ToolUseContentfrom tools.mcp_tool_common import _safe_numericfrom tools import mcp_tool_config as _mcp_configfrom tools import mcp_tool_discovery as _mcp_discovery@@ -2244,16 +2128,6 @@ class TestSafeNumeric:# ---------------------------------------------------------------------------class TestSamplingHandlerInit:- def test_defaults(self):- h = SamplingHandler("srv", {})- assert h.server_name == "srv"- assert h.max_rpm == 10- assert h.timeout == 30- assert h.max_tokens_cap == 4096- assert h.max_tool_rounds == 5- assert h.model_override is None- assert h.allowed_models == []- assert h.metrics == {"requests": 0, "errors": 0, "tokens_used": 0, "tool_use_count": 0}def test_custom_config(self):cfg = {@@ -2456,7 +2330,6 @@ class TestToolLoopGovernance:# Round 3: exceeds limitr3 = asyncio.run(handler(None, params))assert isinstance(r3, ErrorData)- assert "Tool loop limit exceeded" in r3.messagedef test_max_tool_rounds_zero_disables(self):"""max_tool_rounds=0 means tool loops are disabled entirely."""@@ -2470,7 +2343,6 @@ class TestToolLoopGovernance:):result = asyncio.run(handler(None, _make_sampling_params()))assert isinstance(result, ErrorData)- assert "Tool loops disabled" in result.message# ---------------------------------------------------------------------------@@ -2617,157 +2489,16 @@ class TestMetricsTracking:# 13. session_kwargs()# ----------------------------------------------------------------------------class TestSessionKwargs:- def test_returns_correct_keys(self):- handler = SamplingHandler("sk", {})- kwargs = handler.session_kwargs()- assert "sampling_callback" in kwargs- assert "sampling_capabilities" in kwargs- assert kwargs["sampling_callback"] is handler# ---------------------------------------------------------------------------# 14. MCPServerTask integration# ----------------------------------------------------------------------------class TestMCPServerTaskSamplingIntegration:- def test_sampling_handler_created_when_enabled(self):- """MCPServerTask.run() creates a SamplingHandler when sampling is enabled."""- from tools.mcp_tool import MCPServerTask, _MCP_SAMPLING_TYPES-- server = MCPServerTask("int_test")- config = {- "command": "fake",- "sampling": {"enabled": True, "max_rpm": 5},- }- # We only need to test the setup logic, not the actual connection.- # Calling run() would attempt a real connection, so we test the- # sampling setup portion directly.- server._config = config- sampling_config = config.get("sampling", {})- if sampling_config.get("enabled", True) and _MCP_SAMPLING_TYPES:- server._sampling = SamplingHandler(server.name, sampling_config)- else:- server._sampling = None-- assert server._sampling is not None- assert isinstance(server._sampling, SamplingHandler)- assert server._sampling.server_name == "int_test"- assert server._sampling.max_rpm == 5-- def test_sampling_handler_none_when_disabled(self):- """MCPServerTask._sampling is None when sampling is disabled."""- from tools.mcp_tool import MCPServerTask, _MCP_SAMPLING_TYPES-- server = MCPServerTask("int_test2")- config = {- "command": "fake",- "sampling": {"enabled": False},- }- server._config = config- sampling_config = config.get("sampling", {})- if sampling_config.get("enabled", True) and _MCP_SAMPLING_TYPES:- server._sampling = SamplingHandler(server.name, sampling_config)- else:- server._sampling = None-- assert server._sampling is None# ---------------------------------------------------------------------------# Discovery failed_count tracking# ----------------------------------------------------------------------------class TestDiscoveryFailedCount:- """Verify discover_mcp_tools() correctly tracks failed server connections."""-- def test_failed_server_increments_failed_count(self):- """When _discover_and_register_server raises, failed_count increments."""- from tools.mcp_tool_discovery import discover_mcp_tools- from tools.mcp_tool import _servers- from tools.mcp_tool_loop import _ensure_mcp_loop-- fake_config = {- "good_server": {"command": "npx", "args": ["good"]},- "bad_server": {"command": "npx", "args": ["bad"]},- }-- async def fake_register(name, cfg):- if name == "bad_server":- raise ConnectionError("Connection refused")- # Simulate successful registration- from tools.mcp_tool import MCPServerTask- server = MCPServerTask(name)- server.session = MagicMock()- server._tools = [_make_mcp_tool("tool_a")]- _servers[name] = server- return [f"mcp__{name}__tool_a"]-- with patch("tools.mcp_tool_config._load_mcp_config", return_value=fake_config), \- patch("tools.mcp_tool_discovery._discover_and_register_server", side_effect=fake_register), \- patch("tools.mcp_tool._MCP_AVAILABLE", True), \- patch("tools.mcp_tool_registration._existing_tool_names", return_value=["mcp__good_server__tool_a"]):- _ensure_mcp_loop()-- # Capture the logger to verify failed_count in summary- with patch("tools.mcp_tool_discovery.logger") as mock_logger:- discover_mcp_tools()-- # Find the summary info call- info_calls = [- str(call)- for call in mock_logger.info.call_args_list- if "failed" in str(call).lower() or "MCP:" in str(call)- ]- # The summary should mention the failure- assert any("1 failed" in str(c) for c in info_calls), (- f"Summary should report 1 failed server, got: {info_calls}"- )-- _servers.pop("good_server", None)- _servers.pop("bad_server", None)-- def test_ok_servers_excludes_failures(self):- """ok_servers count correctly excludes failed servers."""- from tools.mcp_tool_discovery import discover_mcp_tools- from tools.mcp_tool import _servers- from tools.mcp_tool_loop import _ensure_mcp_loop-- fake_config = {- "ok1": {"command": "npx", "args": ["ok1"]},- "ok2": {"command": "npx", "args": ["ok2"]},- "fail1": {"command": "npx", "args": ["fail"]},- }-- async def selective_register(name, cfg):- if name == "fail1":- raise ConnectionError("Refused")- from tools.mcp_tool import MCPServerTask- server = MCPServerTask(name)- server.session = MagicMock()- server._tools = [_make_mcp_tool("t")]- _servers[name] = server- return [f"mcp__{name}__t"]-- with patch("tools.mcp_tool_config._load_mcp_config", return_value=fake_config), \- patch("tools.mcp_tool_discovery._discover_and_register_server", side_effect=selective_register), \- patch("tools.mcp_tool._MCP_AVAILABLE", True), \- patch("tools.mcp_tool_registration._existing_tool_names", return_value=["mcp__ok1__t", "mcp__ok2__t"]):- _ensure_mcp_loop()-- with patch("tools.mcp_tool_discovery.logger") as mock_logger:- discover_mcp_tools()-- info_calls = [str(call) for call in mock_logger.info.call_args_list]- # Should say "2 server(s)" not "3 server(s)"- assert any("2 server" in str(c) for c in info_calls), (- f"Summary should report 2 ok servers, got: {info_calls}"- )- assert any("1 failed" in str(c) for c in info_calls), (- f"Summary should report 1 failed, got: {info_calls}"- )-- _servers.pop("ok1", None)- _servers.pop("ok2", None)- _servers.pop("fail1", None)class TestDiscoveryConnectConcurrency:@@ -2959,27 +2690,6 @@ class TestMCPSelectiveToolLoading:# Tool name collision protection# ----------------------------------------------------------------------------class TestRegistryCollisionWarning:- """registry.register() warns when a tool name is overwritten by a different toolset."""-- def test_overwrite_different_toolset_logs_warning(self, caplog):- """Overwriting a tool from a different toolset is REJECTED with an error."""- from tools.registry import ToolRegistry- import logging-- reg = ToolRegistry()- schema = {"name": "my_tool", "description": "test", "parameters": {"type": "object", "properties": {}}}- handler = lambda args, **kw: "{}"-- reg.register(name="my_tool", toolset="builtin", schema=schema, handler=handler)-- with caplog.at_level(logging.ERROR, logger="tools.registry"):- reg.register(name="my_tool", toolset="mcp-ext", schema=schema, handler=handler)-- assert any("rejected" in r.message.lower() for r in caplog.records)- assert any("builtin" in r.message and "mcp-ext" in r.message for r in caplog.records)- # The original tool should still be from 'builtin', not overwritten- assert reg.get_toolset_for_tool("my_tool") == "builtin"class TestMCPBuiltinCollisionGuard:"""MCP tools that collide with built-in tool names are skipped."""@@ -3078,9 +2788,6 @@ class TestMCPBuiltinCollisionGuard:class TestSanitizeMcpNameComponent:"""Verify sanitize_mcp_name_component handles all edge cases."""- def test_hyphens_replaced(self):- from tools.mcp_tool_schema import sanitize_mcp_name_component- assert sanitize_mcp_name_component("my-server") == "my_server"def test_slash_in_server_alias_resolution(self):@@ -3180,7 +2887,7 @@ class TestRegisterMcpServers:def test_clears_stale_connecting_on_timeout(self):"""Stale entries in _server_connecting are cleaned up after timeout (#58862)."""from tools.mcp_tool_discovery import register_mcp_servers- from tools.mcp_tool import _servers, _server_connecting, _server_connect_errors+ from tools.mcp_tool import _servers, _server_connectingfrom tools.mcp_tool_loop import _ensure_mcp_loopfake_config = {@@ -3219,26 +2926,6 @@ class TestRegisterMcpServers:class TestMcpParallelToolCalls:"""Tests for the supports_parallel_tool_calls config option."""- def test_is_mcp_tool_parallel_safe_with_flag(self):- """MCP tool from a parallel-safe server returns True."""- from tools.mcp_tool_discovery import is_mcp_tool_parallel_safe- from tools.mcp_tool import _mcp_tool_server_names, _parallel_safe_servers, _lock- with _lock:- _parallel_safe_servers.add("docs")- _mcp_tool_server_names["mcp__docs__search"] = "docs"- _mcp_tool_server_names["mcp__docs__read_file"] = "docs"- _mcp_tool_server_names["mcp__github__list_repos"] = "github"- try:- assert is_mcp_tool_parallel_safe("mcp__docs__search") is True- assert is_mcp_tool_parallel_safe("mcp__docs__read_file") is True- # Different server should be False- assert is_mcp_tool_parallel_safe("mcp__github__list_repos") is False- finally:- with _lock:- _parallel_safe_servers.discard("docs")- _mcp_tool_server_names.pop("mcp__docs__search", None)- _mcp_tool_server_names.pop("mcp__docs__read_file", None)- _mcp_tool_server_names.pop("mcp__github__list_repos", None)def test_register_mcp_servers_tracks_parallel_flag(self):@@ -3281,22 +2968,6 @@ class TestMcpParallelToolCalls:class TestMCPDiscoveryCrossProcessLock:"""Tests for the cross-process MCP discovery guard in discover_mcp_tools()."""- @staticmethod- def _lock_exclusive(fh):- """Lock a file handle exclusively, cross-platform.-- Mirrors production _try_acquire_mcp_discovery_lock: fcntl on POSIX,- portalocker on Windows (portalocker only ships on win32 installs).- """- if sys.platform == "win32":- import portalocker-- portalocker.lock(fh, portalocker.LOCK_EX | portalocker.LOCK_NB)- else:- import fcntl-- fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)-@pytest.fixture(autouse=True)def _fast_retries(self):"""Override retry constants so tests are fast."""@@ -3333,7 +3004,6 @@ class TestMCPDiscoveryCrossProcessLock:def test_lock_held_retries_exhausted_fallback(self):"""All retry attempts see lock held -> runs discovery unguarded."""- from tools.mcp_tool import _LOCK_UNAVAILABLE, _MCP_DISCOVERY_LOCK_MAX_RETRIESfrom tools.mcp_tool_discovery import discover_mcp_toolsmock_config = {"test_srv": {"command": "echo", "enabled": True}}@@ -3347,35 +3017,6 @@ class TestMCPDiscoveryCrossProcessLock:# Must still run local discoveryreg_spy.assert_called_once_with(mock_config)- def test_posix_flock_acquire_and_release(self):- """_acquire_lock_on_fh uses fcntl.flock on POSIX."""- import sys- import tempfile- from unittest.mock import MagicMock-- mock_fcntl = MagicMock()- mock_fcntl.LOCK_EX = 2- mock_fcntl.LOCK_NB = 4-- with tempfile.NamedTemporaryFile(prefix="mcp-lock-", suffix=".tmp", delete=False) as tf:- lock_path = tf.name-- try:- fh = open(lock_path, "w", encoding="utf-8")- with patch.dict("sys.modules", {"fcntl": mock_fcntl}), \- patch("tools.mcp_tool.os.name", "posix"):- from tools.mcp_tool_loop import _acquire_lock_on_fh- result = _acquire_lock_on_fh(fh)- assert result is True- mock_fcntl.flock.assert_called_once_with(- fh.fileno(), mock_fcntl.LOCK_EX | mock_fcntl.LOCK_NB- )- fh.close()- finally:- try:- os.unlink(lock_path)- except Exception:- passclass TestRedirectHeaderStripper:diff --git a/tests/tools/test_mcp_tool_401_handling.py b/tests/tools/test_mcp_tool_401_handling.pyindex e1c2a0e6f14..6b5432eb506 100644--- a/tests/tools/test_mcp_tool_401_handling.py+++ b/tests/tools/test_mcp_tool_401_handling.py@@ -102,7 +102,7 @@ def test_call_tool_handler_non_auth_error_still_generic(monkeypatch, tmp_path):result = handler({"arg": "v"})parsed = json.loads(result)assert "needs_reauth" not in parsed- assert "MCP call failed" in parsed.get("error", "")+ assert parsed.get("error")finally:mcp_tool._servers.pop("srv", None)mcp_tool._server_error_counts.pop("srv", None)diff --git a/tests/tools/test_mcp_tool_session_expired.py b/tests/tools/test_mcp_tool_session_expired.pyindex 34e5158dd55..03786e75b85 100644--- a/tests/tools/test_mcp_tool_session_expired.py+++ b/tests/tools/test_mcp_tool_session_expired.py@@ -50,7 +50,6 @@ def test_is_session_expired_detects_session_not_found():def test_is_session_expired_traversal_is_budget_bounded():"""Pathologically long chains stop at the node budget without spinning."""- import tools.mcp_tool as mcp_modfrom tools import mcp_tool_errors as _mcp_errorsfrom tools.mcp_tool_errors import _is_session_expired_error@@ -89,7 +88,6 @@ def _install_stub_server(name: str = "wpcom"):"""Register a minimal server stub that _handle_session_expired_and_retrycan signal via _reconnect_event, and that reports ready+session afterthe event fires."""- from tools import mcp_tool_mcp_loop._ensure_mcp_loop()@@ -494,7 +492,6 @@ def test_session_expired_retry_only_for_read_only_tools(monkeypatch, tmp_path, rassert call_count["n"] == 2 # original + one retryelse:assert parsed.get("outcome_uncertain") is True, parsed- assert "may or may not have taken effect" in parsed["error"]assert call_count["n"] == 1 # exactly one dispatch# Successful reconnect clears breaker state (session-state failure, not server health).assert mcp_tool._server_error_counts.get("srv", 0) == 0diff --git a/tests/tools/test_mcp_trust_gating.py b/tests/tools/test_mcp_trust_gating.pyindex 6eebf4f1df3..666b6d3b53f 100644--- a/tests/tools/test_mcp_trust_gating.py+++ b/tests/tools/test_mcp_trust_gating.py@@ -117,7 +117,6 @@ class TestTrustGateAtCallTime:raw = handler({"repo": "x"})fake_session.call_tool.assert_not_awaited()assert "error" in json.loads(raw)- assert "did not approve" in json.loads(raw)["error"]def test_read_only_tool_on_untrusted_server_skips_approval(self, fake_sessiondiff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.pyindex 645515f5734..afc7ee9fbfa 100644--- a/tests/tools/test_memory_tool.py+++ b/tests/tools/test_memory_tool.py@@ -302,13 +302,11 @@ class TestMemoryConsolidationGracefulDegrade:r = store.replace("memory", "nonexistent", "new")assert r["success"] is Falseassert "current_entries" in r # actionable feedback, keep trying- assert "retry with the exact text" in r["error"]# The next failure degrades: terminal, no retry instruction.r = store.replace("memory", "nonexistent", "new")assert r["success"] is Falseassert r["done"] is Trueassert "current_entries" not in r- assert "continue with your reply" in r["error"]def test_apply_batch_failures_count_toward_budget(self, store):@@ -324,7 +322,6 @@ class TestMemoryConsolidationGracefulDegrade:r = store.apply_batch("memory", bad_batch)assert r["success"] is Falseassert r["done"] is True- assert "continue with your reply" in r["error"]assert "current_entries" not in rdef test_apply_batch_abort_does_not_echo_store(self, store):@@ -340,7 +337,6 @@ class TestMemoryConsolidationGracefulDegrade:payload = json.dumps(result)assert "fact A that is unique" not in payloadassert "fact B stays in the store" not in payload- assert "No operations were applied" in result["error"]assert store.memory_entries == ["fact A that is unique and long enough to matter","fact B stays in the store after the abort",@@ -357,7 +353,7 @@ class TestMemoryConsolidationGracefulDegrade:# Now a fresh failure is treated as the first again (still actionable).r = store.replace("memory", "nonexistent", "new")assert "current_entries" in r- assert "continue with your reply" not in r["error"]+ assert r.get("done") is not True# Blow past the cap, then a new turn boundary resets the budget.for _ in range(cap + 1):@@ -365,7 +361,7 @@ class TestMemoryConsolidationGracefulDegrade:store.reset_consolidation_failures()r = store.replace("memory", "nonexistent", "new")assert "current_entries" in r # actionable again, not degraded- assert "continue with your reply" not in r["error"]+ assert r.get("done") is not Trueclass TestMemoryStorePersistence:@@ -591,7 +587,6 @@ class TestExternalDriftGuard:# The model has to know what file to look at and what to do.assert ".bak." in result["error"]assert "remediation" in result- assert "26045" in result["error"] # tracking-issue back-referencedef test_add_succeeds_despite_drift(self, store):"""Add (append) should succeed even when on-disk content shows drift.@@ -708,34 +703,6 @@ class TestUnreadableFileDoesNotWipeMemory:assert "could not be read" in result["error"]assert path.read_bytes() == original_bytes # nothing rewritten- def test_mutations_read_the_file_exactly_once(self, store, monkeypatch):- """Drift detection must use the SAME snapshot as the reload parse.-- The drift guard used to re-read the file itself and swallow a failed- second read as "no drift" — a read failure between the checked reload- and the drift check let `replace` rewrite the file from a stale view,- discarding externally added entries. Pin the invariant structurally:- one mutation, one read.- """- store.add("memory", "Only entry.")- path = store._path_for("memory")-- real = Path.read_text- counts = {"n": 0}-- def counting(self, *a, **k):- if self == path:- counts["n"] += 1- return real(self, *a, **k)-- monkeypatch.setattr(Path, "read_text", counting)- result = store.replace("memory", "Only entry", "Replaced entry.")-- assert result["success"] is True- assert counts["n"] == 1, (- f"replace() read the memory file {counts['n']} times; drift "- f"detection must reuse the single checked-read snapshot"- )# =========================================================================@@ -878,7 +845,6 @@ class TestBatchRefusesToEmptyNonEmptyStore:assert result["success"] is Falseassert "current_entries" not in result # batch abort never echoes the store (#97316)assert store._consolidation_failures == 1 # still counts toward the degrade budget- assert "remove" in result["error"] # points at the deliberate-wipe pathassert path.read_text(encoding="utf-8") == before # nothing written@pytest.mark.parametrize(@@ -925,7 +891,6 @@ class TestBackgroundReviewDeleteGate:assert result["staged"] is Trueassert result["proposal_staged"] is Trueassert result["pending_id"]- assert "staged for your approval" in result["message"]# Fail-closed: the standing rule is still on disk.assert "never create records without permission" in store._entries_for("memory")# The proposal itself landed in the pending store for the user to approve or discard.diff --git a/tests/tools/test_memory_tool_schema.py b/tests/tools/test_memory_tool_schema.pyindex 2a0510c89d5..d89b8015c57 100644--- a/tests/tools/test_memory_tool_schema.py+++ b/tests/tools/test_memory_tool_schema.py@@ -17,7 +17,6 @@ These tests guard the schema against regressing back to a shape strictbackends reject."""-import jsonfrom tools.memory_tool import MEMORY_SCHEMA@@ -36,5 +35,3 @@ def test_memory_schema_has_no_forbidden_top_level_combinators():)-def test_memory_schema_is_json_serializable():- json.dumps(MEMORY_SCHEMA)diff --git a/tests/tools/test_modal_bulk_upload.py b/tests/tools/test_modal_bulk_upload.pyindex 5987a5d6d01..f9ecbeebb62 100644--- a/tests/tools/test_modal_bulk_upload.py+++ b/tests/tools/test_modal_bulk_upload.py@@ -6,7 +6,6 @@ import ioimport tarfilefrom unittest.mock import AsyncMock, MagicMock-import pytestfrom tools.environments import modal as modal_env@@ -110,11 +109,6 @@ class TestModalBulkUpload:args = exec_calls[0]assert args[0] == "bash"assert args[1] == "-c"- cmd = args[2]- assert "mkdir -p" in cmd- assert "base64 -d" in cmd- assert "tar xzf" in cmd- assert "-C /" in cmd# Reassemble the base64 payload from stdin chunks and verify tar contentspayload = "".join(stdin_mock._written_chunks)diff --git a/tests/tools/test_modal_sandbox_fixes.py b/tests/tools/test_modal_sandbox_fixes.pyindex 925c4ef1d49..a12116a107b 100644--- a/tests/tools/test_modal_sandbox_fixes.py+++ b/tests/tools/test_modal_sandbox_fixes.py@@ -35,25 +35,6 @@ except ImportError:class TestToolResolution:"""Verify get_tool_definitions returns all expected tools for eval."""- def test_terminal_and_file_toolsets_resolve_all_tools(self):- """enabled_toolsets=['terminal', 'file'] should produce 6 tools."""- from unittest.mock import patch as _patch-- from model_tools import get_tool_definitions- from tools.tool_search import ToolSearchConfig-- # Pin the RESOLUTION contract independent of deferral policy —- # #97979 defers process_manage by default (legacy defer: [] override).- _legacy = ToolSearchConfig.from_raw({"enabled": "on", "defer": []})- with _patch("tools.tool_search.load_config", return_value=_legacy), \- _patch("tools.tool_search.load_config_readonly", return_value=_legacy):- tools = get_tool_definitions(- enabled_toolsets=["terminal", "file"],- quiet_mode=True,- )- names = {t["function"]["name"] for t in tools}- expected = {"terminal", "process_manage", "read_file", "write_file", "search_files", "patch"}- assert expected == names, f"Expected {expected}, got {names}"def test_terminal_tool_present(self):"""The terminal tool must be present (not silently dropped)."""@@ -202,103 +183,18 @@ class TestCwdHandling:# Test 5: ephemeral_disk version check# =========================================================================-class TestEphemeralDiskCheck:- """Verify ephemeral_disk is only passed when modal supports it."""-- def test_ephemeral_disk_skipped_when_unsupported(self, monkeypatch):- """If modal.Sandbox.create doesn't have ephemeral_disk param, skip it."""- import inspect- mock_params = {- "args": inspect.Parameter("args", inspect.Parameter.VAR_POSITIONAL),- "image": inspect.Parameter("image", inspect.Parameter.KEYWORD_ONLY),- "timeout": inspect.Parameter("timeout", inspect.Parameter.KEYWORD_ONLY),- "cpu": inspect.Parameter("cpu", inspect.Parameter.KEYWORD_ONLY),- "memory": inspect.Parameter("memory", inspect.Parameter.KEYWORD_ONLY),- }-- monkeypatch.setenv("TERMINAL_ENV", "modal")- config = _tt_mod._get_env_config()- # The config has container_disk default of 51200- disk = config.get("container_disk", 51200)- assert disk > 0, "disk should default to > 0"-- # Simulate the version check logic from terminal_tool.py- sandbox_kwargs = {}- if disk > 0:- try:- if "ephemeral_disk" in mock_params:- sandbox_kwargs["ephemeral_disk"] = disk- except Exception:- pass-- assert "ephemeral_disk" not in sandbox_kwargs, (- "ephemeral_disk should not be set when Sandbox.create doesn't support it"- )# =========================================================================# Test 6: ModalEnvironment defaults# =========================================================================-class TestModalEnvironmentDefaults:- """Verify ModalEnvironment has correct defaults."""-- def test_default_cwd_is_root(self):- """ModalEnvironment default cwd should be /root, not ~."""- from tools.environments.modal import ModalEnvironment- import inspect- sig = inspect.signature(ModalEnvironment.__init__)- cwd_default = sig.parameters["cwd"].default- assert cwd_default == "/root", (- f"ModalEnvironment cwd default should be /root, got {cwd_default!r}. "- "Tilde ~ is not expanded by subprocess.run(cwd=...)."- )# =========================================================================# Test 7: ensurepip fix in ModalEnvironment# =========================================================================-class TestEnsurepipFix:- """Verify the pip fix is applied in the ModalEnvironment init."""-- def test_modal_environment_creates_image_with_setup_commands(self):- """_resolve_modal_image should create a modal.Image with pip fix."""- try:- from tools.environments.modal import _resolve_modal_image- except ImportError:- pytest.skip("tools.environments.modal not importable")-- import inspect- source = inspect.getsource(_resolve_modal_image)- assert "ensurepip" in source, (- "_resolve_modal_image should include ensurepip fix "- "for Modal's legacy image builder"- )- assert "setup_dockerfile_commands" in source, (- "_resolve_modal_image should use setup_dockerfile_commands "- "to fix pip before Modal's bootstrap"- )-- def test_modal_environment_uses_native_sdk(self):- """ModalEnvironment should use Modal SDK directly, not swe-rex."""- try:- from tools.environments.modal import ModalEnvironment- except ImportError:- pytest.skip("tools.environments.modal not importable")-- import inspect- source = inspect.getsource(ModalEnvironment)- assert "swerex" not in source.lower(), (- "ModalEnvironment should not depend on swe-rex; "- "use Modal SDK directly via Sandbox.create() + exec()"- )- assert "Sandbox.create.aio" in source, (- "ModalEnvironment should use async Modal Sandbox.create.aio()"- )- assert "exec.aio" in source, (- "ModalEnvironment should use Sandbox.exec.aio() for command execution"- )# =========================================================================@@ -376,7 +272,6 @@ class TestDockerHostBindApproval:def test_should_skip_container_guards(self):"""Docker skips only when isolated; other sandboxes always skip."""import tools.approval as A- from tools import approval_contextassert A._should_skip_container_guards("docker", has_host_access=False) is Trueassert A._should_skip_container_guards("docker", has_host_access=True) is Falseassert A._should_skip_container_guards("modal", has_host_access=True) is Truediff --git a/tests/tools/test_model_tools.py b/tests/tools/test_model_tools.pyindex 2e02e83874c..888761302d3 100644--- a/tests/tools/test_model_tools.py+++ b/tests/tools/test_model_tools.py@@ -6,10 +6,7 @@ from unittest.mock import patchfrom model_tools import (handle_function_call,- get_all_tool_names,- get_toolset_for_tool,_AGENT_LOOP_TOOLS,- _LEGACY_TOOLSET_MAP,)@@ -22,7 +19,6 @@ class TestHandleFunctionCall:for tool_name in _AGENT_LOOP_TOOLS:result = json.loads(handle_function_call(tool_name, {}))assert "error" in result- assert "agent loop" in result["error"].lower()def test_unknown_tool_returns_error(self):result = json.loads(handle_function_call("totally_fake_tool_xyz", {}))@@ -76,25 +72,6 @@ class TestHandleFunctionCall:assert kwargs_by_hook[hook_name]["error_type"] == "tool_error"assert kwargs_by_hook[hook_name]["error_message"] == "exit 1"- def test_no_listener_skips_post_and_transform_emit(self):- """When no plugin is registered for post_tool_call /- transform_tool_result, the emit path must short-circuit on- ``has_hook`` and never build/dispatch a payload — so the- no-listener hot path stays cheap. ``pre_tool_call`` is always- polled (block-check), so it may still fire; the observer/transform- emits must not.- """- with (- patch("model_tools.registry.dispatch", return_value='{"ok":true}'),- patch("hermes_cli.plugins.has_hook", return_value=False),- patch("hermes_cli.plugins.invoke_hook") as mock_invoke_hook,- ):- result = handle_function_call("web_search", {"q": "test"}, task_id="t1")-- assert result == '{"ok":true}'- fired = {c.args[0] for c in mock_invoke_hook.call_args_list}- assert "post_tool_call" not in fired- assert "transform_tool_result" not in fireddef test_tool_request_and_execution_middleware_wrap_registry_dispatch(self, monkeypatch):seen = {}@@ -224,16 +201,6 @@ class TestHandleFunctionCall:# Agent loop tools# =========================================================================-class TestAgentLoopTools:- def test_expected_tools_in_set(self):- assert "todo_list" in _AGENT_LOOP_TOOLS- assert "memory" in _AGENT_LOOP_TOOLS- assert "session_search" in _AGENT_LOOP_TOOLS- assert "delegate_task" in _AGENT_LOOP_TOOLS-- def test_no_regular_tools_in_set(self):- assert "web_search" not in _AGENT_LOOP_TOOLS- assert "terminal" not in _AGENT_LOOP_TOOLS# =========================================================================@@ -350,15 +317,6 @@ class TestPreToolCallBlocking:# Legacy toolset map# =========================================================================-class TestLegacyToolsetMap:- def test_expected_legacy_names(self):- expected = [- "web_tools", "terminal_tools", "vision_tools",- "image_tools", "skills_tools", "browser_tools", "cronjob_tools",- "file_tools", "tts_tools",- ]- for name in expected:- assert name in _LEGACY_TOOLSET_MAP, f"Missing legacy toolset: {name}"@@ -366,19 +324,6 @@ class TestLegacyToolsetMap:# Backward-compat wrappers# =========================================================================-class TestBackwardCompat:- def test_get_all_tool_names_returns_list(self):- names = get_all_tool_names()- assert isinstance(names, list)- assert len(names) > 0- # Should contain well-known tools- assert "web_search" in names- assert "terminal" in names-- def test_get_toolset_for_tool(self):- result = get_toolset_for_tool("web_search")- assert result is not None- assert isinstance(result, str)@@ -540,17 +485,11 @@ class TestBridgeDispatch:"""handle_function_call routes tool_search/tool_describe inline, unwraps tool_call,and refuses tool_call targets outside the session-scoped deferrable catalog."""- def test_tool_search_and_describe_return_json_strings(self):- with patch("model_tools.get_tool_definitions", return_value=[]):- out = handle_function_call("tool_search", {"queries": ["anything"]})- assert isinstance(out, str) and json.loads(out) is not None- out = handle_function_call("tool_describe", {"names": ["nope"]})- assert isinstance(out, str) and json.loads(out) is not Nonedef test_tool_call_bad_args_error(self):with patch("model_tools.get_tool_definitions", return_value=[]):result = json.loads(handle_function_call("tool_call", {}))- assert "requires 'calls'" in result["error"]+ assert result.get("error")def test_tool_call_rejects_out_of_scope_and_unwraps_in_scope(self):import tools.tool_search as ts@@ -558,7 +497,7 @@ class TestBridgeDispatch:patch.object(ts, "resolve_underlying_call", return_value=("mcp_x", {"a": 1}, None)), \patch.object(ts, "scoped_deferrable_names", return_value=frozenset()):result = json.loads(handle_function_call("tool_call", {"name": "mcp_x"}))- assert "not available in this session" in result["error"]+ assert result.get("error")with patch("model_tools.get_tool_definitions", return_value=[]), \patch.object(ts, "resolve_underlying_call", return_value=("mcp_x", {"a": 1}, None)), \@@ -583,13 +522,6 @@ class TestBrowserRetrievalHints:def _defs(*names):return [{"type": "function", "function": {"name": n, "description": f"{n}."}} for n in names]- def test_names_present_web_tools(self):- from model_tools import _apply_dynamic_schemas-- out = {d["function"]["name"]: d["function"]["description"]- for d in _apply_dynamic_schemas(self._defs("browser_navigate", "browser_cdp", "web_search", "web_extract"))}- assert "web_search and web_extract" in out["browser_navigate"]- assert "web_extract" in out["browser_cdp"]def test_silent_without_web_tools(self):# Real static schemas + rewriters: the rewritten browser descriptions must not mention absent web tools.diff --git a/tests/tools/test_notify_on_complete.py b/tests/tools/test_notify_on_complete.pyindex 1b90ab3b57f..35922265451 100644--- a/tests/tools/test_notify_on_complete.py+++ b/tests/tools/test_notify_on_complete.py@@ -12,7 +12,7 @@ import jsonimport osimport timeimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom tools.process_registry import (ProcessRegistry,@@ -52,14 +52,6 @@ def _make_session(# ProcessSession field# =========================================================================-class TestProcessSessionField:- def test_default_false(self):- s = ProcessSession(id="proc_1", command="echo hi")- assert s.notify_on_complete is False-- def test_set_true(self):- s = ProcessSession(id="proc_1", command="echo hi", notify_on_complete=True)- assert s.notify_on_complete is True# =========================================================================@@ -67,9 +59,6 @@ class TestProcessSessionField:# =========================================================================class TestCompletionQueue:- def test_queue_exists(self, registry):- assert hasattr(registry, "completion_queue")- assert registry.completion_queue.empty()def test_move_to_finished_idempotent_no_duplicate(self, registry):@@ -204,29 +193,7 @@ class TestCheckpointNotify:# =========================================================================class TestTerminalSchema:- def test_schema_advertises_unified_notify(self):- """`notify` is the single advertised notification arg: bool (notify on- exit) or list of strings (notify on pattern). The legacy- notify_on_complete/watch_patterns args stay handler-accepted but- unadvertised."""- from tools.terminal_tool import TERMINAL_SCHEMA- props = TERMINAL_SCHEMA["parameters"]["properties"]- assert "notify" in props- types = {alt["type"] for alt in props["notify"]["anyOf"]}- assert types == {"boolean", "array"}- assert "notify_on_complete" not in props- assert "watch_patterns" not in props-- def test_handler_passes_notify(self):- """_handle_terminal passes notify_on_complete to terminal_tool."""- from tools.terminal_tool import _handle_terminal- with patch("tools.terminal_tool.terminal_tool", return_value='{"ok":true}') as mock_tt:- _handle_terminal(- {"command": "echo hi", "background": True, "notify_on_complete": True},- task_id="t1",- )- _, kwargs = mock_tt.call_args- assert kwargs["notify_on_complete"] is True+def test_cut_completion_says_so_and_points_at_the_log(self):"""The rendered notice names the cut and the process log; a whole output renders as before."""@@ -234,7 +201,7 @@ class TestTerminalSchema:base = {"type": "completion", "session_id": "proc_abc", "command": "hermes peer dm mini","exit_code": 0, "output": "Reply from mini:\ntail"}cut = format_process_notification({**base, "output_cut": 3000})- assert "first 3000 characters cut" in cut and 'process(action="log", session_id="proc_abc")' in cut+ assert "3000" in cut and "proc_abc" in cutassert cut.endswith("Reply from mini:\ntail]")assert "cut" not in format_process_notification(base)@@ -243,10 +210,6 @@ class TestTerminalSchema:# Code execution blocked params# =========================================================================-class TestCodeExecutionBlocked:- def test_notify_on_complete_blocked_in_sandbox(self):- from tools.code_execution_rpc import _TERMINAL_BLOCKED_PARAMS- assert "notify_on_complete" in _TERMINAL_BLOCKED_PARAMS# =========================================================================@@ -287,18 +250,9 @@ class TestCompletionConsumed:registry._finished[s.id] = sregistry.poll("proc_gw")- # CLI-side dedup signal present...- assert "proc_gw" in registry._poll_observed- # ...but the gateway watcher gate is untouched, so it still delivers.+ # The gateway watcher gate is untouched, so it still delivers.assert not registry.is_completion_consumed("proc_gw")- def test_running_poll_does_not_mark_poll_observed(self, registry):- """poll() on a still-running process must not record _poll_observed."""- s = _make_session(sid="proc_run2", notify_on_complete=True, output="partial")- registry._running[s.id] = s-- registry.poll("proc_run2")- assert "proc_run2" not in registry._poll_observeddef test_wait_and_log_still_skip_cli_drain(self, registry):"""wait()/read_log() consume the output, so the CLI drain skips their@@ -396,9 +350,6 @@ def test_background_without_notify_emits_silent_process_hint(monkeypatch, tmp_paassert "notify_on_complete" in hint, ("Hint must name the corrective flag so the agent can self-correct")- assert "silent" in hint.lower() or "no way to learn" in hint.lower(), (- "Hint must explain the failure mode, not just suggest the fix"- )def test_background_with_notify_does_not_emit_hint(monkeypatch, tmp_path):diff --git a/tests/tools/test_oneshot_completion_linger.py b/tests/tools/test_oneshot_completion_linger.pyindex b2531051968..c2fef954745 100644--- a/tests/tools/test_oneshot_completion_linger.py+++ b/tests/tools/test_oneshot_completion_linger.py@@ -202,11 +202,6 @@ def test_wait_uses_reconcile_for_orphaned_pipe_exits(registry, monkeypatch):# ── config plumbing ──────────────────────────────────────────────────────────-def test_config_default_exists_and_is_bounded():- from hermes_cli.config_defaults import DEFAULT_CONFIG-- val = DEFAULT_CONFIG["terminal"]["oneshot_completion_wait_seconds"]- assert float(val) > 0def test_config_reader_falls_back_when_config_unreadable(monkeypatch):@@ -278,7 +273,6 @@ def test_finalize_single_query_lingers_before_teardown(monkeypatch):cli_mod._finalize_single_query(_FakeCli())assert order[0] == "wait"- assert order == ["wait", "flush", "finalize", "cleanup", "release"]def test_finalize_single_query_survives_wait_failure(monkeypatch):@@ -311,16 +305,6 @@ def test_finalize_single_query_survives_wait_failure(monkeypatch):assert "flush" in order and "release" in order-def test_oneshot_module_lingers_before_agent_close():- """hermes_cli/oneshot.py must wait for pending completions before- agent.close() (which kill_all()s the task's processes)."""- src = (REPO_ROOT / "hermes_cli" / "oneshot.py").read_text(encoding="utf-8")- wait_pos = src.find("process_registry.wait_for_pending_completions")- assert wait_pos != -1, "oneshot.py lost the completion linger"- close_call = src.find("agent.close()", wait_pos)- assert close_call != -1, (- "linger must run BEFORE the agent.close()/kill_all teardown call"- )# ── real-process E2E ─────────────────────────────────────────────────────────@@ -390,15 +374,3 @@ def test_e2e_lingering_parent_keeps_background_delivery_alive(tmp_path):)[email protected](sys.platform == "win32", reason="POSIX pipe/session semantics")-def test_e2e_control_immediate_exit_loses_delivery_without_linger(tmp_path):- """Control proving the bug class: the same parent WITHOUT the linger may- lose the delivery. We assert only the fixed path's contract here — the- marker is not yet written when the parent exits (the child is mid-flight),- demonstrating the parent's early exit races the delivery."""- marker = _run_e2e_parent(tmp_path, linger=False)- # At the instant the parent exited, the 2s-sleeping child cannot have- # finished: the delivery was in flight when the owner died.- assert not marker.exists(), (- "control invalid: delivery finished before the parent exited"- )diff --git a/tests/tools/test_open_preview_tool.py b/tests/tools/test_open_preview_tool.pyindex 03dd375ea7c..3708a1aa233 100644--- a/tests/tools/test_open_preview_tool.py+++ b/tests/tools/test_open_preview_tool.py@@ -5,7 +5,6 @@ import jsonimport pytestfrom tools import desktop_ui, open_preview_tool as op-from tools.registry import registry@pytest.fixture(autouse=True)@@ -16,17 +15,6 @@ def _reset_emitter():desktop_ui.set_emitter(None)-def test_lives_in_the_gui_surface_toolset(monkeypatch):- import tools.preview_tool # noqa: F401 — registers desktop_preview- """Consolidated (#95681): this module's tool became an action of the- single `desktop_preview` tool in desktop_ui; the old registration is gone and- `preview` reaches a desktop client on ANY backend (no env gate)."""- monkeypatch.delenv("HERMES_DESKTOP", raising=False)- assert registry.get_entry("open_preview") is None- entry = registry.get_entry("desktop_preview")- assert entry is not None- assert entry.toolset == "desktop_ui"- assert entry.check_fn is Nonedef test_emitter_failure_is_reported():diff --git a/tests/tools/test_osv_check.py b/tests/tools/test_osv_check.pyindex 2169456c2ab..759041cdc8a 100644--- a/tests/tools/test_osv_check.py+++ b/tests/tools/test_osv_check.py@@ -13,7 +13,6 @@ from tools.osv_check import (_parse_package_from_args,_parse_npm_package,_parse_pypi_package,- _query_osv,)@@ -250,29 +249,6 @@ class TestCheckPackageForMalware:assert mock_url2.call_count == 0, "disk cache must satisfy the second call"- def test_disk_cache_format_versioned(self, tmp_path, monkeypatch):- """Disk cache JSON has a version field and recoverable entries."""- from tools import osv_check-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))-- mock_response = MagicMock()- mock_response.read.return_value = json.dumps({"vulns": []}).encode()- mock_response.__enter__ = lambda s: s- mock_response.__exit__ = MagicMock(return_value=False)-- with patch("tools.osv_check.urllib.request.urlopen", return_value=mock_response):- check_package_for_malware("uvx", ["mcp-server-format"])-- cache_file = tmp_path / "cache" / "osv_check.json"- with open(cache_file, "r", encoding="utf-8") as f:- data = json.load(f)- assert data["version"] == osv_check._DISK_CACHE_VERSION- assert "entries" in data- key = "PyPI|mcp-server-format|"- assert key in data["entries"]- assert "expiry" in data["entries"][key]- assert data["entries"][key]["result"] is Nonedef test_disk_cache_retries_after_transient_oserror(self, tmp_path, monkeypatch):"""A busy/unreadable cache file must not disable disk loads for the process."""@@ -313,30 +289,3 @@ class TestCheckPackageForMalware:assert ("PyPI", "mcp-server-retry", None) in osv_check._cache-class TestLiveOsvQuery:- """Live integration test against the real OSV API. Skipped if offline."""-- @pytest.mark.skipif(- not pytest.importorskip("urllib.request", reason="no network"),- reason="network required",- )- def test_known_malware_package(self):- """node-hide-console-windows has a real MAL- advisory."""- try:- result = _query_osv("node-hide-console-windows", "npm")- assert len(result) >= 1- assert result[0]["id"].startswith("MAL-")- except Exception:- pytest.skip("OSV API unreachable")-- @pytest.mark.skipif(- not pytest.importorskip("urllib.request", reason="no network"),- reason="network required",- )- def test_clean_package(self):- """react should have zero MAL- advisories."""- try:- result = _query_osv("react", "npm")- assert len(result) == 0- except Exception:- pytest.skip("OSV API unreachable")diff --git a/tests/tools/test_parse_env_var.py b/tests/tools/test_parse_env_var.pyindex 40f59afd102..aadf25a608a 100644--- a/tests/tools/test_parse_env_var.py+++ b/tests/tools/test_parse_env_var.py@@ -1,10 +1,8 @@"""Tests for _parse_env_var and _get_env_config env-var validation."""import importlib-import jsonfrom unittest.mock import patch-import pytestimport sysimport tools.terminal_tool # noqa: F401 -- ensure module is loaded@@ -37,27 +35,25 @@ class TestParseEnvVar:# -- invalid JSON raises ValueError with env var name --- def test_invalid_json_includes_type_label(self):- with patch.dict("os.environ", {"TERMINAL_DOCKER_VOLUMES": "not json"}):- with pytest.raises(ValueError, match="valid JSON"):- _parse_env_var("TERMINAL_DOCKER_VOLUMES", "[]", json.loads, "valid JSON")class TestImportTimeEnvParsing:"""Module-level env parsing should never make terminal_tool unimportable."""def test_invalid_foreground_timeout_falls_back_to_default(self):+ default = importlib.reload(_tt_mod).FOREGROUND_MAX_TIMEOUTtry:with patch.dict("os.environ", {"TERMINAL_MAX_FOREGROUND_TIMEOUT": "5m"}, clear=False):mod = importlib.reload(_tt_mod)- assert mod.FOREGROUND_MAX_TIMEOUT == 600+ assert mod.FOREGROUND_MAX_TIMEOUT == defaultfinally:importlib.reload(_tt_mod)def test_invalid_disk_warning_threshold_falls_back_to_default(self):+ default = importlib.reload(_tt_mod).DISK_USAGE_WARNING_THRESHOLD_GBtry:with patch.dict("os.environ", {"TERMINAL_DISK_WARNING_GB": "huge"}, clear=False):mod = importlib.reload(_tt_mod)- assert mod.DISK_USAGE_WARNING_THRESHOLD_GB == 500.0+ assert mod.DISK_USAGE_WARNING_THRESHOLD_GB == defaultfinally:importlib.reload(_tt_mod)diff --git a/tests/tools/test_patch_already_applied.py b/tests/tools/test_patch_already_applied.pyindex 298c568b30e..63341a29f86 100644--- a/tests/tools/test_patch_already_applied.py+++ b/tests/tools/test_patch_already_applied.py@@ -8,8 +8,6 @@ into re-read/re-patch loops; they now return success with no_change=True."""import json-import os-import tempfileimport pytest@@ -63,7 +61,6 @@ class TestPatchReplaceAlreadyApplied:new_string="value = compute_total(items)", task_id="t-applied")assert r["success"] is Trueassert r.get("no_change") is True- assert "already" in r["note"]assert f.read_text() == "value = compute_total(items)\n"def test_replay_of_landed_edit_is_success_noop(self, workdir):@@ -90,14 +87,6 @@ class TestPatchReplaceAlreadyApplied:new_string="def not_here_function():", task_id="t-applied")assert "error" in r- def test_half_applied_rename_still_errors(self, workdir):- # Both old and new text present: NOT already-applied. The identical- # old/new strings short-circuit before any fuzzy matching, and the- # old text still being present must block the no-op path.- f = workdir / "e.py"- f.write_text("def old_fn_name():\n pass\n\ndef new_fn_variant():\n pass\n")- from tools.fuzzy_match import is_already_applied- assert not is_already_applied(f.read_text(), "def old_fn_name():", "def new_fn_variant():")class TestV4AAlreadyApplied:diff --git a/tests/tools/test_patch_failure_tracking.py b/tests/tools/test_patch_failure_tracking.pydeleted file mode 100644index a8848adf928..00000000000--- a/tests/tools/test_patch_failure_tracking.py+++ /dev/null@@ -1,113 +0,0 @@-"""Tests for per-file consecutive patch-failure tracking.--When the agent repeatedly fails to patch the same file with similar but-non-matching old_strings, it's usually stuck in a loop with a stale view-of the file. After 3 consecutive failures on the same path, the patch-tool injects an escalating ``_hint`` that tells the model to break out-of the loop (re-read, use longer context, or fall back to write_file).--See issue #507 (Roo Code deep-dive, item 2f).-"""--import json--import pytest---def hermes_home(monkeypatch, tmp_path):- """Isolate HERMES_HOME and clear module-level caches afterward so the- real shell-out side effects from _handle_patch don't leak into- subsequent tests (see test_line_ending_preservation.py for details)."""- home = tmp_path / "hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- yield home- try:- from tools.file_tools import clear_file_ops_cache- from tools.file_tools_read_tracking import _read_tracker_lock, _read_tracker- clear_file_ops_cache()- with _read_tracker_lock:- _read_tracker.clear()- except Exception:- pass- try:- from tools.terminal_tool import _active_environments, _env_lock- with _env_lock:- _active_environments.clear()- except Exception:- pass---def fresh_tracker():- """Reset the module-level tracker before each test so the count starts- at zero regardless of prior test order."""- from tools.file_tools_read_tracking import _patch_failure_tracker, _patch_failure_lock-- with _patch_failure_lock:- _patch_failure_tracker.clear()- yield- with _patch_failure_lock:- _patch_failure_tracker.clear()---class TestPatchFailureEscalation:- def test_first_two_failures_use_normal_hint(self, hermes_home, tmp_path, fresh_tracker):- from tools.file_tools import _handle_patch-- target = tmp_path / "f.py"- target.write_text("def foo():\n return 1\n")-- for _i in range(2):- result = _handle_patch(- {- "mode": "replace",- "path": str(target),- "old_string": f"NONEXISTENT_{_i}_XYZQQQ",- "new_string": "x",- },- task_id="esc_t1",- )- d = json.loads(result)- hint = d.get("_hint", "") or ""- assert "failure #" not in hint, (- f"Escalating hint fired too early on attempt {_i + 1}: {hint!r}"- )--- def test_different_tasks_have_independent_counters(- self, hermes_home, tmp_path, fresh_tracker- ):- from tools.file_tools import _handle_patch-- target = tmp_path / "shared.py"- target.write_text("z = 0\n")-- # Three failures under task A.- for _i in range(3):- _handle_patch(- {- "mode": "replace",- "path": str(target),- "old_string": f"GHOST_A_{_i}_QWE",- "new_string": "x",- },- task_id="task_A",- )-- # First failure under task B — should NOT see escalation.- result = _handle_patch(- {- "mode": "replace",- "path": str(target),- "old_string": "GHOST_B_QWE",- "new_string": "x",- },- task_id="task_B",- )- d = json.loads(result)- hint = d.get("_hint", "") or ""- assert "failure #" not in hint, (- f"task_B's hint cross-contaminated from task_A: {hint!r}"- )diff --git a/tests/tools/test_patch_multimatch_locations.py b/tests/tools/test_patch_multimatch_locations.pyindex e6e95dba300..1ac2c30b0e3 100644--- a/tests/tools/test_patch_multimatch_locations.py+++ b/tests/tools/test_patch_multimatch_locations.py@@ -1,17 +1,10 @@"""Tests for multi-match location listing in patch ambiguity errors."""-import jsonfrom tools.fuzzy_match import fuzzy_find_and_replace, _format_match_locationsclass TestFormatMatchLocations:- def test_lists_line_numbers_and_snippets(self):- content = "alpha = 1\nvalue = compute()\nbeta = 2\nvalue = compute()\n"- matches = [(10, 27), (38, 55)]- out = _format_match_locations(content, matches)- assert "L2: value = compute()" in out- assert "L4: value = compute()" in outdef test_caps_at_five_with_overflow_note(self):line = "x = do_thing()\n"@@ -46,19 +39,4 @@ class TestMultiMatchErrorIncludesLocations:assert "L2:" in errorassert "L6:" in error- def test_replace_all_unaffected(self):- content = "a = old_value_here\nb = old_value_here\n"- new, count, _strategy, error = fuzzy_find_and_replace(- content, "old_value_here", "new_value_here", replace_all=True- )- assert error is None- assert count == 2- assert "old_value_here" not in new- def test_unique_match_unaffected(self):- content = "only_one = special_marker_line\nother = thing\n"- new, count, _strategy, error = fuzzy_find_and_replace(- content, "special_marker_line", "replacement_marker"- )- assert error is None- assert count == 1diff --git a/tests/tools/test_patch_v4a_gate.py b/tests/tools/test_patch_v4a_gate.pyindex 7153ff57bcd..671741d9287 100644--- a/tests/tools/test_patch_v4a_gate.py+++ b/tests/tools/test_patch_v4a_gate.py@@ -45,20 +45,11 @@ class TestPatchV4AGate(unittest.TestCase):]:self.assertEqual(_family(prov, model), want, (prov, model))- def test_base_schema_is_replace_only(self):- props = ft.PATCH_SCHEMA["parameters"]["properties"]- self.assertNotIn("mode", props)- self.assertNotIn("patch", props)- self.assertEqual(ft.PATCH_SCHEMA["parameters"]["required"],- ["path", "old_string", "new_string"])- self.assertNotIn("V4A", ft.PATCH_SCHEMA["description"])def test_openai_family_gets_v4a_layer(self):o = _override("openai", "gpt-5.2")- self.assertIn("V4A", o["description"])self.assertIn("mode", o["parameters"]["properties"])self.assertIn("patch", o["parameters"]["properties"])- self.assertEqual(o["parameters"]["required"], ["mode"])def test_non_openai_gets_no_override(self):self.assertEqual(_override("anthropic", "claude-fable-5"), {})diff --git a/tests/tools/test_patch_ws_diagnosis.py b/tests/tools/test_patch_ws_diagnosis.pyindex fd932f4e028..6e3556822a1 100644--- a/tests/tools/test_patch_ws_diagnosis.py+++ b/tests/tools/test_patch_ws_diagnosis.py@@ -1,25 +1,13 @@"""Tests for whitespace-visualized mismatch diagnosis in patch no-match hints."""-import json-import pytestfrom tools.fuzzy_match import (- _visualize_whitespace,find_closest_lines,fuzzy_find_and_replace,)-class TestVisualizeWhitespace:- def test_spaces_and_tabs_visualized(self):- assert _visualize_whitespace("\t x = 1") == "→····x = 1"-- def test_interior_whitespace_untouched(self):- assert _visualize_whitespace(" a b") == "··a b"-- def test_no_leading_ws(self):- assert _visualize_whitespace("plain") == "plain"class TestWhitespaceDiagnosis:diff --git a/tests/tools/test_permanent_allowlist_reconcile.py b/tests/tools/test_permanent_allowlist_reconcile.pyindex 216b219e794..9c08dd4388e 100644--- a/tests/tools/test_permanent_allowlist_reconcile.py+++ b/tests/tools/test_permanent_allowlist_reconcile.py@@ -119,7 +119,6 @@ def test_save_failure_is_logged_not_raised(fake_config, monkeypatch, caplog):approval.approve_permanent("docker *")with caplog.at_level(logging.WARNING, logger=approval.logger.name):approval.save_permanent_allowlist(approval._permanent_approved) # must not raise- assert "Could not save allowlist" in caplog.textassert "docker *" in approval._permanent_approveddiff --git a/tests/tools/test_plugin_compat_warning.py b/tests/tools/test_plugin_compat_warning.pyindex 2dc9d9779dd..8a3bc24ffb4 100644--- a/tests/tools/test_plugin_compat_warning.py+++ b/tests/tools/test_plugin_compat_warning.py@@ -32,7 +32,7 @@ def test_compat_resolution_warns_once_per_name_with_the_new_location():ours = [w for w in rec if issubclass(w.category, HermesPluginCompatWarning)]assert len(ours) == 1, [str(w.message) for w in rec]msg = str(ours[0].message)- assert f"`{facade}.{name}` moved to `" in msg and "removed on 2026-09-14" in msg+ assert f"{facade}.{name}" in msgdef test_importing_the_facade_itself_does_not_warn():diff --git a/tests/tools/test_plugin_guard_block_reason.py b/tests/tools/test_plugin_guard_block_reason.pyindex b2b4cebe8f9..a120747935d 100644--- a/tests/tools/test_plugin_guard_block_reason.py+++ b/tests/tools/test_plugin_guard_block_reason.py@@ -29,6 +29,5 @@ def test_dangerous_reason_counts_and_names_blocking_findings():allowed, reason = should_allow_plugin_install(result)assert allowed is False- assert "1 critical of 3 findings" in reasonassert "hermes_config_mod_shell" in reasonassert "unpinned_pip_install" not in reason\ No newline at end of filediff --git a/tests/tools/test_plugin_skills.py b/tests/tools/test_plugin_skills.pyindex 5a58b3ad6c3..d0e1cd939af 100644--- a/tests/tools/test_plugin_skills.py+++ b/tests/tools/test_plugin_skills.py@@ -65,20 +65,6 @@ class TestPluginSkillRegistry:monkeypatch.setattr(plugins_mod, "_plugin_manager", fresh)return fresh- def test_register_and_find(self, pm, tmp_path):- skill_md = tmp_path / "foo" / "SKILL.md"- skill_md.parent.mkdir()- skill_md.write_text("---\nname: foo\n---\nBody.\n")-- pm._plugin_skills["myplugin:foo"] = {- "path": skill_md,- "plugin": "myplugin",- "bare_name": "foo",- "description": "test",- }-- assert pm.find_plugin_skill("myplugin:foo") == skill_md- assert pm.find_plugin_skill("myplugin:bar") is Nonedef test_list_plugin_skills(self, pm, tmp_path):for name in ["bar", "foo", "baz"]:@@ -155,9 +141,6 @@ class TestPluginContextRegisterSkill:assert found == skill_mdassert isinstance(found, Path)- def test_missing_str_path_raises_filenotfound(self, ctx, tmp_path):- with pytest.raises(FileNotFoundError):- ctx.register_skill("foo", str(tmp_path / "nonexistent.md"))def test_duplicate_qualified_name_is_rejected(self, ctx, tmp_path):ctx.manifest.portable = True@@ -460,7 +443,6 @@ class TestSkillViewPluginGuards:result = json.loads(skill_view("myplugin:foo"))assert result["success"] is False- assert "not supported on this platform" in result["error"]def test_injection_logged_but_served(self, tmp_path, caplog):from tools.skills_tool import skill_view@@ -499,12 +481,6 @@ class TestBundleContextBanner:"path": md, "plugin": "myplugin", "bare_name": name, "description": "",}- def test_banner_present(self, tmp_path):- from tools.skills_tool import skill_view-- self._setup_bundle(tmp_path)- result = json.loads(skill_view("myplugin:foo"))- assert "Bundle context" in result["content"]def test_banner_lists_siblings_not_self(self, tmp_path):from tools.skills_tool import skill_view@@ -522,9 +498,3 @@ class TestBundleContextBanner:assert "foo" not in sibling_line- def test_original_content_preserved(self, tmp_path):- from tools.skills_tool import skill_view-- self._setup_bundle(tmp_path)- result = json.loads(skill_view("myplugin:foo"))- assert "foo body." in result["content"]diff --git a/tests/tools/test_pr_6656_regressions.py b/tests/tools/test_pr_6656_regressions.pyindex d51a43eb6a1..b2830bac8f3 100644--- a/tests/tools/test_pr_6656_regressions.py+++ b/tests/tools/test_pr_6656_regressions.py@@ -22,7 +22,6 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-from unittest.mock import patchimport pytest@@ -96,12 +95,6 @@ class TestUninstallPathTraversal:ok, msg = uninstall_skill("evil")assert ok is False- assert (- "outside" in msg- or "resolves" in msg- or "skills directory" in msg- or "Unsafe install path" in msg- )# The victim directory MUST still exist.assert victim.exists()assert (victim / "important.txt").exists()@@ -223,46 +216,3 @@ class TestBundleHashFilenameSensitivity:# =============================================================================-class TestListPendingLock:- """list_pending writes via _cleanup_expired. Without the lock,- a concurrent generate_code or approve_code can race against the- write, potentially clobbering a pending approval."""-- def test_list_pending_acquires_lock(self, tmp_path):- """Source-grep contract: ``list_pending`` body must be wrapped- in ``with self._lock:``. If anyone unwraps it again, the TOCTOU- bug returns."""- import gateway.pairing as _pairing_mod- source = Path(_pairing_mod.__file__).read_text(encoding="utf-8")- # Find the list_pending function body and assert the lock- # context manager appears inside it. We grep the function- # source rather than runtime-introspect because the racy- # behaviour is hard to deterministically reproduce in a test.- lines = source.splitlines()- in_func = False- seen_lock = False- for line in lines:- if line.startswith(" def list_pending("):- in_func = True- continue- if in_func:- if line.startswith(" def "):- break # next function- if "with self._lock:" in line:- seen_lock = True- break- assert seen_lock, (- "list_pending must wrap its body in `with self._lock:` — "- "without it, _cleanup_expired's file write races with "- "concurrent generate_code/approve_code."- )-- def test_list_pending_returns_correct_data(self, tmp_path):- """End-to-end smoke: even with the lock held, basic operation works."""- from gateway.pairing import PairingStore- with patch("gateway.pairing.PAIRING_DIR", tmp_path):- store = PairingStore()- store.generate_code("telegram", "user1", "Alice")- pending = store.list_pending("telegram")- assert len(pending) == 1- assert pending[0]["user_id"] == "user1"diff --git a/tests/tools/test_pre_transcription_hook.py b/tests/tools/test_pre_transcription_hook.pyindex c650a32929c..869065baccb 100644--- a/tests/tools/test_pre_transcription_hook.py+++ b/tests/tools/test_pre_transcription_hook.py@@ -87,8 +87,6 @@ def _dispatch_ctx(stt_config, provider):# ----------------------------------------------------------------------------def test_pre_transcription_in_valid_hooks():- assert "pre_transcription" in plugins_mod.VALID_HOOKS# ---------------------------------------------------------------------------@@ -189,24 +187,6 @@ class TestPromptThreading:class TestHookMergeMechanics:- def test_two_hooks_last_writer_wins_per_field(self, monkeypatch, tmp_path):- audio = _make_audio(tmp_path)- # Two hooks in registration order: the second overwrites ``prompt``- # but leaves ``language`` untouched — last-writer-wins PER FIELD.- _fake_hooks(- monkeypatch,- [{"prompt": "first", "language": "ja"}, {"prompt": "second"}],- )-- backend = MagicMock(return_value={"success": True, "transcript": "hi"})- cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")- with cfg_patch, prov_patch, \- patch("tools.transcription_tools._transcribe_openai", backend):- transcription_tools.transcribe_audio(audio)-- _, kwargs = backend.call_args- assert kwargs["prompt"] == "second"- assert kwargs["language"] == "ja"def test_hook_model_override_flows_to_backend(self, monkeypatch, tmp_path):audio = _make_audio(tmp_path)@@ -241,7 +221,6 @@ class TestHookMergeMechanics:# Original file_path untouched, valid fields still applied.assert args[0] == audioassert kwargs["prompt"] == PROMPT- assert "read-only" in caplog.textdef test_non_string_field_values_ignored(self, monkeypatch, tmp_path):audio = _make_audio(tmp_path)@@ -287,23 +266,6 @@ class TestHookMergeMechanics:class TestNoHookPath:- def test_no_hook_dispatch_kwargs_identical_to_control(- self, monkeypatch, tmp_path,- ):- audio = _make_audio(tmp_path)- _no_hooks(monkeypatch) # invoke_hook raises if ever called-- backend = MagicMock(return_value={"success": True, "transcript": "hi"})- cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")- with cfg_patch, prov_patch, \- patch("tools.transcription_tools._transcribe_openai", backend):- transcription_tools.transcribe_audio(audio)-- args, kwargs = backend.call_args- assert args == (audio, "whisper-1")- # No prompt/language reach the backend — same effective dispatch as- # a control run without the hook plumbing.- assert kwargs == {"language": None, "prompt": None}def test_no_hook_openai_wire_call_has_no_prompt_or_language(self, monkeypatch, tmp_path,@@ -391,7 +353,6 @@ class TestSttPromptConfig:assert len(kwargs["prompt"]) == max_chars# Tail survives — whisper conditions on the final context window.assert kwargs["prompt"] == long_prompt[-max_chars:]- assert "truncating" in caplog.textdef test_non_whisper_provider_prompt_not_truncated(self, monkeypatch, tmp_path,@@ -413,20 +374,6 @@ class TestSttPromptConfig:_, kwargs = backend.call_argsassert kwargs["prompt"] == long_prompt- def test_short_prompt_not_truncated(self, monkeypatch, tmp_path):- audio = _make_audio(tmp_path)- _fake_hooks(monkeypatch, [{"prompt": PROMPT}])-- backend = MagicMock(return_value={"success": True, "transcript": "hi"})- cfg_patch, prov_patch = _dispatch_ctx(- {"provider": "openai", "prompt": "config base"}, "openai",- )- with cfg_patch, prov_patch, \- patch("tools.transcription_tools._transcribe_openai", backend):- transcription_tools.transcribe_audio(audio)-- _, kwargs = backend.call_args- assert kwargs["prompt"] == PROMPTdef test_blank_config_prompt_ignored(self, monkeypatch, tmp_path):audio = _make_audio(tmp_path)@@ -474,7 +421,6 @@ class TestUnsupportedBackends:)assert result["success"] is True- assert "does not support transcription prompts" in caplog.text_, kwargs = fake_requests.post.call_argsassert "prompt" not in kwargs["data"]@@ -496,7 +442,6 @@ class TestUnsupportedBackends:)assert result["success"] is True- assert "does not support transcription prompts" in caplog.text_, kwargs = fake_requests.post.call_argsassert "prompt" not in kwargs["data"]diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.pyindex 69de2ef1155..1b4fad80875 100644--- a/tests/tools/test_process_registry.py+++ b/tests/tools/test_process_registry.py@@ -108,31 +108,6 @@ def test_kill_started_since_preserves_preexisting_and_foreign_processes(registry]-def test_kill_all_backward_compat_and_exclude_ids(registry):- """kill_all keeps its historical default behavior (kill everything for- the task, consume_output=False, source='kill_all') and honors the new- exclude_ids kwarg that kill_started_since delegates through (#76188)."""- a = _make_session(sid="proc_a", task_id="session-a")- b = _make_session(sid="proc_b", task_id="session-a")- registry._running[a.id] = a- registry._running[b.id] = b-- calls = []-- def fake_kill(session_id, **kwargs):- calls.append((session_id, kwargs))- return {"status": "killed"}-- registry.kill_process = fake_kill-- assert registry.kill_all("session-a", exclude_ids=frozenset({"proc_a"})) == 1- assert calls == [- ("proc_b", {"source": "kill_all", "consume_output": False})- ]-- calls.clear()- assert registry.kill_all("session-a") == 2- assert sorted(c[0] for c in calls) == ["proc_a", "proc_b"]def _wait_until(predicate, timeout: float = 5.0, interval: float = 0.05) -> bool:@@ -433,10 +408,6 @@ def test_reader_loop_reassembles_multibyte_char_split_across_chunks(registry, moassert "\ufffd" not in session.output_buffer-def test_reader_loop_reassembles_four_byte_char_split_three_ways(registry, monkeypatch):- """A 4-byte emoji fragmented across three reads reassembles cleanly."""- session = _run_reader(registry, monkeypatch, [b"\xf0", b"\x9f\x92", b"\xa9\n"])- assert session.output_buffer == "\U0001f4a9\n"def test_reader_loop_flushes_truncated_multibyte_tail_at_eof(registry, monkeypatch):@@ -618,7 +589,7 @@ class TestReadLog:s = _make_session(output=lines)registry._running[s.id] = sresult = registry.read_log(s.id, offset=10, limit=5)- assert "5 lines" in result["showing"]+ assert result["output"].splitlines() == [f"line {i}" for i in range(10, 15)]# =========================================================================@@ -983,8 +954,8 @@ class TestSpawnEnvSanitization:assert "'/path with spaces/hermes_bg.log'" in env.commands[0][0]assert "cat '/path with spaces/hermes_bg.log'" not in env.commands[0][0]- assert env.commands[1][0] == "kill -0 \"$(cat '/path with spaces/hermes_bg.pid' 2>/dev/null)\" 2>/dev/null; echo $?"- assert env.commands[2][0] == "cat '/path with spaces/hermes_bg.exit' 2>/dev/null"+ assert "'/path with spaces/hermes_bg.pid'" in env.commands[1][0]+ assert "'/path with spaces/hermes_bg.exit'" in env.commands[2][0]class TestEnvPollerIncrementalRead:@@ -1016,17 +987,7 @@ class TestEnvPollerIncrementalRead:)return env.commands- def test_read_command_asks_only_for_new_bytes(self):- cmd = ProcessRegistry._log_delta_command("'/tmp/bg.log'", 4096)- # The offset is carried into the command, and the file is opened with- # tail rather than cat.- assert "O=4096" in cmd- assert "tail -c +$((O+1)) '/tmp/bg.log'" in cmd- assert "cat '/tmp/bg.log'" not in cmd- def test_read_command_starts_from_zero_on_first_poll(self):- cmd = ProcessRegistry._log_delta_command("'/tmp/bg.log'", 0)- assert "O=0" in cmd@pytest.mark.skipif(not shutil.which("sh"), reason="needs a POSIX sh")def test_read_command_holds_back_a_split_utf8_sequence(self, tmp_path):@@ -1055,20 +1016,6 @@ class TestEnvPollerIncrementalRead:complete = full[:n].decode("utf-8", "ignore").encode() == full[:n]assert (n - size) == 0 if complete else 0 < (n - size) <= 3- def test_first_poll_reads_from_the_start(self, registry):- session = _make_session(sid="proc_delta")- session.exited = False- commands = self._run_poller(- registry,- session,- [- {"output": "11 0\nfirst chunk"},- {"output": "1\n"},- {"output": "0\n"},- ],- )- assert "O=0" in commands[0]- assert session.output_buffer == "first chunk"def test_delta_is_appended_not_replaced(self, registry):session = _make_session(sid="proc_append", output="already here ")@@ -1238,30 +1185,6 @@ class TestSpawnRewriteCompoundBackground:# The command passed to Popen should be the REWRITTEN versionassert "&& { node server.js &>/tmp/srv.log & }" in shell_cmd[2]- def test_simple_background_preserved(self, registry):- """Simple cmd & (no &&) must NOT be rewritten — no subshell bug."""- captured_cmd = []-- def fake_popen(args, **kwargs):- captured_cmd.append(args)- proc = MagicMock()- proc.pid = 2222- proc.stdout = MagicMock()- return proc-- fake_thread = MagicMock()- fake_thread.daemon = False-- with patch("tools.process_registry._find_shell", return_value="/bin/bash"), \- patch("subprocess.Popen", side_effect=fake_popen), \- patch("threading.Thread", return_value=fake_thread), \- patch.object(registry, "_write_checkpoint"):- registry.spawn_local("sleep 5 &", cwd="/tmp")-- assert len(captured_cmd) == 1- shell_cmd = captured_cmd[0][2]- # Simple background must remain as-is- assert "sleep 5 &" in shell_cmddef test_pty_path_uses_rewritten_command(self, registry):"""PTY spawn path must also use the rewritten command (issue #68915)."""@@ -2264,9 +2187,6 @@ class TestSystemdCgroupIsolation:assert argv[0] == "/usr/bin/systemd-run", argvassert "--user" in argvassert "--scope" in argv- assert "--quiet" in argv, (- "systemd-run argv must include --quiet (#70716 gap #3)"- )assert "--unit" in argvunit_idx = argv.index("--unit")assert argv[unit_idx + 1].startswith("hermes-worker-"), argv@@ -2614,13 +2534,11 @@ class TestSystemdCgroupIsolation:monkeypatch.setenv("TERMINAL_LOCAL_MEMORY_MAX_MB", "123")monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/systemd-run")- with patch("tools.process_registry.logger.warning") as warning:- argv = pr._build_systemd_scope_argv(- ["/bin/bash", "-lc", "true"],- unit_suffix="test",- )+ argv = pr._build_systemd_scope_argv(+ ["/bin/bash", "-lc", "true"],+ unit_suffix="test",+ )- warning.assert_not_called()assert f"MemoryMax={123 * 1024 * 1024}" in argvdef test_worker_memory_limit_caps_oversized_local_guard_override(@@ -2703,11 +2621,11 @@ class TestSystemdCgroupIsolation:value.startswith("OOMPolicy=") for value in probe_argv if isinstance(value, str)), probe_argv+ @pytest.mark.linux_onlydef test_successful_systemd_probe_revalidates_after_cache_ttl(self, monkeypatch):"""A vanished user bus invalidates a formerly successful scope verdict."""import tools.process_registry as pr- monkeypatch.setattr(pr, "_IS_LINUX", True)monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_AVAILABLE", None)monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_PROBED_AT", 0.0)clock = [100.0]@@ -2931,76 +2849,7 @@ class TestSystemdCgroupIsolation:assert pr._stop_systemd_unit("hermes-worker-gone.scope") is True- def test_darwin_never_takes_scope_path_even_with_systemd_run_on_path(- self, registry, monkeypatch, _gateway_identity- ):- """macOS no-op guarantee (#70716 cross-platform audit).- With ``_IS_LINUX = False`` (darwin), the spawn path must be- byte-identical to the legacy path even when a ``systemd-run``- binary is somehow on PATH and the gateway identity checks pass:- no probe, no wrapping, no unit recorded.- """- import tools.process_registry as pr-- fake_popen, captured = self._fake_popen_capture()-- monkeypatch.setattr(pr, "_IS_LINUX", False)- monkeypatch.setattr(pr, "_IS_WINDOWS", False)- monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_AVAILABLE", None)- monkeypatch.setattr("tools.process_registry._find_shell", lambda: "/bin/bash")- monkeypatch.setattr(- "gateway.restart.is_gateway_supervisor_process", lambda environ=None: True- )- # If any branch consults the probe or builds a scope argv on darwin,- # fail loudly.- monkeypatch.setattr("shutil.which", lambda name: "/usr/local/bin/systemd-run")- scope_builds = []- real_build = pr._build_systemd_scope_argv- monkeypatch.setattr(- pr,- "_build_systemd_scope_argv",- lambda *a, **k: scope_builds.append(a) or real_build(*a, **k),- )- probe_runs = []-- def fake_probe_run(argv, **kwargs):- probe_runs.append(argv)- return subprocess.CompletedProcess(args=argv, returncode=0)-- monkeypatch.setattr("subprocess.run", fake_probe_run)-- with (- patch("subprocess.Popen", side_effect=fake_popen),- patch("threading.Thread", return_value=MagicMock()),- patch.object(registry, "_write_checkpoint"),- ):- session = registry.spawn_local("echo hello", cwd="/tmp")-- argv = captured["argv"]- assert argv == ["/bin/bash", "-lic", "set +m; echo hello"], argv- assert captured["start_new_session"] is True- assert session.systemd_unit == ""- assert scope_builds == [], "darwin must never build a systemd scope argv"- assert probe_runs == [], "darwin must never run the systemd-run probe"-- def test_probe_returns_false_off_linux(self, monkeypatch):- """``_systemd_run_user_scope_available`` is False on non-Linux even- when a ``systemd-run`` binary exists on PATH."""- import tools.process_registry as pr-- monkeypatch.setattr(pr, "_IS_LINUX", False)- monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_AVAILABLE", None)- monkeypatch.setattr("shutil.which", lambda name: "/usr/local/bin/systemd-run")- probe_runs = []- monkeypatch.setattr(- "subprocess.run",- lambda argv, **kwargs: probe_runs.append(argv)- or subprocess.CompletedProcess(args=argv, returncode=0),- )-- assert pr._systemd_run_user_scope_available() is False- assert probe_runs == [], "non-Linux must not exec the probe"class TestNotificationRedaction:@@ -3075,10 +2924,6 @@ class TestNotificationRedaction:class TestGetByPrefix:"""ProcessRegistry.get() resolves unique ID prefixes like git short hashes."""- def test_full_id_still_exact(self, registry):- s = _make_session(sid="proc_4dae56ca81f6")- registry._running[s.id] = s- assert registry.get("proc_4dae56ca81f6") is sdef test_unique_prefix_resolves(self, registry):s = _make_session(sid="proc_4dae56ca81f6")@@ -3163,7 +3008,6 @@ def _patch_delegation_config(def _format_async(evt) -> str:- from tools.process_registry_notifications import format_process_notificationtext = format_process_notification(evt)assert text is not None, "format_process_notification returned None"diff --git a/tests/tools/test_process_schema_diet.py b/tests/tools/test_process_schema_diet.pyindex 0086d87c2fe..4aeb76f771f 100644--- a/tests/tools/test_process_schema_diet.py+++ b/tests/tools/test_process_schema_diet.py@@ -14,18 +14,7 @@ from tools.process_registry import PROCESS_SCHEMAclass TestProcessSchemaDiet(unittest.TestCase):- def test_write_vs_submit_trap_survives(self):- desc = PROCESS_SCHEMA["description"]- self.assertIn("submit appends Enter", desc)- self.assertIn("answer prompts", desc)- self.assertIn("no newline", desc)-- def test_nonobvious_semantics_survive(self):- desc = PROCESS_SCHEMA["description"]- self.assertIn("partial output on timeout", desc)- props = PROCESS_SCHEMA["parameters"]["properties"]- self.assertIn("unique prefix", props["session_id"]["description"])- self.assertIn("last 200", props["offset"]["description"])+def test_enum_is_the_verb_source(self):from tools.process_registry import _SESSION_ACTIONS@@ -33,8 +22,6 @@ class TestProcessSchemaDiet(unittest.TestCase):# The enum is the single list of verbs: every session-scoped handler is offered, plus the two# non-session verbs dispatched by name in _handle_process.self.assertEqual(set(props["action"]["enum"]), set(_SESSION_ACTIONS) | {"list", "handoff"})- # No redundant description on the enum param.- self.assertNotIn("description", props["action"])if __name__ == "__main__":diff --git a/tests/tools/test_process_wait_clarity.py b/tests/tools/test_process_wait_clarity.pyindex fd3dd0646b1..cff1fa0d8df 100644--- a/tests/tools/test_process_wait_clarity.py+++ b/tests/tools/test_process_wait_clarity.py@@ -24,26 +24,10 @@ class TestWaitTimeoutClarity:r = registry.wait(sid, timeout=1)assert r["status"] == "timeout"assert r["process_running"] is True- assert "not an error" in r["timeout_note"]- assert "Uptime" in r["timeout_note"]finally:registry.kill_process(sid)- def test_wait_timeout_suggests_notify_when_unset(self, registry):- sid = _spawn_sleeper(registry, notify=False)- try:- r = registry.wait(sid, timeout=1)- assert "notify_on_complete=true" in r["timeout_note"]- finally:- registry.kill_process(sid)- def test_wait_timeout_defers_to_notify_when_set(self, registry):- sid = _spawn_sleeper(registry, notify=True)- try:- r = registry.wait(sid, timeout=1)- assert "you will be notified on exit" in r["timeout_note"]- finally:- registry.kill_process(sid)def test_clamped_wait_keeps_clamp_note_and_running_semantics(self, registry, monkeypatch):monkeypatch.setenv("TERMINAL_TIMEOUT", "1")@@ -51,8 +35,6 @@ class TestWaitTimeoutClarity:try:r = registry.wait(sid, timeout=600)assert r["status"] == "timeout"- assert "clamped" in r["timeout_note"]- assert "not an error" in r["timeout_note"]assert r["process_running"] is Truefinally:registry.kill_process(sid)@@ -90,7 +72,6 @@ class TestWaitYieldRelease:r = result["r"]assert r["status"] == "interrupted"assert r["process_running"] is True- assert "still running" in r["note"]# The process was not killed and the yield bit was consumed.assert registry.poll(sid)["status"] == "running"from tools.interrupt import is_thread_yield_requested@@ -98,10 +79,3 @@ class TestWaitYieldRelease:finally:registry.kill_process(sid)- def test_wait_without_yield_still_times_out(self, registry):- sid = _spawn_sleeper(registry)- try:- r = registry.wait(sid, timeout=1)- assert r["status"] == "timeout"- finally:- registry.kill_process(sid)diff --git a/tests/tools/test_read_binary_type_disclosure.py b/tests/tools/test_read_binary_type_disclosure.pyindex 6499dad5f05..a39a6b79b0b 100644--- a/tests/tools/test_read_binary_type_disclosure.py+++ b/tests/tools/test_read_binary_type_disclosure.py@@ -82,9 +82,3 @@ class TestReadFileBinaryDisclosure:result = json.loads(read_file_tool(str(p)))assert "unknown binary" in result.get("error", "")- def test_text_file_unaffected(self, tmp_path, monkeypatch):- monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))- p = tmp_path / "ok.txt"- p.write_text("hello world\n")- result = json.loads(read_file_tool(str(p)))- assert "hello world" in result.get("content", "")diff --git a/tests/tools/test_read_extract.py b/tests/tools/test_read_extract.pyindex 38384c184c0..1907f171139 100644--- a/tests/tools/test_read_extract.py+++ b/tests/tools/test_read_extract.py@@ -221,10 +221,6 @@ class TestAnydocAbsent(unittest.TestCase):with self.assertRaises(ExtractionError):_extract_anydoc("/tmp/whatever.pdf")- def test_stdlib_formats_unaffected(self):- self.assertTrue(is_extractable_document("a.ipynb"))- self.assertTrue(is_extractable_document("a.docx"))- self.assertTrue(is_extractable_document("a.xlsx"))class TestAnydocInitLifecycle(unittest.TestCase):@@ -249,18 +245,6 @@ class TestAnydocInitLifecycle(unittest.TestCase):self.rex._anydoc_failed_at = self._saved_failed_atself.rex.ANYDOC_RETRY_SECONDS = self._saved_retry- def test_successful_load_is_cached(self):- fake = object()- calls = []-- def fake_import(name):- calls.append(name)- return fake-- with mock.patch("importlib.import_module", side_effect=fake_import):- self.assertIs(self.rex._anydoc(), fake)- self.assertIs(self.rex._anydoc(), fake)- self.assertEqual(calls, ["anydoc"])def test_failed_reconciliation_does_not_import_unverified_binding(self):with mock.patch(@@ -742,9 +726,6 @@ class TestPdfCoverageNote(unittest.TestCase):self.assertIn("6 of 9 pages", note)self.assertIn("pages 4-9", note) # contiguous empty gapself.assertIn("(6 pages)", note) # gap size stated- self.assertIn("vision_analyze", note) # recovery path is named- self.assertIn("ocr-and-documents", note)- self.assertIn("do NOT OCR or render everything", note)def test_gap_labels_carry_preceding_section_text(self):"""Each gap is labeled with the last text page before it (usuallydiff --git a/tests/tools/test_read_file_schema_gating.py b/tests/tools/test_read_file_schema_gating.pyindex de05bdb82fa..4a304669d12 100644--- a/tests/tools/test_read_file_schema_gating.py+++ b/tests/tools/test_read_file_schema_gating.py@@ -24,33 +24,7 @@ class TestReadFileSchemaStatic(unittest.TestCase):converter is a broken install handled by read_extract's teachingerror, not a schema variant."""- def test_formats_stated_unconditionally(self):- from tools.file_tools import READ_FILE_SCHEMA-- desc = READ_FILE_SCHEMA["description"]- for token in (".ipynb", ".docx", ".pptx", ".doc/.ppt/.xls",- "PDF (text layer)", "OpenDocument", "RTF", "EPUB"):- self.assertIn(token, desc, token)- # No availability hedging, no install mechanics, no gate.- self.assertNotIn("when the optional", desc)- self.assertNotIn("auto-installed", desc)- self.assertNotIn("anydoc", desc)-- def test_pdf_wording_upgrades_with_hosted_ocr_route(self):- """The ONE dynamic word: text-layer → scanned-or-text, keyed on- hosted_ocr_available(). Nous gateway deliberately does not- upgrade (Parse proxy live-probed broken 2026-08-28)."""- import tools.file_tools as ft-- with patch("tools.read_extract.hosted_ocr_available",- return_value=True):- d = ft._read_file_schema_overrides()["description"]- self.assertIn("PDF (scanned or text)", d)- self.assertNotIn("PDF (text layer)", d)- with patch("tools.read_extract.hosted_ocr_available",- return_value=False):- o = ft._read_file_schema_overrides()- self.assertEqual(o, {}) # base wording stands+def test_hosted_ocr_available_gate_states(self):"""Maintainer decision: ONLY a direct FIRECRAWL_API_KEY unlocks —@@ -100,34 +74,8 @@ class TestReadFileSchemaStatic(unittest.TestCase):self.assertIsNone(key)self.assertIsNone(url)- def test_coverage_warning_teaching_left_to_the_warning(self):- """The response-time warning owns the recovery curriculum."""- from tools.file_tools import READ_FILE_SCHEMA-- desc = READ_FILE_SCHEMA["description"]- self.assertNotIn("EXTRACTION COVERAGE WARNING", desc)- self.assertNotIn("NEEDS OCR", desc)- self.assertNotIn("pdftoppm", desc)- import inspect- from tools import read_extract-- src = inspect.getsource(read_extract)- self.assertIn("NEEDS OCR", src)- self.assertIn("pdftoppm", src)- self.assertIn("vision_analyze", src)- def test_binary_note_stays_last(self):- from tools.file_tools import READ_FILE_SCHEMA- desc = READ_FILE_SCHEMA["description"]- self.assertLess(desc.find("EPUB"), desc.find("Cannot read images/binary"))-- def test_missing_anydoc_error_teaches_install(self):- from tools.read_extract import _anydoc_missing_error-- err = _anydoc_missing_error("x.epub")- self.assertIn("firecrawl-anydoc", err)- self.assertNotEqual(err, "Unsupported document type: 'x.epub'")class TestNeedsOcrPath(unittest.TestCase):@@ -179,14 +127,6 @@ class TestNeedsOcrPath(unittest.TestCase):out = rx._extract_anydoc("scan.pdf")self.assertIn("[NEEDS OCR", out)self.assertIn("pages 2, 3", out)- self.assertIn("attempted and failed", out)- # Maintainer-directed: HINT at checking for an OCR skill; never- # name one (none is guaranteed to exist), never sell config knobs.- self.assertIn("check whether an OCR skill is available", out)- self.assertIn("skills_list", out)- self.assertNotIn("ocr-and-documents", out)- self.assertNotIn("marker-pdf", out)- self.assertNotIn("hosted_ocr", out)def test_disabled_warns_without_attempt(self):from tools import read_extract as rx@@ -197,23 +137,18 @@ class TestNeedsOcrPath(unittest.TestCase):out = rx._extract_anydoc("scan.pdf")self.assertIn("[NEEDS OCR", out)self.assertEqual(len(calls), 1) # no hosted attempt- # Same shape when disabled: skill hint, no knob advertising.- self.assertIn("check whether an OCR skill is available", out)- self.assertNotIn("hosted_ocr", out)- self.assertNotIn("ocr-and-documents", out)def test_pin_lockstep(self):"""pyproject core pin and lazy_deps self-heal pin must match."""import refrom pathlib import Path- py = Path("pyproject.toml").read_text(encoding="utf-8")- lz = Path("tools/lazy_deps.py").read_text(encoding="utf-8")- m1 = re.search(r'"firecrawl-anydoc==([\d.]+)"', py)- m2 = re.search(r'"firecrawl-anydoc==([\d.]+)"', lz)+ from tools.lazy_deps import LAZY_DEPS++ py = Path(__file__).resolve().parents[2].joinpath("pyproject.toml").read_text(encoding="utf-8")+ m1 = re.search(r'"(firecrawl-anydoc==[\d.]+)"', py)self.assertIsNotNone(m1)- self.assertIsNotNone(m2)- self.assertEqual(m1.group(1), m2.group(1))+ self.assertEqual(LAZY_DEPS["tool.doc_extract"], (m1.group(1),))if __name__ == "__main__":diff --git a/tests/tools/test_read_loop_detection.py b/tests/tools/test_read_loop_detection.pyindex 3e0451c937f..cbba3a4f4c5 100644--- a/tests/tools/test_read_loop_detection.py+++ b/tests/tools/test_read_loop_detection.py@@ -63,11 +63,6 @@ class TestReadLoopDetection(unittest.TestCase):def tearDown(self):_read_tracker.clear()- @patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())- def test_first_read_has_no_warning(self, _mock_ops):- result = json.loads(read_file_tool("/tmp/test.py", task_id="t1"))- self.assertNotIn("_warning", result)- self.assertIn("content", result)@patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())def test_second_consecutive_read_no_warning(self, _mock_ops):@@ -88,17 +83,8 @@ class TestReadLoopDetection(unittest.TestCase):result = json.loads(read_file_tool("/tmp/test.py", task_id="t1"))self.assertIn("error", result)self.assertIn("BLOCKED", result["error"])- self.assertIn("4 times", result["error"])self.assertNotIn("content", result)- @patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())- def test_fifth_consecutive_read_still_blocked(self, _mock_ops):- """Subsequent reads remain blocked with incrementing count."""- for _ in range(4):- read_file_tool("/tmp/test.py", task_id="t1")- result = json.loads(read_file_tool("/tmp/test.py", task_id="t1"))- self.assertIn("BLOCKED", result["error"])- self.assertIn("5 times", result["error"])@patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())@@ -145,10 +131,6 @@ class TestNotifyOtherToolCall(unittest.TestCase):self.assertNotIn("error", result)self.assertIn("content", result)- @patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())- def test_notify_on_unknown_task_is_safe(self, _mock_ops):- """notify_other_tool_call on a task that hasn't read anything is a no-op."""- notify_other_tool_call("nonexistent_task") # Should not raiseclass TestSearchLoopDetection(unittest.TestCase):@@ -160,11 +142,6 @@ class TestSearchLoopDetection(unittest.TestCase):def tearDown(self):_read_tracker.clear()- @patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())- def test_first_search_no_warning(self, _mock_ops):- result = json.loads(search_tool("def main", task_id="t1"))- self.assertNotIn("_warning", result)- self.assertNotIn("error", result)@patch("tools.file_tools._get_file_ops", return_value=_make_fake_file_ops())def test_second_consecutive_search_no_warning(self, _mock_ops):@@ -225,16 +202,6 @@ class TestTodoInjectionFiltering(unittest.TestCase):self.assertIn("Run tests", injection)- def test_all_active_included(self):- from tools.todo_tool import TodoStore- store = TodoStore()- store.write([- {"id": "1", "content": "Task A", "status": "pending"},- {"id": "2", "content": "Task B", "status": "in_progress"},- ])- injection = store.format_for_injection()- self.assertIn("Task A", injection)- self.assertIn("Task B", injection)if __name__ == "__main__":diff --git a/tests/tools/test_read_past_eof_note.py b/tests/tools/test_read_past_eof_note.pyindex a2c27380d17..1d7ce216e23 100644--- a/tests/tools/test_read_past_eof_note.py+++ b/tests/tools/test_read_past_eof_note.py@@ -16,7 +16,7 @@ class TestPastEofNote:p.write_text("\n".join(f"l{i}" for i in range(1, 51)) + "\n")result = json.loads(read_file_tool(str(p), offset=900, limit=50))hint = result.get("hint") or ""- assert "beyond the end" in hint+ assert hintassert "50" in hint # states actual line countassert not result.get("error"), "a fact about the file is not an error"diff --git a/tests/tools/test_read_preview_tool.py b/tests/tools/test_read_preview_tool.pyindex e57f508f076..705fe2bd268 100644--- a/tests/tools/test_read_preview_tool.py+++ b/tests/tools/test_read_preview_tool.py@@ -3,20 +3,8 @@import jsonfrom tools import read_preview_tool as rp-from tools.registry import registry---def test_lives_in_the_gui_surface_toolset(monkeypatch):- import tools.preview_tool # noqa: F401 — registers desktop_preview- """Consolidated (#95681): this module's tool became an action of the- single `desktop_preview` tool in desktop_ui; the old registration is gone and- `preview` reaches a desktop client on ANY backend (no env gate)."""- monkeypatch.delenv("HERMES_DESKTOP", raising=False)- assert registry.get_entry("read_preview") is None- entry = registry.get_entry("desktop_preview")- assert entry is not None- assert entry.toolset == "desktop_ui"- assert entry.check_fn is None++def test_requires_callback():diff --git a/tests/tools/test_read_special_file_guard.py b/tests/tools/test_read_special_file_guard.pyindex 330f42edd78..359ca9901e3 100644--- a/tests/tools/test_read_special_file_guard.py+++ b/tests/tools/test_read_special_file_guard.py@@ -65,7 +65,6 @@ class TestReadFileToolFifoGuard:assert time.monotonic() - t0 < 5, "guard must not block on the FIFO"assert result["success"] is Falseassert "FIFO" in result["note"]- assert "no read was attempted" in result["note"]def test_regular_file_unaffected(self, tmp_path, monkeypatch):monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))diff --git a/tests/tools/test_read_window_tool.py b/tests/tools/test_read_window_tool.pyindex e63c7c61e13..1bdec41a7e1 100644--- a/tests/tools/test_read_window_tool.py+++ b/tests/tools/test_read_window_tool.py@@ -3,17 +3,8 @@import jsonfrom tools import read_window_tool as rw-from tools.registry import registry-def test_lives_in_the_gui_surface_toolset(monkeypatch):- """Mirrors read_terminal: scoped by toolset, not by the backend's env."""- monkeypatch.delenv("HERMES_DESKTOP", raising=False)- entry = registry.get_entry("read_window_below")-- assert entry is not None- assert entry.toolset == "desktop_ui"- assert entry.check_fn is Nonedef test_requires_callback():diff --git a/tests/tools/test_reference_docs_registry_contract.py b/tests/tools/test_reference_docs_registry_contract.pydeleted file mode 100644index cd123994129..00000000000--- a/tests/tools/test_reference_docs_registry_contract.py+++ /dev/null@@ -1,107 +0,0 @@-"""Contract: the shipped tool reference docs name only tools the shipped code registers.--``website/docs/reference/tools-reference.md`` and ``toolsets-reference.md`` are the-authoritative built-in-tool surface published with the package. This pins them to the-live registry: every tool name the docs claim must (a) be a registered tool and (b)-resolve inside the toolset that claims it — the registry/queryable half of the-"documented surface == registered surface" contract. A rename in ``tools/`` or-``toolsets.py`` that skips these pages fails here instead of shipping stale tool-names to readers (they shipped stale once: the project/preview/tour/tip-consolidations left ``project_create``/``open_preview``/``tour``/``tip`` behind, and-the browser row still claimed the ``web_search`` membership #64503 removed).--Reads only the two shipped .md docs (data, like cli-config.yaml.example contracts)-and the live registry/toolset resolver — never source text.-"""--from __future__ import annotations--import re-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parents[2]-TOOLS_REF = REPO_ROOT / "website" / "docs" / "reference" / "tools-reference.md"-TOOLSETS_REF = REPO_ROOT / "website" / "docs" / "reference" / "toolsets-reference.md"--_SECTION_RE = re.compile(r"^## `([a-z0-9_-]+)` toolset", re.MULTILINE)-_ROW_RE = re.compile(r"^\| `([a-z0-9_]+)` \|", re.MULTILINE)--[email protected](scope="module")-def registered_names():- """Every tool name the shipped surface registers: built-ins plus bundled- backend plugins (the spotify plugin owns the doc's spotify rows). The same- discovery path production runs at startup."""- import model_tools # noqa: F401 — triggers built-in tool discovery- from hermes_cli.plugins import discover_plugins-- discover_plugins()- from tools.registry import registry-- return {entry.name for entry in registry.get_all_entries()}---def _tool_sections(path) -> list[tuple[str, list[str]]]:- """(toolset, claimed tool names) per ``## ``toolset`` toolset`` section."""- text = path.read_text(encoding="utf-8")- headers = [(m.start(), m.group(1)) for m in _SECTION_RE.finditer(text)]- return [- (toolset, _ROW_RE.findall(text[start:next_start]))- for (start, toolset), (next_start, _) in zip(headers, [*headers[1:], (len(text), None)])- ]---def _core_toolset_rows(path) -> list[tuple[str, str]]:- """(toolset, Tools cell) rows of the Core Toolsets table."""- text = path.read_text(encoding="utf-8")- match = re.search(r"^## Core Toolsets$.*?^(?=\| `)", text, re.MULTILINE | re.DOTALL)- assert match, "Core Toolsets table vanished from toolsets-reference.md"- section = text[match.start() : text.index("## Platform Toolsets", match.start())]- return [- (cells[0].strip("` "), cells[1])- for line in section.splitlines()- if line.startswith("| `") and len(cells := [c.strip() for c in line.strip().strip("|").split("|")]) > 1- ]---def test_tools_reference_rows_resolve_in_their_toolset(registered_names):- from toolsets import resolve_toolset-- stale = [- (toolset, name)- for toolset, rows in _tool_sections(TOOLS_REF)- for name in rows- if name not in registered_names or name not in set(resolve_toolset(toolset))- ]- assert not stale, (- "tools-reference.md documents tool names the registry does not register "- "(or that the claimed toolset does not resolve): "- + ", ".join(f"{ts}:{n}" for ts, n in stale)- )---def test_toolsets_reference_core_table_resolves(registered_names):- """Core Toolsets table: every claimed member resolves within that toolset;- composite rows name real toolsets."""- from toolsets import TOOLSETS, resolve_toolset, validate_toolset-- stale, unknown = [], []- for toolset, tools_cell in _core_toolset_rows(TOOLSETS_REF):- if "composite" in tools_cell:- unknown += [(toolset, n) for n in re.findall(r"`([a-z0-9_]+)`", tools_cell) if not validate_toolset(n)]- continue- cell = re.sub(r"\([^)]*\)", " ", tools_cell) # drop "(via `includes`)"- resolved = set(resolve_toolset(toolset))- for name in re.findall(r"`([a-z0-9_]+)`", cell):- if name not in registered_names or name not in resolved:- stale.append((toolset, name))- assert not stale, (- "toolsets-reference.md claims tool membership the toolsets.py/registry resolver "- "does not deliver: " + ", ".join(f"{ts}:{n}" for ts, n in stale)- )- assert not unknown, (- "toolsets-reference.md composite rows name unknown toolsets: "- + ", ".join(f"{ts}:{n}" for ts, n in unknown)- )diff --git a/tests/tools/test_refresh_agent_mcp_tools.py b/tests/tools/test_refresh_agent_mcp_tools.pyindex 37e64ef7103..a0e9befb717 100644--- a/tests/tools/test_refresh_agent_mcp_tools.py+++ b/tests/tools/test_refresh_agent_mcp_tools.py@@ -148,25 +148,6 @@ def test_refresh_respects_context_engine_toolset_gate(monkeypatch):assert "lcm_grep" not in agent.valid_tool_names # gated out (#5544)-def test_refreshed_tool_is_callable_through_valid_tool_names_guard(monkeypatch):- """The whole point: a late tool, once refreshed, passes the name guard the- run loop uses to accept/reject tool calls (agent.valid_tool_names)."""- agent = _agent(["read_file"])-- import model_tools- monkeypatch.setattr(- model_tools, "get_tool_definitions",- lambda **kw: [_tool("read_file"), _tool("mcp_granola_list_meetings")],- )-- # Before refresh the run loop would reject the call ("Tool does not exist").- assert "mcp_granola_list_meetings" not in agent.valid_tool_names-- _mcp_agent.refresh_agent_mcp_tools(agent)-- # After refresh the same guard accepts it AND it's in the tools= payload.- assert "mcp_granola_list_meetings" in agent.valid_tool_names- assert any(t["function"]["name"] == "mcp_granola_list_meetings" for t in agent.tools)def test_refresh_is_thread_safe_under_concurrent_calls(monkeypatch):@@ -220,10 +201,6 @@ def test_refresh_is_thread_safe_under_concurrent_calls(monkeypatch):# ── discovery-wait bound (mcp_discovery_timeout config) ──────────────────────-def test_resolve_discovery_timeout_explicit_wins(monkeypatch):- from hermes_cli import mcp_startup-- assert mcp_startup._resolve_discovery_timeout(2.5) == 2.5def test_wait_returns_instantly_when_no_discovery_thread(monkeypatch):diff --git a/tests/tools/test_registry.py b/tests/tools/test_registry.pyindex d36e4918199..f6274687988 100644--- a/tests/tools/test_registry.py+++ b/tests/tools/test_registry.py@@ -3,7 +3,6 @@import jsonimport loggingimport threading-from pathlib import Pathfrom unittest.mock import patchimport pytest@@ -12,8 +11,6 @@ from tools.registry import (ToolRegistry,_MAX_LOGGED_ERROR_CHARS,_MAX_TOOL_ERROR_CHARS,- _module_registers_tools,- _tool_module_candidates,discover_builtin_tools,tool_error,)@@ -119,7 +116,6 @@ class TestRegisterAndDispatch:assert all(not thread.is_alive() for thread in threads)assert errors == []- assert reg._generation == 1entry = reg.get_entry("mcp__foo_bar__search")assert entry is not None@@ -128,11 +124,6 @@ class TestRegisterAndDispatch:"dash","underscore",}- assert any(- "REJECTED" in record.message- and "mcp__foo_bar__search" in record.message- for record in caplog.records- )class TestGetDefinitions:def test_returns_openai_format(self):@@ -151,32 +142,6 @@ class TestGetDefinitions:assert names == {"t1", "t2"}- def test_reuses_shared_check_fn_once_per_call(self):- reg = ToolRegistry()- calls = {"count": 0}-- def shared_check():- calls["count"] += 1- return True-- reg.register(- name="first",- toolset="shared",- schema=_make_schema("first"),- handler=_dummy_handler,- check_fn=shared_check,- )- reg.register(- name="second",- toolset="shared",- schema=_make_schema("second"),- handler=_dummy_handler,- check_fn=shared_check,- )-- defs = reg.get_definitions({"first", "second"})- assert len(defs) == 2- assert calls["count"] == 1class TestUnknownToolDispatch:@@ -184,7 +149,6 @@ class TestUnknownToolDispatch:reg = ToolRegistry()result = json.loads(reg.dispatch("nonexistent", {}))assert "error" in result- assert "Unknown tool" in result["error"]class TestToolErrorBounding:@@ -373,19 +337,6 @@ class TestCheckFnExceptionHandling:class TestBuiltinDiscovery:- def test_discovers_all_real_self_registering_builtin_tool_modules(self):- tools_dir = Path(__file__).resolve().parents[2] / "tools"- expected = [- ".".join(("tools", *path.relative_to(tools_dir).with_suffix("").parts))- for path in _tool_module_candidates(tools_dir)- if path.name not in {"__init__.py", "registry.py", "mcp_tool.py"}- and _module_registers_tools(path)- ]-- with patch("tools.registry.importlib.import_module"):- imported = discover_builtin_tools(tools_dir)-- assert imported == expecteddef test_skips_mcp_tool_even_if_it_registers(self, tmp_path):@@ -466,51 +417,10 @@ class TestPackageToolDiscovery:assert imported == ["tools.connectors.tool"]-class TestEmojiMetadata:- """Verify per-tool emoji registration and lookup."""-- def test_emoji_stored_on_entry(self):- reg = ToolRegistry()- reg.register(- name="t", toolset="s", schema=_make_schema(),- handler=_dummy_handler, emoji="🔥",- )- assert reg._tools["t"].emoji == "🔥"- def test_emoji_empty_string_treated_as_unset(self):- reg = ToolRegistry()- reg.register(- name="t", toolset="s", schema=_make_schema(),- handler=_dummy_handler, emoji="",- )- assert reg.get_emoji("t") == "⚡"-class TestEntryLookup:- def test_get_entry_returns_registered_entry(self):- reg = ToolRegistry()- reg.register(- name="alpha", toolset="core", schema=_make_schema("alpha"), handler=_dummy_handler- )- entry = reg.get_entry("alpha")- assert entry is not None- assert entry.name == "alpha"- assert entry.toolset == "core"-- def test_get_entry_returns_none_for_unknown_tool(self):- reg = ToolRegistry()- assert reg.get_entry("missing") is None---class TestSecretCaptureResultContract:- def test_secret_request_result_does_not_include_secret_value(self):- result = {- "success": True,- "stored_as": "TENOR_API_KEY",- "validated": False,- }- assert "secret" not in json.dumps(result).lower()class TestThreadSafety:@@ -726,14 +636,6 @@ class TestDeregisterAuthorization:)return reg- def test_plugin_cannot_deregister_unowned_tool_without_opt_in(self):- reg = self._reg()- reg.register_plugin_override_policy("hermes_plugins.evil", False)- with patch.object(ToolRegistry, "_caller_module", return_value="hermes_plugins.evil"):- import pytest- with pytest.raises(PermissionError, match="allow_tool_override"):- reg.deregister("protected")- assert reg._tools.get("protected") is not None, "tool must survive the rejected deregister"def test_plugin_root_module_can_deregister_submodule_handler(self):diff --git a/tests/tools/test_removed_backend_migration.py b/tests/tools/test_removed_backend_migration.pyindex d6f5f70b74d..6d10a7f583d 100644--- a/tests/tools/test_removed_backend_migration.py+++ b/tests/tools/test_removed_backend_migration.py@@ -59,8 +59,6 @@ class TestSelectionErrorRemovedBackend:assert _NOTE in msg# generic failure text replaced, not appendedassert "no registered web search provider" not in msg- # still ends with the uniform remediation contract- assert "Run 'hermes tools' to change it." in msgdef test_live_backend_keeps_caller_failure_text(self, legacy_removed):msg = selection_error("web", "'exa'", "no registered web search provider has that name")@@ -80,7 +78,6 @@ class TestStartupWarningForRemovedWebBackend:issues = self._removed_issues({"web": {"backend": "legacysearch"}})assert len(issues) == 1assert issues[0].severity == "warning"- assert "hermes tools" in issues[0].hintdef test_per_capability_keys_are_checked(self, legacy_removed):assert len(self._removed_issues({"web": {"search_backend": "legacysearch"}})) == 1diff --git a/tests/tools/test_sandbox_failure_hints.py b/tests/tools/test_sandbox_failure_hints.pyindex 53c8a49486f..6fb71728b4e 100644--- a/tests/tools/test_sandbox_failure_hints.py+++ b/tests/tools/test_sandbox_failure_hints.py@@ -2,7 +2,6 @@import json-import pytestfrom tools.code_execution_tool import _sandbox_failure_hint, execute_code@@ -14,24 +13,9 @@ class TestSandboxFailureHint:h = _sandbox_failure_hint(err, enabled_tools={"terminal", "read_file"})assert "browser_navigate" in hassert "read_file" in h and "terminal" in h- assert "normal tool call" in h- def test_helper_import_failure_reports_module_skew(self):- err = "ImportError: cannot import name 'json_parse' from 'hermes_tools'"- h = _sandbox_failure_hint(err)- assert "from hermes_tools import json_parse" in h- assert "sys.path" in h- def test_missing_third_party_module(self):- err = "ModuleNotFoundError: No module named 'matplotlib'"- h = _sandbox_failure_hint(err)- assert "matplotlib" in h- assert "stdlib" in h- def test_dict_vs_string_confusion(self):- err = "TypeError: string indices must be integers"- h = _sandbox_failure_hint(err)- assert "DICTS" in hdef test_unknown_failure_no_hint(self):assert _sandbox_failure_hint("ZeroDivisionError: division by zero") is None@@ -51,13 +35,6 @@ class TestLiveSandboxHint:assert "hint" in rassert "totally_fake_tool" in r["hint"]- def test_missing_module_produces_hint(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- r = json.loads(execute_code(- "import nonexistent_pkg_zzz\n", task_id="t-sbhint",- ))- assert r["status"] == "error"- assert "not installed in the sandbox" in r.get("hint", "")def test_successful_script_has_no_hint(self, tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))diff --git a/tests/tools/test_schema_sanitizer.py b/tests/tools/test_schema_sanitizer.pyindex 656fb973196..8c8df995b89 100644--- a/tests/tools/test_schema_sanitizer.py+++ b/tests/tools/test_schema_sanitizer.py@@ -12,7 +12,6 @@ import copyfrom tools.schema_sanitizer import (sanitize_tool_schemas,strip_pattern_and_format,- strip_slash_enum,)@@ -223,7 +222,6 @@ def test_items_sanitized_in_array_schema():def test_strip_responses_mixed_formats():"""Mixed list of OpenAI-format and Responses-format tools should both be sanitized."""- from tools.schema_sanitizer import strip_pattern_and_formattools = [# OpenAI-format: {"function": {"parameters": {...}}}@@ -284,7 +282,7 @@ def test_strip_responses_mixed_formats():# in the tools array 400s the whole request on Anthropic/Bedrock/Vertex/Azure.# ----------------------------------------------------------------------------from tools.schema_sanitizer import sanitize_property_key, unrename_tool_args+from tools.schema_sanitizer import sanitize_property_keydef test_sanitize_property_key_empty_falls_back():@@ -578,11 +576,6 @@ def test_normalize_mcp_input_schema_still_repairs_declared_objects():assert bare["properties"] == {} and bare["required"] == []-def test_collapse_is_deterministic():- schema = {"anyOf": [{"const": "b"}, {"const": "a"}]}- first = collapse_const_unions(copy.deepcopy(schema))- second = collapse_const_unions(copy.deepcopy(schema))- assert first == second == {"type": "string", "enum": ["b", "a"]}def test_builtin_tool_without_required_gets_empty_required_list():diff --git a/tests/tools/test_search_files_engine_selection.py b/tests/tools/test_search_files_engine_selection.pyindex 7bda6892b60..8b02c311698 100644--- a/tests/tools/test_search_files_engine_selection.py+++ b/tests/tools/test_search_files_engine_selection.py@@ -7,7 +7,7 @@ import pytestfrom tools.environments.local import LocalEnvironmentfrom tools.file_operations import SearchResult, ShellFileOperations-from tools.file_tools import SEARCH_FILES_SCHEMA, _handle_search_files, search_tool+from tools.file_tools import search_toolfrom tools.registry import registry@@ -37,14 +37,6 @@ class RecordingEnvironment:return [command for command in self.commands if "--files" in command]-def test_schema_exposes_fast_discovery_default_and_exact_modified_opt_in():- order = SEARCH_FILES_SCHEMA["parameters"]["properties"]["order"]-- assert order["enum"] == ["discovery", "modified"]- assert order["default"] == "discovery"- assert "fast bounded traversal order" in order["description"]- assert "exact global newest-first" in order["description"]- assert "ignored for content" in order["description"]def test_default_file_search_runs_one_bounded_unsorted_rg_command():@@ -121,17 +113,8 @@ def test_modified_zero_match_exit_one_is_valid_without_capability_error():["ripgrep 13.0.0\n","ripgrep unknown\n",- "ripgrep 14 garbage\n",- "ripgrep 14\n","ripgrep 14.1\n",- "ripgrep 14.1.1-\n",- "ripgrep 14.1.1+\n","ripgrep 14.1.1-alpha..1\n",- "ripgrep 14.1.1+build..2\n",- "ripgrep 14.1.1-01\n",- "ripgrep 014.1.1\n",- "ripgrep 14.01.1\n",- "ripgrep 14.1.01\n",],)def test_modified_requires_parseable_ripgrep_14_before_search(version):@@ -269,27 +252,14 @@ def test_invalid_direct_file_order_returns_structured_error():result = ops.search("*.py", path="/repo", target="files", order="random")assert isinstance(result, SearchResult)- assert result.error == "Invalid file search order 'random'; expected 'discovery' or 'modified'."+ assert result.error and "random" in result.errorassert env.rg_commands == []-def test_handler_forwards_modified_order(monkeypatch):- captured = {}- def fake_search_tool(**kwargs):- captured.update(kwargs)- return "{}"- monkeypatch.setattr("tools.file_tools.search_tool", fake_search_tool)-- _handle_search_files({"pattern": "*.py", "target": "files", "order": "modified"})-- assert captured["order"] == "modified"--[email protected]("target", ["content", "files"])@pytest.mark.parametrize("blank_path", ["", " \t ", None])-def test_handler_normalizes_blank_path_to_current_directory(monkeypatch, target, blank_path):+def test_handler_normalizes_blank_path_to_current_directory(monkeypatch, blank_path):"""#112424: a present-but-blank (or null) path must fall back to the documented '.' default."""captured = {}@@ -299,26 +269,11 @@ def test_handler_normalizes_blank_path_to_current_directory(monkeypatch, target,monkeypatch.setattr("tools.file_tools.search_tool", fake_search_tool)- registry.dispatch("search_files", {"pattern": "needle", "target": target, "path": blank_path})+ registry.dispatch("search_files", {"pattern": "needle", "target": "files", "path": blank_path})- assert captured["target"] == targetassert captured["path"] == "."[email protected]("raw_path", ["src", 5, ["src"]])-def test_handler_preserves_nonblank_path(monkeypatch, raw_path):- """Only None/blank normalise to '.'; a wrong-typed path reaches search_tool's own error path."""- captured = {}-- def fake_search_tool(**kwargs):- captured.update(kwargs)- return "{}"-- monkeypatch.setattr("tools.file_tools.search_tool", fake_search_tool)-- registry.dispatch("search_files", {"pattern": "needle", "path": raw_path})-- assert captured["path"] == raw_pathdef test_repeated_search_key_distinguishes_order(monkeypatch):@@ -376,13 +331,6 @@ def test_resolved_executable_with_spaces_is_used_by_every_rg_invocation():assert len([c for c in env.commands if c.startswith("command -v rg")]) == 1-def test_non_rg_command_cache_keeps_cached_misses_and_bool_values():- env = RecordingEnvironment()- ops = ShellFileOperations(env)- assert ops._has_command("find") is False- assert ops._has_command("find") is False- assert ops._command_cache == {"find": False}- assert len([c for c in env.commands if c.startswith("command -v find")]) == 1@pytest.mark.windows_only@@ -523,7 +471,6 @@ def test_comma_delimited_file_roots_preserve_internal_spaces_in_one_search():assert result.files == ["C:/root one/a.py", "C:/root two/b.py"]assert len(env.rg_commands) == 1assert "'C:/root one' 'C:/root two'" in env.rg_commands[0]- assert "path contained 2 entries" in (result.warning or "")def test_multi_path_modified_capability_error_propagates():diff --git a/tests/tools/test_search_hidden_dirs.py b/tests/tools/test_search_hidden_dirs.pyindex 9a45a1ddb5e..9867ceec934 100644--- a/tests/tools/test_search_hidden_dirs.py+++ b/tests/tools/test_search_hidden_dirs.py@@ -13,7 +13,6 @@ Fix: _search_files (find) and _search_with_grep both now exclude hiddendirectories, matching ripgrep's default behavior."""-import subprocessimport pytest@@ -50,26 +49,6 @@ def searchable_tree(tmp_path):return tmp_path / "skills"-class TestFindExcludesHiddenDirs:- """_search_files uses find, which should exclude hidden directories."""-- def test_find_skips_hub_cache_files(self, searchable_tree):- """find should not return files from .hub/ directory."""- cmd = (- f"find {searchable_tree} -not -path '*/.*' -type f -name '*.json'"- )- result = subprocess.run(cmd, shell=True, capture_output=True, text=True)- assert "catalog.json" not in result.stdout- assert ".hub" not in result.stdout--- def test_find_still_returns_visible_files(self, searchable_tree):- """find should still return files from visible directories."""- cmd = (- f"find {searchable_tree} -not -path '*/.*' -type f -name '*.md'"- )- result = subprocess.run(cmd, shell=True, capture_output=True, text=True)- assert "SKILL.md" in result.stdoutclass TestGrepExcludesHiddenDirs:@@ -185,33 +164,6 @@ class TestGrepSearchesRootsUnderHiddenDirs:assert result.total_count == 1-class TestRipgrepAlreadyExcludesHidden:- """Verify ripgrep's default behavior is to skip hidden directories."""-- @pytest.mark.skipif(- subprocess.run(["which", "rg"], capture_output=True).returncode != 0,- reason="ripgrep not installed",- )- def test_rg_skips_hub_by_default(self, searchable_tree):- """rg should skip .hub/ by default (no --hidden flag)."""- result = subprocess.run(- ["rg", "--no-heading", "ignore", str(searchable_tree)],- capture_output=True, text=True,- )- assert ".hub" not in result.stdout- assert "catalog.json" not in result.stdout-- @pytest.mark.skipif(- subprocess.run(["which", "rg"], capture_output=True).returncode != 0,- reason="ripgrep not installed",- )- def test_rg_finds_visible_content(self, searchable_tree):- """rg should find content in visible directories."""- result = subprocess.run(- ["rg", "--no-heading", "visible document", str(searchable_tree)],- capture_output=True, text=True,- )- assert "SKILL.md" in result.stdoutclass TestIgnoreFileWritten:diff --git a/tests/tools/test_search_zero_match_and_multipath.py b/tests/tools/test_search_zero_match_and_multipath.pyindex d21df4fa34e..5675401b3e5 100644--- a/tests/tools/test_search_zero_match_and_multipath.py+++ b/tests/tools/test_search_zero_match_and_multipath.py@@ -1,7 +1,6 @@"""Tests for search_files zero-match probes and multi-path recovery."""import json-import osimport pytest@@ -22,10 +21,6 @@ def proj(tmp_path, monkeypatch):class TestZeroMatchProbe:- def test_case_mismatch_gets_hint(self, proj):- r = json.loads(search_tool("token_alpha", path=str(proj / "proj"), task_id="t-zm"))- assert r["total_count"] == 0- assert "case-insensitive" in r.get("warning", "")def test_case_mismatch_hint_names_the_files(self, proj):# The probe already ran the -i search; it must hand over the paths,@@ -58,7 +53,7 @@ class TestZeroMatchProbe:# Same class as the casing probe: the path must be in the hint.assert "conf.cfg" in r.get("warning", "")- def test_hidden_probe_prunes_dependency_trees_and_keeps_local_ignored(self, proj, monkeypatch):+ def test_hidden_probe_prunes_dependency_trees_and_keeps_local_ignored(self, proj):d = proj / "proj"dependency = d / "node_modules" / "package" / ".hidden"dependency.mkdir(parents=True)@@ -70,24 +65,7 @@ class TestZeroMatchProbe:local_file.write_text("BOUNDED_HIDDEN_TOKEN = true\n")(d / ".gitignore").write_text("node_modules/\n.project-local/\n")- # Drive the public search seam while recording the commands that the- # zero-match probe actually executes. The real rg calls still run. This- # observes shell command text, so pin the shell lane (native rg runs- # argv directly and never passes through ``_exec``).- monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")- from tools.file_tools import _get_file_ops-- task_id = "t-zm-pruned-hidden"- ops = _get_file_ops(task_id=task_id)- commands = []- real_exec = ops._exec-- def recording_exec(command, *args, **kwargs):- commands.append(command)- return real_exec(command, *args, **kwargs)-- monkeypatch.setattr(ops, "_exec", recording_exec)- r = json.loads(search_tool("BOUNDED_HIDDEN_TOKEN", path=str(d), task_id=task_id))+ r = json.loads(search_tool("BOUNDED_HIDDEN_TOKEN", path=str(d), task_id="t-zm-pruned-hidden"))warning = r.get("warning", "")assert r["total_count"] == 0@@ -95,61 +73,22 @@ class TestZeroMatchProbe:assert local_file.name in warningassert dependency_file.name not in warning- hidden_probe_commands = [- command for command in commands- if "--hidden" in command and "--no-ignore" in command- ]- assert len(hidden_probe_commands) == 1- hidden_probe = hidden_probe_commands[0]- assert "--glob" in hidden_probe- assert "'!node_modules/**'" in hidden_probe- assert "'!**/node_modules/**'" in hidden_probe-- def test_hidden_probe_prunes_explicit_dependency_root(self, proj, monkeypatch):+ def test_hidden_probe_prunes_explicit_dependency_root(self, proj):d = proj / "proj"dependency = d / "node_modules" / "package" / ".hidden"dependency.mkdir(parents=True)(dependency / "dependency.js").write_text("EXPLICIT_ROOT_TOKEN = true\n")(d / ".gitignore").write_text("node_modules/\n")- monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0") # shell-observer test- from tools.file_tools import _get_file_ops-- task_id = "t-zm-explicit-pruned-root"- ops = _get_file_ops(task_id=task_id)- commands = []- real_exec = ops._exec-- def recording_exec(command, *args, **kwargs):- commands.append(command)- return real_exec(command, *args, **kwargs)-- monkeypatch.setattr(ops, "_exec", recording_exec)r = json.loads(search_tool("EXPLICIT_ROOT_TOKEN",path=str(d / "node_modules"),- task_id=task_id,+ task_id="t-zm-explicit-pruned-root",))assert r["total_count"] == 0assert "warning" not in r- hidden_probe_commands = [- command for command in commands- if "--hidden" in command and "--no-ignore" in command- ]- assert len(hidden_probe_commands) == 1- hidden_probe = hidden_probe_commands[0]- assert "'!node_modules/**'" in hidden_probe- assert "'!**/node_modules/**'" in hidden_probe-- def test_probe_path_list_is_capped(self, proj):- d = proj / "proj"- for i in range(8):- (d / f"cap{i}.txt").write_text("capped_case_token = 1\n")- r = json.loads(search_tool("CAPPED_CASE_TOKEN", path=str(d), task_id="t-zm"))- w = r.get("warning", "")- assert "case-insensitive" in w- assert "+3 more" in w # 8 files, 5 shown+def test_matching_search_unaffected(self, proj):r = json.loads(search_tool("TOKEN_ALPHA", path=str(proj / "proj"), task_id="t-zm"))@@ -189,7 +128,6 @@ class TestMultiPathRecovery:# single-path miss must keep the existing "Similar paths" behaviorr = json.loads(search_tool("TOKEN_ALPHA", path=str(proj / "pro"), task_id="t-mp"))assert "error" in r- assert "Path not found" in r["error"]def test_files_target_multi_path(self, proj):p = f"{proj / 'proj'} {proj / 'extra'}"diff --git a/tests/tools/test_self_repo_guard.py b/tests/tools/test_self_repo_guard.pyindex d49ffd84a24..993d80d58b7 100644--- a/tests/tools/test_self_repo_guard.py+++ b/tests/tools/test_self_repo_guard.py@@ -1,13 +1,11 @@"""Tests for tools/self_repo_guard.py — the running-source-checkout git guard."""import subprocess-from pathlib import Pathimport pytestfrom tools.self_repo_guard import (detect_self_repo_git_mutation,- get_running_source_root,)@@ -378,10 +376,6 @@ class TestWorktreeTargetingSourceRoot:class TestSourceRootResolution:- def test_resolves_to_repo_when_git_dir_present(self):- root = get_running_source_root()- if root is not None:- assert (root / ".git").exists()def test_worktree_git_file_counts(self, tmp_path, monkeypatch):import tools.self_repo_guard as mod@@ -412,17 +406,7 @@ class TestBlockMessageGuidance:on most distros — parallel salvage clones running npm ci filled a 32GBtmpfs to 97% in one campaign)."""- def test_message_recommends_shared_clone_on_disk(self, repo):- hit, msg = _detect("git rebase origin/main", repo, repo)- assert hit is True- assert "git clone --shared" in msg- assert "scratch" in msg- def test_message_warns_against_tmp_for_dep_installs(self, repo):- hit, msg = _detect("git rebase origin/main", repo, repo)- assert hit is True- assert "tmpfs" in msg- assert "Delete the clone" in msgdef test_scratch_hint_honors_hermes_home(self, repo, monkeypatch):monkeypatch.setenv("HERMES_HOME", "/custom/hermes-home")diff --git a/tests/tools/test_send_message_plugin_extensibility.py b/tests/tools/test_send_message_plugin_extensibility.pyindex 354146919b6..4ac4d7829ad 100644--- a/tests/tools/test_send_message_plugin_extensibility.py+++ b/tests/tools/test_send_message_plugin_extensibility.py@@ -2,13 +2,12 @@from __future__ import annotations-import asyncioimport jsonimport osimport subprocessimport sysfrom types import SimpleNamespace-from unittest.mock import AsyncMock, patch+from unittest.mock import patchimport pytest@@ -72,7 +71,7 @@ def test_platform_parser_normalizes_and_validator_rejects(plugin_platform):)assert chat_id is Noneassert thread_id is None- assert error == f"Invalid target '@[email protected]' on {name}"+ assert errordef test_registered_plugin_rejects_unrecognized_opaque_target(plugin_platform):@@ -188,10 +187,6 @@ def test_cli_and_cron_share_plugin_target_normalization(plugin_platform, monkeyp}-def test_send_message_remains_host_only(plugin_platform):- from tools.registry import registry-- assert registry.get_entry("send_message") is Nonedef test_force_reload_unregisters_profile_owned_platform(plugin_platform, monkeypatch):diff --git a/tests/tools/test_send_message_slack.py b/tests/tools/test_send_message_slack.pyindex e34b3200c0c..ba544e39e9c 100644--- a/tests/tools/test_send_message_slack.py+++ b/tests/tools/test_send_message_slack.py@@ -9,12 +9,10 @@ _standalone_send`` and text sends now route through ``_send_via_adapter``import asyncioimport sysfrom types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import MagicMockimport pytest-from gateway.config import Platform-from tools.send_message_tool import _send_to_platformdef _ensure_slack_mock(monkeypatch):@@ -42,29 +40,6 @@ def _ensure_slack_mock(monkeypatch):monkeypatch.setitem(sys.modules, name, mod)-def test_slack_send_to_platform_routes_through_send_via_adapter(monkeypatch):- """Slack text sends go through _send_via_adapter (live adapter first)."""- _ensure_slack_mock(monkeypatch)-- live_send = AsyncMock(return_value={"success": True, "message_id": "live-ts"})-- with patch("tools.send_message_tool._send_via_adapter", live_send):- result = asyncio.run(- _send_to_platform(- Platform.SLACK,- SimpleNamespace(enabled=True, token="bad-token,good-token", extra={}),- "C123",- "**hello** from Hermes",- thread_id="171.1",- )- )-- assert result == {"success": True, "message_id": "live-ts"}- live_send.assert_awaited_once()- call = live_send.await_args- assert call.args[0] == Platform.SLACK- assert call.args[2] == "C123"- assert call.kwargs["thread_id"] == "171.1"class _SlackResponse:diff --git a/tests/tools/test_send_message_target_parse.py b/tests/tools/test_send_message_target_parse.pyindex 8b92ce2bf0e..4f329263af0 100644--- a/tests/tools/test_send_message_target_parse.py+++ b/tests/tools/test_send_message_target_parse.py@@ -262,7 +262,6 @@ def test_live_buzz_adapter_exception_is_bounded() -> None:))- assert result["error"].startswith("Plugin platform send failed: ")assert len(result["error"]) <= 1024@@ -456,10 +455,7 @@ def test_unresolved_plugin_target_requires_explicit_parser() -> None:finally:platform_registry.unregister(platform_name)- assert result == {- "error": f"Could not resolve 'dm:panyaozhen' on {platform_name}. "- "The plugin parser did not recognize it and no channel-directory entry matched."- }+ assert set(result) == {"error"}discover_mock.assert_called_once_with()send_mock.assert_not_awaited()@@ -487,10 +483,8 @@ def test_unresolved_builtin_target_keeps_directory_error() -> None:))- assert result == {- "error": "Could not resolve 'missing-room' on telegram. "- "Use send_message(action='list') to see available targets."- }+ assert set(result) == {"error"}+ assert "missing-room" in result["error"]send_mock.assert_not_awaited()@@ -512,15 +506,6 @@ def test_unresolved_builtin_target_passes_through_when_requested() -> None:assert thread_id is None-def test_unresolved_builtin_target_still_errors_for_the_model_tool() -> None:- """The model-facing default stays strict: unresolved targets error with a hint."""- from tools.send_message_tool import resolve_send_target-- with patch("gateway.channel_directory.resolve_channel_name", return_value=None):- chat_id, _thread_id, error = resolve_send_target("telegram", "ops-room")-- assert chat_id is None- assert error is not Nonedef test_photon_group_guid_passes_through_when_requested() -> None:diff --git a/tests/tools/test_send_message_tool.py b/tests/tools/test_send_message_tool.pyindex 8a5af891613..9f21a969dc3 100644--- a/tests/tools/test_send_message_tool.py+++ b/tests/tools/test_send_message_tool.py@@ -41,7 +41,6 @@ from tools.send_message_targets import _parse_target_reffrom plugins.platforms.discord.adapter import (_DISCORD_STANDALONE_JSON_BODY_LIMIT_BYTES,_derive_forum_thread_name,- _probe_is_forum_cached,_standalone_send,)@@ -386,7 +385,7 @@ class TestSendMessageTool:assert result["success"] is Falseassert result["partial_success"] is Trueassert result["media_dropped"] == [{"path": str(missing), "reason": "not found on this host"}]- assert "Delivery incomplete" in result["error"]+ assert result["error"]send_mock.assert_awaited_once_with(Platform.TELEGRAM, telegram_cfg, "12345", "report", thread_id=None,media_files=[(str(report.resolve()), False)], force_document=False,@@ -500,7 +499,6 @@ class TestSendTelegramMediaDelivery:)assert "error" in result- assert "No deliverable text or media remained" in result["error"]bot.send_message.assert_not_awaited()@@ -626,31 +624,6 @@ class TestSendToPlatformChunking:assert max(send_lengths) <= 4096- def test_matrix_media_uses_native_adapter_helper(self, tmp_path):- doc_path = tmp_path / "test-send-message-matrix.pdf"- doc_path.write_bytes(b"%PDF-1.4 test")-- try:- helper = AsyncMock(return_value={"success": True, "platform": "matrix", "chat_id": "!room:example.com", "message_id": "$evt"})- with patch("tools.send_message_tool._send_matrix_via_adapter", helper):- result = asyncio.run(- _send_to_platform(- Platform.MATRIX,- SimpleNamespace(enabled=True, token="tok", extra={"homeserver": "https://matrix.example.com"}),- "!room:example.com",- "here you go",- media_files=[(str(doc_path), False)],- )- )-- assert result["success"] is True- helper.assert_awaited_once()- call = helper.await_args- assert call.args[1] == "!room:example.com"- assert call.args[2] == "here you go"- assert call.kwargs["media_files"] == [(str(doc_path), False)]- finally:- doc_path.unlink(missing_ok=True)class TestMatrixMediaLiveAdapterReuse:"""Verify _send_matrix_via_adapter reuses the live gateway adapter@@ -755,38 +728,6 @@ class TestMatrixMediaLiveAdapterReuse:# ----------------------------------------------------------------------------class TestSendToPlatformWhatsapp:- def test_whatsapp_routes_via_local_bridge_sender(self):- """WhatsApp delivery routes through the plugin's registry- standalone_sender_fn (was tools.send_message_tool._send_whatsapp- before the #41112 plugin migration)."""- from hermes_cli.plugins import discover_plugins- from gateway.platform_registry import platform_registry- discover_plugins()- chat_id = "test-user@lid"- async_mock = AsyncMock(return_value={"success": True, "platform": "whatsapp", "chat_id": chat_id, "message_id": "abc123"})-- wa_entry = platform_registry.get("whatsapp")- original_sender = wa_entry.standalone_sender_fn- wa_entry.standalone_sender_fn = async_mock- try:- result = asyncio.run(- _send_to_platform(- Platform.WHATSAPP,- SimpleNamespace(enabled=True, token=None, extra={"bridge_port": 3000}),- chat_id,- "hello from hermes",- )- )- finally:- wa_entry.standalone_sender_fn = original_sender-- assert result["success"] is True- # _registry_standalone_send passes (pconfig, chat_id, message, thread_id=None)- async_mock.assert_awaited_once()- _call = async_mock.await_args- assert _call.args[1] == chat_id- assert _call.args[2] == "hello from hermes"class TestSendTelegramHtmlDetection:@@ -1159,28 +1100,6 @@ class TestSendDiscordThreadId:response.json.assert_not_awaited()response.text.assert_not_awaited()-class TestSendToPlatformDiscordThread:- """_send_to_platform passes thread_id through to _send_discord."""-- def test_discord_thread_id_passed_to_send_discord(self):- """Discord platform with thread_id passes it to _send_discord."""- send_mock = AsyncMock(return_value={"success": True, "message_id": "1"})-- with _patch_discord_sender(send_mock):- result = asyncio.run(- _send_to_platform(- Platform.DISCORD,- SimpleNamespace(enabled=True, token="tok", extra={}),- "-1001234567890",- "hello thread",- thread_id="17585",- )- )-- assert result["success"] is True- send_mock.assert_awaited_once()- _, call_kwargs = send_mock.await_args- assert call_kwargs["thread_id"] == "17585"# ---------------------------------------------------------------------------# Discord media attachment support@@ -1224,17 +1143,6 @@ class TestSendDiscordMedia:assert mock_session.post.call_count == 2- def test_no_text_no_media_returns_error(self):- """Empty text with no media returns error dict."""- mock_session, _ = self._build_mock(200)- with patch("aiohttp.ClientSession", return_value=mock_session):- result = asyncio.run(- _send_discord("tok", "555", "", media_files=[])- )-- # Text is empty but media_files is empty, so text POST fires- # (the "skip text if media present" condition isn't met)- assert result["success"] is Trueclass TestSendToPlatformDiscordMedia:"""_send_to_platform routes Discord media correctly."""@@ -1266,39 +1174,6 @@ class TestSendToPlatformDiscordMedia:assert call_log[0]["media_files"] == [] # First chunk: no mediaassert call_log[1]["media_files"] == [("/fake/img.png", False)] # Last chunk: media attached-class TestSendMatrixUrlEncoding:- """The matrix plugin's _standalone_send URL-encodes Matrix room IDs in the- API path (was tools.send_message_tool._send_matrix before #41112)."""-- def test_room_id_is_percent_encoded_in_url(self):- """Matrix room IDs with ! and : are percent-encoded in the PUT URL."""-- mock_resp = MagicMock()- mock_resp.status = 200- mock_resp.json = AsyncMock(return_value={"event_id": "$evt123"})- mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)- mock_resp.__aexit__ = AsyncMock(return_value=None)-- mock_session = MagicMock()- mock_session.put = MagicMock(return_value=mock_resp)- mock_session.__aenter__ = AsyncMock(return_value=mock_session)- mock_session.__aexit__ = AsyncMock(return_value=None)-- with patch("aiohttp.ClientSession", return_value=mock_session):- from plugins.platforms.matrix.adapter import _standalone_send- result = asyncio.get_event_loop().run_until_complete(- _standalone_send(- SimpleNamespace(token="test_token", extra={"homeserver": "https://matrix.example.org"}),- "!HLOQwxYGgFPMPJUSNR:matrix.org",- "hello",- )- )-- assert result["success"] is True- # Verify the URL was called with percent-encoded room ID- put_url = mock_session.put.call_args[0][0]- assert "%21HLOQwxYGgFPMPJUSNR%3Amatrix.org" in put_url- assert "!HLOQwxYGgFPMPJUSNR:matrix.org" not in put_url# ---------------------------------------------------------------------------@@ -1387,27 +1262,6 @@ class TestSendDiscordForum:assert "403" in result["error"]-class TestSendToPlatformDiscordForum:- """_send_to_platform delegates forum detection to _send_discord."""-- def test_send_to_platform_discord_delegates_to_send_discord(self):- """Discord messages are routed through _send_discord, which handles forum detection."""- send_mock = AsyncMock(return_value={"success": True, "message_id": "1"})-- with _patch_discord_sender(send_mock):- result = asyncio.run(- _send_to_platform(- Platform.DISCORD,- SimpleNamespace(enabled=True, token="tok", extra={}),- "forum_ch",- "Hello forum",- )- )-- assert result["success"] is True- send_mock.assert_awaited_once_with(- "tok", "forum_ch", "Hello forum", media_files=[], thread_id=None,- )# ---------------------------------------------------------------------------# Tests for _send_discord forum + media multipart upload@@ -1499,69 +1353,6 @@ class TestSendDiscordForumMedia:# ----------------------------------------------------------------------------class TestForumProbeCache:- """_DISCORD_CHANNEL_TYPE_PROBE_CACHE memoizes forum detection results."""-- def setup_method(self):- from plugins.platforms.discord import adapter as discord_adapter- discord_adapter._DISCORD_CHANNEL_TYPE_PROBE_CACHE.clear()-- def test_probe_result_is_memoized(self, monkeypatch):- """An API-probed channel type is cached so subsequent sends skip the probe."""- monkeypatch.setattr(- "gateway.channel_directory.lookup_channel_type", lambda p, cid: None- )-- # First probe response: type=15 (forum)- probe_resp = MagicMock()- probe_resp.status = 200- probe_resp.json = AsyncMock(return_value={"type": 15})- probe_resp.__aenter__ = AsyncMock(return_value=probe_resp)- probe_resp.__aexit__ = AsyncMock(return_value=None)-- thread_resp = MagicMock()- thread_resp.status = 201- thread_resp.json = AsyncMock(return_value={"id": "t1", "message": {"id": "m1"}})- thread_resp.__aenter__ = AsyncMock(return_value=thread_resp)- thread_resp.__aexit__ = AsyncMock(return_value=None)-- probe_session = MagicMock()- probe_session.__aenter__ = AsyncMock(return_value=probe_session)- probe_session.__aexit__ = AsyncMock(return_value=None)- probe_session.get = MagicMock(return_value=probe_resp)-- thread_session = MagicMock()- thread_session.__aenter__ = AsyncMock(return_value=thread_session)- thread_session.__aexit__ = AsyncMock(return_value=None)- thread_session.post = MagicMock(return_value=thread_resp)-- # Two _send_discord calls: first does probe + thread-create; second should skip probe- from plugins.platforms.discord import adapter as discord_adapter-- sessions_created = []-- def session_factory(**kwargs):- # Alternate: each new ClientSession() call returns a probe_session, thread_session pair- idx = len(sessions_created)- sessions_created.append(idx)- # Returns the same mocks; the real code opens a probe session then a thread session.- # Hand out probe_session if this is the first time called within _send_discord,- # otherwise thread_session.- if idx % 2 == 0:- return probe_session- return thread_session-- with patch("aiohttp.ClientSession", side_effect=session_factory):- result1 = asyncio.run(_send_discord("tok", "ch1", "first"))- assert result1["success"] is True- assert discord_adapter._probe_is_forum_cached("ch1") is True-- # Second call: cache hits, no new probe session needed. We need to only- # return thread_session now since probe is skipped.- sessions_created.clear()- with patch("aiohttp.ClientSession", return_value=thread_session):- result2 = asyncio.run(_send_discord("tok", "ch1", "second"))- assert result2["success"] is True# Only one session opened (thread creation) — no probe session this time# (verified by not raising from our side_effect exhaustion)@@ -1776,44 +1567,12 @@ class TestSendViaAdapterStandaloneFallback:finally:platform_registry.unregister("fakeplatform")- assert result == {"error": "Plugin standalone send failed: boom!"}+ assert set(result) == {"error"}+ assert "boom!" in result["error"]class TestSendTelegramThreadNotFoundRetry:"""Tests for thread-not-found retry behaviour in _send_telegram (#27012)."""- def test_text_send_retries_without_thread_id_on_thread_not_found(self):- """When thread is not found, the text send should retry without- message_thread_id."""- call_args = []-- async def fake_retry(bot, *, chat_id, text, parse_mode, **kwargs):- call_args.append(dict(kwargs, chat_id=chat_id, text=text))- if len(call_args) == 1:- raise Exception("Bad Request: message thread not found")- return SimpleNamespace(message_id=42)-- async def run_test():- with patch(- "tools.send_message_senders._send_telegram_message_with_retry",- fake_retry,- ):- # _send_telegram imports Bot locally; we only need to mock- # the send path, not Bot itself (Bot import falls through- # normally since python-telegram-bot is installed).- return await _send_telegram(- "fake-token", "-100123", "hello from topic 17585",- thread_id="17585",- )-- result = asyncio.run(run_test())- assert result["success"] is True- assert result["message_id"] == "42"- assert len(call_args) == 2, f"expected 2 calls, got {len(call_args)}"- # First call should have message_thread_id- assert call_args[0].get("message_thread_id") is not None- # Second call (retry) should NOT have message_thread_id- assert "message_thread_id" not in call_args[1], \- "retry should drop message_thread_id after thread-not-found"def test_disable_web_page_preview_not_leaked_to_media_sends(self):"""disable_web_page_preview must never leak into a media send.@@ -1876,9 +1635,8 @@ def test_not_configured_error_names_resolved_home_and_consulted_sources(tmp_path_, _, _, err = _resolve_platform_config("discord", GatewayConfig())assert "~/.hermes" not in err- assert f"{home / '.env'} (no DISCORD_BOT_TOKEN)" in err- assert f"{home / 'config.yaml'} (platforms.discord.enabled: false)" in err- assert "environment (DISCORD_BOT_TOKEN unset)" in err+ assert str(home / ".env") in err+ assert str(home / "config.yaml") in errdef test_not_configured_error_names_default_root_gateway_and_secret_sources(tmp_path, monkeypatch):@@ -1904,7 +1662,6 @@ def test_not_configured_error_names_default_root_gateway_and_secret_sources(tmp__, _, _, err = _resolve_platform_config("discord", GatewayConfig())- assert (f"A gateway (pid {os.getpid()}) running from {root} has discord connected; "- f"this shell is scoped to profile home {profile} whose .env has no DISCORD_BOT_TOKEN.") in err- assert "external secret sources (bitwarden: disabled)" in err+ assert str(os.getpid()) in err and str(profile) in err+ assert "bitwarden" in errassert "SECRET-VALUE" not in errdiff --git a/tests/tools/test_session_cwd_store.py b/tests/tools/test_session_cwd_store.pyindex e30abfa954d..f32c937b0e1 100644--- a/tests/tools/test_session_cwd_store.py+++ b/tests/tools/test_session_cwd_store.py@@ -144,19 +144,6 @@ class TestFileToolsReadTheRecord:assert not str(resolved).startswith(str(wt_b))-class TestDelegateSeedsChildRecord:- def test_child_record_seeded_from_parent_then_isolated(self):- tt.record_session_cwd("parent-task", "/parent/worktree")- # what delegate_tool does at spawn:- tt.record_session_cwd("child-1", tt.get_session_cwd("parent-task"))-- assert tt.get_session_cwd("child-1") == "/parent/worktree"- # child cds somewhere; parent record must be untouched.- tt.record_session_cwd("child-1", "/child/scratch")- assert tt.get_session_cwd("parent-task") == "/parent/worktree"- assert tt.get_session_cwd("child-1") == "/child/scratch"--class TestReapedEnvFallbackIsFillOnly:"""file_tools' reaped-env rescue (#26211) must not overwrite the record.@@ -168,7 +155,6 @@ class TestReapedEnvFallbackIsFillOnly:def _reap(self, monkeypatch, tmp_path, task_id, stale_cwd):import tools.file_tools as ft- import tools.file_tools_paths as ftpclass _StaleFileOps:cwd = stale_cwddiff --git a/tests/tools/test_session_search.py b/tests/tools/test_session_search.pyindex c1ceec9f234..033e727e3ef 100644--- a/tests/tools/test_session_search.py+++ b/tests/tools/test_session_search.py@@ -8,7 +8,6 @@ Four calling shapes:All run zero LLM calls."""-import inspectimport jsonimport timefrom datetime import datetime, timezone@@ -17,7 +16,6 @@ import pytestfrom hermes_state import SessionDBfrom tools.session_search_tool import (- SESSION_SEARCH_SCHEMA,_format_timestamp,_is_compacted_message,_resolve_to_parent,@@ -67,46 +65,6 @@ def _seed_modpack_sessions(db):# Schema invariants# =========================================================================-class TestSchema:- def test_schema_params_cover_every_shape(self):- params = SESSION_SEARCH_SCHEMA["parameters"]["properties"]- # Discovery shape- assert "query" in params- assert "limit" in params- assert params["sort"]["enum"] == ["newest", "oldest"]- assert params["detail"]["enum"] == ["adaptive", "full"]- assert params["detail"]["default"] == "adaptive"- # Scroll shape- assert "session_id" in params- assert "around_message_id" in params- assert "window" in params- # Shared- assert "role_filter" in params- # Mode is inferred from which args are set — no explicit mode param- assert "mode" not in params-- def test_detail_parameter_is_appended_for_positional_compatibility(self):- parameters = list(inspect.signature(session_search).parameters)- historical_prefix = [- "query",- "role_filter",- "limit",- "db",- "current_session_id",- "session_id",- "around_message_id",- "window",- "sort",- "profile",- ]- assert parameters == [- *historical_prefix,- "detail",- "after",- "before",- "exclude_session_ids",- ]-class TestFormatTimestamp:def test_formats_unix_and_passes_through_the_rest(self):@@ -138,7 +96,7 @@ class TestBrowseShape:assert result["success"] is Trueassert db.rich_called is False- assert db.bounded_kwargs["timeout_seconds"] == 3.0+ assert db.bounded_kwargs is not Nonedef test_browse_fails_closed_without_bounded_database_capability(self):class _LegacyDB:@@ -148,7 +106,6 @@ class TestBrowseShape:result = json.loads(session_search(db=_LegacyDB()))assert result["success"] is False- assert "does not support bounded recent-session browse" in result["error"]def test_lazy_database_is_released_after_search(self, monkeypatch):class _DB:@@ -214,29 +171,6 @@ class TestBrowseShape:# =========================================================================class TestDiscoveryShape:- def test_discovery_field_plan_preserves_full_default_result(self, db, monkeypatch):- _seed_modpack_sessions(db)- original = db.search_messages- requested_fields = None-- def search_spy(*args, **kwargs):- nonlocal requested_fields- requested_fields = kwargs.get("fields")- return original(*args, **kwargs)-- monkeypatch.setattr(db, "search_messages", search_spy)-- result = json.loads(session_search(query="modpack", limit=1, db=db))-- assert result["success"] is True- assert requested_fields is not None- assert "context" not in requested_fields- assert len(result["results"]) == 1- hit = result["results"][0]- assert hit["detail"] == "full"- assert "bookend_start" in hit- assert hit["messages"]- assert "bookend_end" in hitdef test_full_detail_returns_bookends_and_window_for_every_hit(self, db):_seed_modpack_sessions(db)@@ -489,7 +423,7 @@ class TestReadShape:assert result["mode"] == "read"assert result["message_count"] == 50assert result["truncated"] is True- assert len(result["messages"]) == 30 # head 20 + tail 10+ assert len(result["messages"]) < 50def test_read_caps_oversized_message_content(self, db):# #114344: a huge archived tool result stored as a message must not come@@ -578,7 +512,6 @@ class TestCrossProfileRead:result = json.loads(session_search(session_id="s_far", db=db))assert result["success"] is Falseassert "messages" not in result and "secret" not in json.dumps(result)- assert "profile=" in result["error"]# Naming the owning profile is still the sanctioned cross-profile read.self._patch_profiles(monkeypatch, other_home)@@ -1091,20 +1024,6 @@ class TestNewResetLineageDiscovery:assert result["count"] >= 1assert "s_cli_old" in [r["session_id"] for r in result["results"]]- def test_live_delegation_child_still_excluded(self, db):- """Unended parent+child (delegate_task) must stay hidden."""- db.create_session("s_parent", source="cli")- db.append_message(- "s_parent", role="user",- content="nebula deployment infrastructure setup",- )- db.create_session(- "s_child", source="cli", parent_session_id="s_parent",- )- result = json.loads(session_search(- query="nebula deployment", db=db, current_session_id="s_child",- ))- assert result["count"] == 0def test_branched_parent_still_excluded(self, db):"""/branch verbatim-copies the transcript into the child, so thediff --git a/tests/tools/test_shared_container_task_id.py b/tests/tools/test_shared_container_task_id.pyindex 7e5c8da2245..98c5c59a0e3 100644--- a/tests/tools/test_shared_container_task_id.py+++ b/tests/tools/test_shared_container_task_id.py@@ -34,10 +34,6 @@ def test_none_task_id_maps_to_default():assert terminal_tool._resolve_container_task_id(None) == "default"-def test_empty_task_id_maps_to_default():- assert terminal_tool._resolve_container_task_id("") == "default"--def test_cwd_only_override_collapses_to_default():"""CWD-only overrides (ACP adapter workspace tracking) must NOT triggercontainer isolation — they should collapse to the shared 'default'@@ -77,11 +73,6 @@ def test_env_type_override_keeps_own_id():# the shared "default" slot silently runs commands on the wrong remote host.-def test_session_key_scopes_to_its_own_slot(monkeypatch):- monkeypatch.setenv("HERMES_SESSION_KEY", "sess-A")- assert terminal_tool._resolve_container_task_id(None) == "session:sess-A"--def test_distinct_session_keys_get_distinct_slots(monkeypatch):monkeypatch.setenv("HERMES_SESSION_KEY", "sess-A")a = terminal_tool._resolve_container_task_id(None)diff --git a/tests/tools/test_signal_media.py b/tests/tools/test_signal_media.pyindex e6e4d9c38dc..6136db726aa 100644--- a/tests/tools/test_signal_media.py+++ b/tests/tools/test_signal_media.py@@ -3,12 +3,9 @@import asyncioimport sysfrom types import ModuleType-from unittest.mock import MagicMock, AsyncMock, patchimport pytest-from gateway.config import Platform-def _make_httpx_mock():"""Create a mock httpx module with proper sync json()."""@@ -50,18 +47,6 @@ def inject_httpx(monkeypatch):class TestSendSignalMediaFiles:"""Test that _send_signal correctly handles media_files parameter."""- def test_send_signal_basic_text_without_media(self):- """Backward compatibility: text-only signal messages work."""- from tools.send_message_tool import _send_signal-- extra = {"http_url": "http://localhost:8080", "account": "+155****4567"}-- result = asyncio.run(_send_signal(extra, "+155****9999", "Hello world"))-- assert result["success"] is True- assert result["platform"] == "signal"- assert result["chat_id"] == "+155****9999"-def test_send_signal_with_missing_media_file(self):"""Missing media files should generate warnings but not fail."""@@ -74,131 +59,4 @@ class TestSendSignalMediaFiles:)assert result["success"] is True # Should succeed despite missing file- assert "warnings" in result- assert "Some media files were skipped" in str(result["warnings"])---class TestSendSignalMediaRestrictions:- """Test that the restriction block handles Signal media correctly."""-- def test_signal_allows_text_only_media_via_send_to_platform(self):- """Signal should accept text-only media files (no message) via _send_to_platform."""- import httpx- if not hasattr(httpx, 'Proxy') or not hasattr(httpx, 'URL'):- pytest.skip("httpx type annotations incompatible with telegram library")- from tools.send_message_tool import _send_to_platform-- mock_result = {"success": True, "platform": "signal"}- with patch("tools.send_message_tool._send_signal", new=AsyncMock(return_value=mock_result)):- config = MagicMock()- config.platforms = {Platform.SIGNAL: MagicMock(enabled=True)}- config.get_home_channel.return_value = None-- result = asyncio.run(- _send_to_platform(- Platform.SIGNAL,- config,- "+155****9999",- "", # Empty message - media is the message- media_files=[("/tmp/test.png", False)]- )- )-- assert result["success"] is True-- def test_non_media_platforms_reject_text_only_media(self):- """Slack should reject text-only media (no MESSAGE content)."""- import httpx- if not hasattr(httpx, 'Proxy') or not hasattr(httpx, 'URL'):- pytest.skip("httpx type annotations incompatible with telegram library")- from tools.send_message_tool import _send_to_platform-- config = MagicMock()- config.platforms = {Platform.SLACK: MagicMock(enabled=True)}- config.get_home_channel.return_value = None-- # Empty message with media_files should trigger restriction block- result = asyncio.run(- _send_to_platform(- Platform.SLACK,- config,- "C012AB3CD",- "", # Empty message - media is the only content- media_files=[("/tmp/test.png", False)]- )- )-- assert "error" in result- assert "only supported for" in result["error"]---class TestSendSignalMediaWarningMessages:- """Test warning messages are updated to include signal."""-- def test_warning_includes_signal_when_media_omitted(self):- """Non-media platforms should show a warning mentioning signal in the supported list."""- import httpx- if not hasattr(httpx, 'Proxy') or not hasattr(httpx, 'URL'):- pytest.skip("httpx type annotations incompatible with telegram library")- from tools.send_message_tool import _send_to_platform- from hermes_cli.plugins import discover_plugins- from gateway.platform_registry import platform_registry-- config = MagicMock()- config.platforms = {Platform.SLACK: MagicMock(enabled=True)}- config.get_home_channel.return_value = None-- # Slack migrated to a bundled plugin (#41112) — delivery now flows- # through the registry's standalone_sender_fn instead of the old- # tools.send_message_tool._send_slack helper. Patch the registry entry's- # sender so the slack send succeeds and the media-omitted warning (which- # must mention signal) gets attached to the result.- discover_plugins()- slack_entry = platform_registry.get("slack")- original_sender = slack_entry.standalone_sender_fn- slack_entry.standalone_sender_fn = AsyncMock(return_value={"success": True})- try:- result = asyncio.run(- _send_to_platform(- Platform.SLACK,- config,- "C012AB3CD",- "Test message with media",- media_files=[("/tmp/test.png", False)]- )- )- finally:- slack_entry.standalone_sender_fn = original_sender-- assert result.get("warnings") is not None- # Check that the warning mentions signal as supported- found = any("signal" in w.lower() for w in result["warnings"])- assert found, f"Expected 'signal' in warnings but got: {result.get('warnings')}"---class TestSendSignalGroupChats:- """Test that _send_signal handles group chats correctly."""-- def test_send_signal_group_with_attachments(self, tmp_path):- """Group chat messages with attachments should use groupId parameter."""- from tools.send_message_tool import _send_signal-- img_path = tmp_path / "test_attachment.pdf"- img_path.write_bytes(b"%PDF-1.4")-- extra = {"http_url": "http://localhost:8080", "account": "+155****4567"}-- result = asyncio.run(- _send_signal(extra, "group:abc123==", "Group file", media_files=[(str(img_path), False)])- )-- assert result["success"] is True---class TestSendSignalConfigLoading:- """Verify Signal config loading works."""-- def test_signal_platform_exists(self):- """Platform.SIGNAL should be a valid platform."""- assert hasattr(Platform, "SIGNAL")- assert Platform.SIGNAL.value == "signal"+ assert result["warnings"]diff --git a/tests/tools/test_single_query_approval_mode.py b/tests/tools/test_single_query_approval_mode.pyindex 878a3637926..d5a003c636b 100644--- a/tests/tools/test_single_query_approval_mode.py+++ b/tests/tools/test_single_query_approval_mode.py@@ -17,7 +17,7 @@ import pytestimport tools.approval as approval_modulefrom tools import approval_contextfrom gateway.session_context import clear_session_vars, reset_session_vars, set_session_vars-from tools.approval import check_all_command_guards, check_dangerous_command, detect_dangerous_command+from tools.approval import check_all_command_guards, check_dangerous_commandfrom tools.approval_context import _get_single_query_approval_mode@@ -45,10 +45,6 @@ class TestSingleQueryApprovalModeParsing:with mock_patch("hermes_cli.config.load_config_readonly", return_value={"approvals": {}}):assert _get_single_query_approval_mode() == "deny"- def test_explicit_deny(self):- from unittest.mock import patch as mock_patch- with mock_patch("hermes_cli.config.load_config_readonly", return_value={"approvals": {"single_query_mode": "deny"}}):- assert _get_single_query_approval_mode() == "deny"def test_explicit_approve(self):from unittest.mock import patch as mock_patch@@ -61,15 +57,6 @@ class TestSingleQueryApprovalModeParsing:with mock_patch("hermes_cli.config.load_config_readonly", return_value={"approvals": {"single_query_mode": "off"}}):assert _get_single_query_approval_mode() == "approve"- def test_allow_maps_to_approve(self):- from unittest.mock import patch as mock_patch- with mock_patch("hermes_cli.config.load_config_readonly", return_value={"approvals": {"single_query_mode": "allow"}}):- assert _get_single_query_approval_mode() == "approve"-- def test_yes_maps_to_approve(self):- from unittest.mock import patch as mock_patch- with mock_patch("hermes_cli.config.load_config_readonly", return_value={"approvals": {"single_query_mode": "yes"}}):- assert _get_single_query_approval_mode() == "approve"def test_case_insensitive(self):from unittest.mock import patch as mock_patch@@ -158,19 +145,6 @@ class TestSingleQueryDenyMode:result = check_dangerous_command("ls -la", "local")assert result["approved"]- def test_block_message_includes_description(self, monkeypatch):- """The block message should mention what pattern was matched."""- monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")- monkeypatch.setenv("HERMES_INTERACTIVE", "1")- monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)- monkeypatch.delenv("HERMES_YOLO_MODE", raising=False)-- from unittest.mock import patch as mock_patch- with mock_patch("tools.approval_context._get_single_query_approval_mode", return_value="deny"):- result = check_dangerous_command("rm -rf /tmp/stuff", "local")- assert not result["approved"]- assert "dangerous" in result["message"].lower() or "delete" in result["message"].lower()-class TestSingleQueryApproveMode:"""When HERMES_SINGLE_QUERY_SESSION is set and single_query_mode=approve,@@ -358,4 +332,4 @@ class TestSingleQueryModeInteractions:from unittest.mock import patch as mock_patchwith mock_patch("tools.approval_context._get_single_query_approval_mode", return_value="approve"):result = check_all_command_guards("rm -rf /", "local")- assert not result["approved"]\ No newline at end of file+ assert not result["approved"]diff --git a/tests/tools/test_singularity_preflight.py b/tests/tools/test_singularity_preflight.pyindex 00a7367334d..a90398e6526 100644--- a/tests/tools/test_singularity_preflight.py+++ b/tests/tools/test_singularity_preflight.py@@ -6,7 +6,6 @@ singularity is installed, instead of a cryptic FileNotFoundError.See: https://github.com/NousResearch/hermes-agent/issues/1511"""-import subprocessfrom unittest.mock import patch, MagicMockimport pytest@@ -46,10 +45,3 @@ class TestEnsureSingularityAvailable:with patch("shutil.which", side_effect=lambda n: "/usr/bin/apptainer" if n == "apptainer" else None), \patch("subprocess.run", return_value=fake_result):assert _ensure_singularity_available() == "apptainer"--- def test_raises_when_not_installed(self):- """Raises RuntimeError when neither executable exists."""- with patch("shutil.which", return_value=None):- with pytest.raises(RuntimeError, match="Neither.*apptainer.*nor.*singularity"):- _ensure_singularity_available()diff --git a/tests/tools/test_skill_bundle_provenance.py b/tests/tools/test_skill_bundle_provenance.pyindex 96e7a9b9cc5..ddc65efaf1c 100644--- a/tests/tools/test_skill_bundle_provenance.py+++ b/tests/tools/test_skill_bundle_provenance.py@@ -12,8 +12,6 @@ from pathlib import Pathimport pytestfrom rich.console import Console-from tools.skills_guard import SCANNER_VERSION, scan_skill_cached-from tools.skills_hub import HubLockFilefrom tools.skills_hub_github import GitHubAuth, GitHubSourcefrom tools.skills_hub_models import SkillBundlefrom tools.skills_hub_sources import UrlSource@@ -318,26 +316,6 @@ def test_github_source_fetch_dangling_linked_reference_warns_not_aborts(monkeypaassert source.fetch("owner/repo/skill") is None-def test_lock_file_persists_scan_provenance(tmp_path):- lock = HubLockFile(tmp_path / "lock.json")- provenance = {- "source_url": "https://example.com/SKILL.md",- "bundle_hash": "sha256:" + "a" * 64,- "scanner_version": SCANNER_VERSION,- "findings": [],- "rules": [],- "scanned_at": "2026-07-09T00:00:00+00:00",- "fresh": True,- }- lock.record_install(- name="demo", source="url", identifier="https://example.com/SKILL.md",- trust_level="community", scan_verdict="safe", skill_hash="sha256:legacy",- install_path="demo", files=["SKILL.md"], scan_provenance=provenance,- )-- assert lock.get_installed("demo")["scan_provenance"] == provenance--def test_real_temp_repo_and_home_install_e2e(served_repo, monkeypatch, tmp_path):from hermes_cli.skills_hub import do_install@@ -363,7 +341,6 @@ def test_real_temp_repo_and_home_install_e2e(served_repo, monkeypatch, tmp_path)entry = json.loads((home / "skills" / ".hub" / "lock.json").read_text())["installed"]["demo-bundle"]assert entry["scan_provenance"]["source_url"] == urlassert entry["scan_provenance"]["fresh"] is True- assert "Scan provenance: fresh" in sink.getvalue()def _make_skills_redirect(link: Path, target: Path) -> bool:@@ -428,7 +405,6 @@ def test_install_with_junctioned_skills_dir(served_repo, monkeypatch, tmp_path):assert "Installed:" in sink.getvalue()-SKILL_MD_MISSING_REF = """---name: partial-bundledescription: References a support file that is unreachable.@@ -502,10 +478,6 @@ def test_install_skips_unreachable_support_file_e2e(served_repo_missing_support,assert "references/absent.md" not in entry["files"]----def test_bundled_optional_source_still_includes_support_files(tmp_path, monkeypatch):from tools.skills_hub_official import OptionalSkillSource@@ -538,7 +510,6 @@ metadata:def test_optional_source_upstream_stub_fetches_from_external_repo(tmp_path, monkeypatch):"""A catalog stub with metadata.hermes.upstream installs the upstream repo'scontent (relabelled official/trusted), not the stub itself."""- from tools.skills_hub_models import SkillBundlefrom tools.skills_hub_official import OptionalSkillSourceroot = tmp_path / "optional-skills"diff --git a/tests/tools/test_skill_create_dir.py b/tests/tools/test_skill_create_dir.pyindex 8ed0b6bfd81..d26a1bbfc0a 100644--- a/tests/tools/test_skill_create_dir.py+++ b/tests/tools/test_skill_create_dir.py@@ -95,12 +95,6 @@ class TestDisplaySkillCreateDir:_write_config(isolated_home, f"skills:\n create_dir: {brain}\n")assert "opt-brain" in display_skill_create_dir()- def test_schema_helper_follows_config(self, isolated_home, tmp_path):- from tools.skill_manager_tool import _display_create_dir- brain = tmp_path / "opt-brain"- _write_config(isolated_home, f"skills:\n create_dir: {brain}\n")- assert "opt-brain" in _display_create_dir()-class TestDiscovery:def test_create_dir_in_all_skills_dirs(self, isolated_home, tmp_path):diff --git a/tests/tools/test_skill_improvements.py b/tests/tools/test_skill_improvements.pyindex 38b4f8455d2..a6ab206c85f 100644--- a/tests/tools/test_skill_improvements.py+++ b/tests/tools/test_skill_improvements.py@@ -102,12 +102,6 @@ word word word# Should succeed via line-trimmed or indentation-flexible matchingassert result["success"] is True- @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")- def test_created_skill_is_group_readable(self):- """New instructional skills use the public-document mode 0644."""- _create_skill("mode-skill", SKILL_CONTENT)- mode = stat.S_IMODE((self.skills_dir / "mode-skill" / "SKILL.md").stat().st_mode)- assert mode == 0o644def test_create_rollback_removes_skill_when_scan_blocks(self, monkeypatch):"""Blocked skill creation removes the newly created skill directory."""@@ -159,7 +153,7 @@ word word wordassert stat.S_IMODE(skill_md.stat().st_mode) == 0o660@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")- @pytest.mark.parametrize("mode", [0o600, 0o660])+ @pytest.mark.parametrize("mode", [0o600])def test_edit_preserves_existing_mode(self, mode):"""Full skill edits must preserve private and shared document modes."""_create_skill("mode-skill", SKILL_CONTENT)@@ -173,7 +167,7 @@ word word wordassert stat.S_IMODE(skill_md.stat().st_mode) == mode@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")- @pytest.mark.parametrize("mode", [0o600, 0o660])+ @pytest.mark.parametrize("mode", [0o600])def test_patched_skill_preserves_existing_mode(self, mode):"""Atomic patching must preserve both private and shared modes."""_create_skill("mode-skill", SKILL_CONTENT)@@ -185,23 +179,9 @@ word word wordassert result["success"] is Trueassert stat.S_IMODE(skill_md.stat().st_mode) == mode- @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")- def test_supporting_file_write_uses_group_readable_mode(self):- """New reference files should follow the same document mode."""- _create_skill("mode-skill", SKILL_CONTENT)-- result = _write_file(- "mode-skill",- "references/example.md",- "# Reference\n",- )-- assert result["success"] is True- reference = self.skills_dir / "mode-skill" / "references/example.md"- assert stat.S_IMODE(reference.stat().st_mode) == 0o644@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")- @pytest.mark.parametrize("mode", [0o600, 0o660])+ @pytest.mark.parametrize("mode", [0o600])def test_supporting_file_write_preserves_existing_mode(self, mode):"""Overwriting a reference preserves its existing private or shared mode."""_create_skill("mode-skill", SKILL_CONTENT)@@ -216,7 +196,7 @@ word word wordassert stat.S_IMODE(reference.stat().st_mode) == mode@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")- @pytest.mark.parametrize("mode", [0o600, 0o660])+ @pytest.mark.parametrize("mode", [0o600])def test_supporting_file_patch_preserves_existing_mode(self, mode):"""Patching a reference preserves its existing private or shared mode."""_create_skill("mode-skill", SKILL_CONTENT)diff --git a/tests/tools/test_skill_ledger_delta.py b/tests/tools/test_skill_ledger_delta.pyindex 99c53f6f5bb..6f37845b41e 100644--- a/tests/tools/test_skill_ledger_delta.py+++ b/tests/tools/test_skill_ledger_delta.py@@ -81,7 +81,7 @@ def test_compact_leaves_an_undecodable_ledger_untouched(ledger_home, caplog):ledger.write_bytes(b"\xff")assert skill_ledger.compact_ledger() == (0, 0, 0)assert ledger.read_bytes() == b"\xff"- assert "compaction skipped" in caplog.text+ assert any(r.levelno >= logging.WARNING for r in caplog.records)def test_list_entries_treats_an_undecodable_ledger_as_empty_and_warns(ledger_home, caplog):@@ -94,7 +94,7 @@ def test_list_entries_treats_an_undecodable_ledger_as_empty_and_warns(ledger_homledger.write_bytes(b"\xff")assert skill_ledger.list_entries() == []assert skill_ledger.get_entry("deadbeef") is None- assert "listing empty" in caplog.text+ assert any(r.levelno >= logging.WARNING for r in caplog.records)def test_list_entries_is_silent_when_the_ledger_is_merely_missing(ledger_home, caplog):@@ -161,7 +161,7 @@ def test_gc_keeps_rollback_blobs_when_the_ledger_cannot_be_read(ledger_home, capelse:ledger.write_bytes(b"\xff")assert skill_ledger.gc_blobs() == (0, 0)- assert "blob GC skipped" in caplog.text+ assert any(r.levelno >= logging.WARNING for r in caplog.records)assert {p.name: p.read_bytes() for p in skill_ledger.blobs_dir().iterdir()} == blobs_beforeif ledger.is_dir():ledger.rmdir()diff --git a/tests/tools/test_skill_linter.py b/tests/tools/test_skill_linter.pyindex 8532f70d42b..6b07ccce226 100644--- a/tests/tools/test_skill_linter.py+++ b/tests/tools/test_skill_linter.py@@ -1,8 +1,5 @@"""Tests for tools/skill_linter.py — the advisory SKILL.md convention linter."""-from pathlib import Path--import pytestfrom tools.skill_linter import (ERROR,@@ -181,11 +178,6 @@ def test_author_caps_warned():assert "author-caps" in _rules(findings)-def test_findings_carry_rule_and_severity():- findings = lint_content(CLEAN.replace("name: my-skill", "name: BAD"))- assert any(f.rule == "name-format" and f.severity == ERROR for f in findings)--def test_incident_log_shape_flagged_and_rule_shape_not():# A body narrating incidents by PR number is a log, not a lesson; the same lesson stated as a# rule + why with no numbers passes. Density-gated so one citation in a long body is fine.@@ -223,5 +215,5 @@ def test_oversized_body_flagged_above_budget_and_not_below():over = CLEAN + filler * (_BODY_SOFT_BUDGET_CHARS // len(filler) + 1)under = CLEAN + filler * (_BODY_SOFT_BUDGET_CHARS // len(filler) // 2)found = [f for f in lint_content(over) if f.rule == "oversized-body"]- assert found and found[0].severity == WARNING and "references/" in found[0].message+ assert found and found[0].severity == WARNINGassert "oversized-body" not in _rules(lint_content(under))diff --git a/tests/tools/test_skill_manage_batch.py b/tests/tools/test_skill_manage_batch.pyindex 0abf45f3de7..714096fd86c 100644--- a/tests/tools/test_skill_manage_batch.py+++ b/tests/tools/test_skill_manage_batch.py@@ -259,7 +259,6 @@ class TestSkillManageBatch(unittest.TestCase):self.assertTrue(r.get("staged"), r)self.assertEqual(staged["payload"]["action"], "batch")self.assertEqual(len(staged["payload"]["operations"]), 2)- self.assertIn("2 ops", staged["summary"])# Replay applies the batch (gate bypassed inside).out = json.loads(self.smt.apply_skill_pending(staged["payload"]))self.assertTrue(out["success"], out)