The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py19 (370 removed)
teknium1f287036ea335
diff --git a/tests/tools/test_skill_manage_schema_diet.py b/tests/tools/test_skill_manage_schema_diet.pyindex 365ad7db3ca..30d6471a540 100644--- a/tests/tools/test_skill_manage_schema_diet.py+++ b/tests/tools/test_skill_manage_schema_diet.py@@ -36,44 +36,6 @@ class TestSkillManageSchemaDiet(unittest.TestCase):self.assertTrue(all(p["type"] != "object" for p in branch["properties"].values()))self.assertTrue(self._op_props("delete"))- def test_patch_args_defer_to_patch_tool(self):- props = self._op_props("patch")- self.assertIn("patch tool", props["old_string"]["description"])- # The uniqueness/context curriculum lives in the patch tool's schema,- # not here.- self.assertNotIn("unique", props["old_string"]["description"])- self.assertNotIn("surrounding context", props["old_string"]["description"])-- def test_file_path_states_relative_shape(self):- desc = self._op_props("write_file")["file_path"]["description"]- self.assertIn("RELATIVE", desc)- self.assertIn("references/api.md", desc)- self.assertIn("never absolute", desc)- # The subdirectory whitelist is a real contract — must stay.- for sub in ("references/", "templates/", "scripts/", "assets/"):- self.assertIn(sub, desc)-- def test_description_cuts_hold(self):- desc = SKILL_MANAGE_SCHEMA["description"]- # Maintainer-directed: no confirm-with-user coaching.- self.assertNotIn("Confirm with the user", desc)- # Authoring curriculum compressed to the 57-char trigger rule +- # skill_view pointer; the numbered-steps/pitfalls list is gone.- self.assertIn("57 chars", desc)- self.assertIn("skill_view()", desc)- self.assertNotIn("numbered steps", desc)- # Stale action vocabulary must not return.- self.assertFalse(self._op_props("edit"))-- def test_content_keeps_pre_irreversibility_warning(self):- """The REPLACES-whole-file warning is pre-irreversibility guidance:- an error can't teach after a successful full rewrite, so it must- stay schema-side (maintainer call). Lives in the description now- (op fields stay terse)."""- desc = SKILL_MANAGE_SCHEMA["description"]- self.assertIn("REPLACES", desc)- self.assertIn("skill_view()", desc)-def _fits(op, branch):"""Plain-Python reading of one per-action branch (required + enum + additionalProperties:diff --git a/tests/tools/test_skill_manager_tool.py b/tests/tools/test_skill_manager_tool.pyindex 7651858efa9..e86873200bd 100644--- a/tests/tools/test_skill_manager_tool.py+++ b/tests/tools/test_skill_manager_tool.py@@ -1,6 +1,5 @@"""Tests for tools/skill_manager_tool.py — skill creation, editing, and deletion."""-import hashlibimport jsonimport threadingfrom contextlib import contextmanager@@ -28,7 +27,6 @@ from tools.skill_manager_tool import (from agent.skill_utils import (extract_skill_description,parse_frontmatter,- SKILL_PROMPT_DESC_LIMIT,)@@ -88,22 +86,16 @@ class TestValidateName:assert _validate_name("a") is Nonedef test_special_chars_rejected(self):- err = _validate_name("skill/name")- assert "Invalid skill name 'skill/name'" in err- err = _validate_name("skill name")- assert "Invalid skill name 'skill name'" in err- err = _validate_name("skill@name")- assert "Invalid skill name 'skill@name'" in err+ for bad in ("skill/name", "skill name", "skill@name"):+ assert _validate_name(bad) is not Noneclass TestValidateCategory:def test_path_traversal_rejected(self):- err = _validate_category("../escape")- assert "Invalid category '../escape'" in err+ assert _validate_category("../escape") is not Nonedef test_absolute_path_rejected(self):- err = _validate_category("/tmp/escape")- assert "Invalid category '/tmp/escape'" in err+ assert _validate_category("/tmp/escape") is not None# ---------------------------------------------------------------------------@@ -114,11 +106,11 @@ class TestValidateCategory:class TestValidateFrontmatter:def test_no_frontmatter(self):err = _validate_frontmatter("# Just a heading\nSome content.\n")- assert err == "SKILL.md must start with YAML frontmatter (---). See existing skills for format."+ assert err is not Nonedef test_invalid_yaml(self):content = "---\n: invalid: yaml: {{{\n---\n\nBody.\n"- assert "YAML frontmatter parse error" in _validate_frontmatter(content)+ assert _validate_frontmatter(content) is not None# ---------------------------------------------------------------------------@@ -134,19 +126,16 @@ class TestValidateFilePath:assert _validate_file_path("assets/image.png") is Nonedef test_path_traversal_blocked(self):- err = _validate_file_path("references/../../../etc/passwd")- assert err == "Path traversal ('..') is not allowed."+ assert _validate_file_path("references/../../../etc/passwd") is not Nonedef test_skill_md_traversal_still_rejected(self):# The SKILL.md exception must not weaken the traversal guard.- err = _validate_file_path("../SKILL.md")- assert err == "Path traversal ('..') is not allowed."+ assert _validate_file_path("../SKILL.md") is not Nonedef test_other_root_md_still_rejected(self):# Only SKILL.md gets the root-level exception, not arbitrary files.- err = _validate_file_path("README.md")- assert "File must be under one of:" in err+ assert _validate_file_path("README.md") is not None# ---------------------------------------------------------------------------@@ -177,7 +166,6 @@ class TestCreateSkill:result = _create_skill("my-skill", VALID_SKILL_CONTENT, category="../escape")assert result["success"] is False- assert "Invalid category '../escape'" in result["error"]assert not (tmp_path / "escape").exists()@@ -189,7 +177,6 @@ class TestCreateSkill:result = _edit_skill("my-skill", LONG_DESC_CONTENT)assert result["success"] is Trueassert "system_prompt_preview" in result- assert "System prompt will show" in result["system_prompt_preview"]fm, _ = parse_frontmatter(LONG_DESC_CONTENT)assert extract_skill_description(fm) in result["system_prompt_preview"]@@ -286,23 +273,6 @@ word wordassert result["success"] is Falseassert "match" in result["error"].lower()- def test_patch_missing_old_string_tells_the_model_how_to_recover(self, tmp_path):- """#33064 — a bare 'required' error is a dead end.-- The model cannot tell whether it omitted old_string or supplied it wrongly,- so it retries blindly and escapes to action='write_file', clobbering the- whole skill file. The error must say how to obtain the exact text, and must- forbid the whole-file rewrite.- """- with _skill_dir(tmp_path):- _create_skill("my-skill", VALID_SKILL_CONTENT)- result = _patch_skill("my-skill", "", "replacement")-- assert result["success"] is False- err = result["error"]- assert "read" in err.lower(), "must tell the model to read the file first"- assert "write_file" in err, "must name the escape hatch it is forbidding"- assert "exact" in err.lower()@@ -393,7 +363,6 @@ class TestSkillMutationLock:lock = _skill_lock_path("mlops/foo")assert lock == _skill_lock_path("foo")assert lock.parent == tmp_path / ".locks"- assert lock.name == hashlib.sha256(b"foo").hexdigest() + ".lock"class TestDeleteSkill:@@ -409,7 +378,6 @@ class TestDeleteSkill:_create_skill("narrow", VALID_SKILL_CONTENT)result = _delete_skill("narrow", absorbed_into="narrow")assert result["success"] is False- assert "cannot equal" in result["error"]assert (tmp_path / "narrow").exists()# ---------------------------------------------------------------------------@@ -482,26 +450,6 @@ class TestRemoveFile:class TestSkillManageDispatcher:- @pytest.mark.parametrize("old_string", [None, ""])- def test_patch_missing_old_string_carries_recovery_guidance(self, tmp_path, old_string):- """#33064 — the actionable error must survive the public dispatch path.-- The dispatcher used to return its own bare "old_string is required"- before ever reaching _patch_skill, so the guidance below was- unreachable through the tool the model actually calls. Assert on the- serialized public result, not the helper's dict.- """- with _skill_dir(tmp_path):- _create_skill("my-skill", VALID_SKILL_CONTENT)- raw = skill_manage(action="patch", name="my-skill",- old_string=old_string, new_string="replacement")-- result = json.loads(raw)- assert result["success"] is False- err = result["error"]- assert "read" in err.lower(), "must tell the model to read the file first"- assert "write_file" in err, "must name the escape hatch it is forbidding"- assert "exact" in err.lower()@pytest.mark.parametrize("op, stray_key, destination", [({"action": "create", "file_content": VALID_SKILL_CONTENT}, "file_content", "'content'"),@@ -549,32 +497,7 @@ class TestSkillManageDispatcher:assert "operations[1]" in result["error"]assert "rolled back" not in result["error"] and not sibling_created- def test_batch_delete_forwards_absorbed_into_to_consolidation_guard(self, tmp_path):- """Curator consolidation emits ``[{action: delete, name, absorbed_into: umbrella}]`` through- the operations[] shape; the guard must see that umbrella, not None (which fail-closes)."""- with _skill_dir(tmp_path), \- patch("tools.skill_manager_tool._curator_consolidation_delete_guard",- return_value=None) as guard:- _create_skill("umbrella", VALID_SKILL_CONTENT)- _create_skill("narrow", VALID_SKILL_CONTENT)- result = json.loads(skill_manage(action="", name="", operations=[- {"name": "narrow", "action": "delete", "absorbed_into": "umbrella"}]))-- assert result["success"] is True, result- guard.assert_called_once_with("narrow", "umbrella")- def test_unmatched_old_string_with_stray_key_is_not_steered_to_a_rewrite(self, tmp_path):- """#112677 — the misplaced-text note belongs to argument-shape misses only. A patch whose- real problem is an unmatched old_string used to get "move that text to ... 'content'- (full rewrite)" appended, steering the model toward the whole-file rewrite the patch- error itself warns against."""- with _skill_dir(tmp_path):- _create_skill("my-skill", VALID_SKILL_CONTENT)- result = json.loads(skill_manage(action="patch", name="my-skill", old_string="NOT IN FILE",- new_string="x", file_content="stray"))-- assert result["success"] is False- assert "move that text" not in result["error"]def test_write_file_given_content_names_the_reverse_misplacement(self, tmp_path):"""#112677 — the reverse direction: create's `content` sent to write_file. Checked on the@@ -610,78 +533,7 @@ class TestSkillManageDispatcher:rec = usage.get("test-skill") or {}assert rec.get("created_by") in {"learn", None, "", False}- def test_successful_mutations_emit_lifecycle_with_correlation(self, tmp_path):- with (- _skill_dir(tmp_path),- patch("tools.skill_provenance.is_background_review", return_value=False),- patch("tools.skill_usage.record_created") as record_created,- patch("tools.skill_usage.bump_patch") as bump_patch,- ):- created = json.loads(skill_manage(- action="create",- name="test-skill",- content=VALID_SKILL_CONTENT,- task_id="task-mutation",- session_id="session-mutation",- ))- patched = json.loads(skill_manage(- action="patch",- name="test-skill",- old_string="Step 1: Do the thing.",- new_string="Step 1: Do the thing safely.",- task_id="task-mutation",- session_id="session-mutation",- ))- edited = json.loads(skill_manage(- action="edit",- name="test-skill",- content=VALID_SKILL_CONTENT_2,- task_id="task-mutation",- session_id="session-mutation",- ))- assert created["success"] is True- assert patched["success"] is True- assert edited["success"] is True- record_created.assert_called_once_with(- "test-skill",- agent_created=False,- task_id="task-mutation",- session_id="session-mutation",- )- assert [call.kwargs for call in bump_patch.call_args_list] == [- {- "action": "patch",- "task_id": "task-mutation",- "session_id": "session-mutation",- },- {- "action": "edit",- "task_id": "task-mutation",- "session_id": "session-mutation",- },- ]- assert all(call.args == ("test-skill",) for call in bump_patch.call_args_list)-- def test_failed_mutations_do_not_emit_lifecycle(self, tmp_path):- with (- _skill_dir(tmp_path),- patch("tools.skill_usage.record_created") as record_created,- patch("tools.skill_usage.bump_patch") as bump_patch,- ):- create_result = json.loads(skill_manage(- action="create",- name="test-skill",- ))- patch_result = json.loads(skill_manage(- action="patch",- name="test-skill",- ))-- assert create_result["success"] is False- assert patch_result["success"] is False- record_created.assert_not_called()- bump_patch.assert_not_called()def test_background_review_delete_refuses_bundled_even_with_absorbed_into(self, tmp_path):@@ -761,18 +613,6 @@ Step 2: Do the other thing.assert "Step 2: Do the other thing." in after, "unrelated content lost"assert after.startswith("---"), "frontmatter destroyed"- def test_recovery_never_requires_write_file(self, tmp_path):- """The forbidden escape hatch must never be *necessary* to recover."""- with _skill_dir(tmp_path):- _create_skill("my-skill", self.CONTENT)- bad = json.loads(skill_manage(action="patch", name="my-skill",- old_string="", new_string="x"))- assert "write_file" in bad["error"]-- ok = json.loads(skill_manage(action="patch", name="my-skill",- old_string="Step 2: Do the other thing.",- new_string="Step 2: Done."))- assert ok["success"] is True, f"recovery required write_file? {ok}"@pytest.mark.parametrize("kwargs", [{"old_string": None, "new_string": "x"},@@ -790,19 +630,6 @@ Step 2: Do the other thing.assert result["success"] is Falseassert before == after, "rejected patch mutated the file"- def test_validation_precedes_skill_lookup(self, tmp_path):- """Centralizing validation must not reorder it behind the skill lookup.-- A missing old_string on a nonexistent skill should still report the- argument error — reporting 'skill not found' first would send the model- chasing the wrong problem.- """- with _skill_dir(tmp_path):- result = json.loads(skill_manage(action="patch", name="does-not-exist",- new_string="x"))- assert result["success"] is False- assert "old_string" in result["error"].lower()- assert "not found" not in result["error"].lower()def test_empty_new_string_still_deletes(self, tmp_path):"""new_string='' is legal (delete matched text) and must NOT be rejected."""@@ -862,7 +689,6 @@ class TestSecurityScanGate:result = _security_scan_skill(tmp_path)assert result is not None- assert "Security scan blocked" in resultdef test_guard_flag_handles_config_error(self):"""If load_config raises, _guard_agent_created_enabled defaults to False (fail-safe off)."""@@ -1116,8 +942,6 @@ class TestPinnedGuard:result = _delete_skill("my-skill")assert result["success"] is Falseassert "pinned" in result["error"].lower()- assert "cannot be deleted" in result["error"]- assert "hermes curator unpin my-skill" in result["error"]# Skill still existsassert (tmp_path / "my-skill" / "SKILL.md").exists()diff --git a/tests/tools/test_skill_provenance.py b/tests/tools/test_skill_provenance.pyindex d3fce754843..3a2cb1f5624 100644--- a/tests/tools/test_skill_provenance.py+++ b/tests/tools/test_skill_provenance.py@@ -3,17 +3,6 @@import contextvars-def test_set_and_get_origin():- from tools.skill_provenance import (- set_current_write_origin,- reset_current_write_origin,- get_current_write_origin,- )- token = set_current_write_origin("background_review")- try:- assert get_current_write_origin() == "background_review"- finally:- reset_current_write_origin(token)def test_empty_origin_falls_back_to_foreground():diff --git a/tests/tools/test_skill_size_limits.py b/tests/tools/test_skill_size_limits.pyindex 50d55831f3f..be2e43fc6b4 100644--- a/tests/tools/test_skill_size_limits.py+++ b/tests/tools/test_skill_size_limits.py@@ -84,7 +84,6 @@ class TestEditSkillSizeLimit:big = big.replace("name: test-skill", "name: grow-me")result = json.loads(skill_manage(action="edit", name="grow-me", content=big))assert result["success"] is False- assert "100,000" in result["error"]class TestPatchSkillSizeLimit:@@ -103,7 +102,6 @@ class TestPatchSkillSizeLimit:new_string="# Test Skill\n" + ("y" * 200),))assert result["success"] is False- assert "100,000" in result["error"]def test_patch_supporting_file_size_limit(self, isolate_skills):@@ -143,7 +141,6 @@ class TestWriteFileSizeLimit:file_content="x" * (MAX_SKILL_CONTENT_CHARS + 1),))assert result["success"] is False- assert "100,000" in result["error"]def test_write_file_within_limit(self, isolate_skills):small = _make_skill_content(1000)diff --git a/tests/tools/test_skill_usage.py b/tests/tools/test_skill_usage.pyindex fcae7c1533f..fb9c95f8b33 100644--- a/tests/tools/test_skill_usage.py+++ b/tests/tools/test_skill_usage.py@@ -62,9 +62,6 @@ description: test skill# Round-trip# ----------------------------------------------------------------------------def test_empty_usage_returns_empty_dict(skills_home):- from tools.skill_usage import load_usage- assert load_usage() == {}def test_save_and_load_roundtrip(skills_home):@@ -333,10 +330,6 @@ def test_concurrent_bump_view_preserves_all_updates(skills_home):# State transitions# ----------------------------------------------------------------------------def test_set_state_active(skills_home):- from tools.skill_usage import set_state, get_record, STATE_ACTIVE- set_state("x", STATE_ACTIVE)- assert get_record("x")["state"] == "active"def test_restoring_from_archive_clears_timestamp(skills_home):diff --git a/tests/tools/test_skill_view_dedup.py b/tests/tools/test_skill_view_dedup.pyindex 50421fc36ec..4da17df191d 100644--- a/tests/tools/test_skill_view_dedup.py+++ b/tests/tools/test_skill_view_dedup.py@@ -1,9 +1,7 @@"""Tests for skill_view repeat-view dedup (unchanged-skill stub)."""import json-import osimport time-from pathlib import Pathimport pytest@@ -53,7 +51,6 @@ class TestSkillViewDedup:assert r2["success"] is Trueassert r2.get("dedup") is Trueassert r2.get("content_returned") is False- assert "unchanged" in r2["message"]assert "content" not in r2def test_modified_skill_returns_full_content(self, skills_home):@@ -132,7 +129,3 @@ class TestSkillViewDedup:assert repeat.get("dedup") is Trueassert repeat.get("content_returned") is False- def test_compression_hook_importable(self):- # conversation_compression imports this lazily; keep the seam stable.- from tools.skills_tool import reset_skill_view_dedup as f- f(None)diff --git a/tests/tools/test_skill_view_path_check.py b/tests/tools/test_skill_view_path_check.pydeleted file mode 100644index c72504ca547..00000000000--- a/tests/tools/test_skill_view_path_check.py+++ /dev/null@@ -1,106 +0,0 @@-"""Tests for the skill_view path boundary check.--Regression test: the original check used a hardcoded "/" separator which-fails on Windows where Path.resolve() returns backslash-separated paths.-Now uses Path.is_relative_to() which handles all platforms correctly.-"""--import pytest-from pathlib import Path---def _path_escapes_skill_dir(resolved: Path, skill_dir_resolved: Path) -> bool:- """Reproduce the boundary check from tools/skills_tool.py.-- Returns True when the resolved path is OUTSIDE the skill directory.- """- return not resolved.is_relative_to(skill_dir_resolved)---class TestSkillViewPathBoundaryCheck:- """Verify the path boundary check works on all platforms."""-- def test_valid_subpath_allowed(self, tmp_path):- """A file inside the skill directory must NOT be flagged."""- skill_dir = tmp_path / "skills" / "axolotl"- ref_file = skill_dir / "references" / "api.md"- skill_dir.mkdir(parents=True)- ref_file.parent.mkdir()- ref_file.write_text("content")-- resolved = ref_file.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is False--- def test_outside_path_blocked(self, tmp_path):- """A file outside the skill directory must be flagged."""- skill_dir = tmp_path / "skills" / "axolotl"- skill_dir.mkdir(parents=True)- outside_file = tmp_path / "secret.env"- outside_file.write_text("SECRET=123")-- resolved = outside_file.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is True-- def test_sibling_skill_dir_blocked(self, tmp_path):- """A file in a sibling skill directory must be flagged.-- This catches prefix confusion: 'axolotl-v2' starts with 'axolotl'- as a string but is a different directory.- """- skill_dir = tmp_path / "skills" / "axolotl"- sibling_dir = tmp_path / "skills" / "axolotl-v2"- skill_dir.mkdir(parents=True)- sibling_dir.mkdir(parents=True)- sibling_file = sibling_dir / "SKILL.md"- sibling_file.write_text("other skill")-- resolved = sibling_file.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is True-- def test_skill_dir_itself_allowed(self, tmp_path):- """Requesting the skill directory itself must be allowed."""- skill_dir = tmp_path / "skills" / "axolotl"- skill_dir.mkdir(parents=True)-- resolved = skill_dir.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is False---class TestOldCheckWouldFail:- """Demonstrate the bug: the old hardcoded '/' check fails on Windows."""-- def _old_path_escapes(self, resolved: Path, skill_dir_resolved: Path) -> bool:- """The BROKEN check that used hardcoded '/'."""- return (- not str(resolved).startswith(str(skill_dir_resolved) + "/")- and resolved != skill_dir_resolved- )-- # ``windows_only`` rather than ``skipif(os.sep == "/")``: the Windows CI- # job greps for the marker to decide which files to import, so a bare- # skipif leaves this running on no host at all.- @pytest.mark.windows_only- def test_old_check_false_positive_on_windows(self, tmp_path):- """On Windows, the old check incorrectly blocks valid subpaths."""- skill_dir = tmp_path / "skills" / "axolotl"- ref_file = skill_dir / "references" / "api.md"- skill_dir.mkdir(parents=True)- ref_file.parent.mkdir()- ref_file.write_text("content")-- resolved = ref_file.resolve()- skill_dir_resolved = skill_dir.resolve()-- # Old check says it escapes (WRONG on Windows)- assert self._old_path_escapes(resolved, skill_dir_resolved) is True- # New check correctly allows it- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is Falsediff --git a/tests/tools/test_skillevaluator_scan.py b/tests/tools/test_skillevaluator_scan.pyindex 4ae22ca9e4f..36bee2ea027 100644--- a/tests/tools/test_skillevaluator_scan.py+++ b/tests/tools/test_skillevaluator_scan.py@@ -12,13 +12,10 @@ import sysfrom pathlib import Pathfrom unittest import mock-import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[2]))from tools.skillevaluator_scan import ( # noqa: E402- SECRETS_CLASS_CHECKS,- Tier1Finding,Tier1Report,_parse_report,format_tier1_report,@@ -70,16 +67,7 @@ class TestParseReport:assert len(report.secrets_findings) == 1assert report.advisory_findings == []- def test_all_secrets_class_checks_classify(self):- for check in SECRETS_CLASS_CHECKS:- f = Tier1Finding(check=check, validator="PII Scan",- severity="critical", message="x")- assert f.is_secrets_class, check- def test_personal_path_is_advisory(self):- f = Tier1Finding(check="personal_paths", validator="PII Scan",- severity="high", message="x")- assert not f.is_secrets_classdef test_malformed_findings_skipped(self):raw = _report_json([_finding("emails")])@@ -120,20 +108,7 @@ class TestParseReport:# failing validator was incompleteassert not report.passed- def test_incomplete_check_without_findings_stays_passed(self):- raw = _report_json([])- raw["results"].append({- "validator": "Security Scan",- "passed": False,- "status": "incomplete",- "findings": [],- })- report = _parse_report(raw)- assert report.passed- def test_complete_failed_check_still_fails(self):- report = _parse_report(_report_json([_finding("emails")]))- assert not report.passedclass TestRunTier1Scan:@@ -185,9 +160,6 @@ class TestFormatReport:def test_unavailable_is_empty(self):assert format_tier1_report(Tier1Report(available=False)) == ""- def test_clean_report_text(self):- text = format_tier1_report(Tier1Report(available=True))- assert "no findings" in textdef test_findings_show_location_and_secrets_tag(self):report = _parse_report(_report_json([@@ -199,7 +171,6 @@ class TestFormatReport:assert "[SECRETS]" in textassert "SKILL.md:3" in textassert "SKILL.md:8" in text- assert "informational" in textdef test_incomplete_checks_noted(self):raw = _report_json([])@@ -210,20 +181,16 @@ class TestFormatReport:"findings": [],})text = format_tier1_report(_parse_report(raw))- assert "not run: Security Scan" in text- assert "no findings" in text+ assert "Security Scan" in textdef test_limit_truncates(self):findings = [_finding("emails", message=f"m{i}", line=i) for i in range(1, 15)]report = _parse_report(_report_json(findings))text = format_tier1_report(report, limit=5)- assert "and 9 more" in text+ assert "9 more" in textclass TestConfigGate:- def test_default_enabled(self):- with mock.patch("hermes_cli.config.load_config", return_value={}):- assert tier1_advisory_enabled()def test_disabled_via_config(self):with mock.patch("hermes_cli.config.load_config",@@ -279,15 +246,3 @@ class TestInstallPathHelper:_print_tier1_advisory(tmp_path, console)assert console.print.called- def test_helper_warns_loud_on_secrets(self, tmp_path):- from hermes_cli.skills_hub import _print_tier1_advisory- console = mock.MagicMock()- report = _parse_report(_report_json([- _finding("private_keys", severity="critical",- message="Private key in PEM format"),- ]))- with mock.patch("tools.skillevaluator_scan.run_tier1_scan",- return_value=report):- _print_tier1_advisory(tmp_path, console)- printed = " ".join(str(c) for c in console.print.call_args_list)- assert "credentials" in printed.lower()diff --git a/tests/tools/test_skills_ast_audit.py b/tests/tools/test_skills_ast_audit.pyindex 3214211ac04..b311299581b 100644--- a/tests/tools/test_skills_ast_audit.py+++ b/tests/tools/test_skills_ast_audit.py@@ -49,4 +49,3 @@ def test_format_report_with_findings():]out = format_ast_report(findings, skill_name="test")assert "test" in out and "a.py" in out and "L1" in out and "L3" in out- assert "diagnostic hints" in outdiff --git a/tests/tools/test_skills_guard.py b/tests/tools/test_skills_guard.pyindex ed7d7d2324c..77219b32da0 100644--- a/tests/tools/test_skills_guard.py+++ b/tests/tools/test_skills_guard.py@@ -30,7 +30,6 @@ from tools.skills_guard import (_determine_verdict,_resolve_trust_level,_check_structure,- _unicode_char_name,_load_skill_ignore,MAX_FILE_COUNT,MAX_SINGLE_FILE_KB,@@ -102,7 +101,6 @@ class TestShouldAllowInstall:f = [Finding("x", "high", "network", "f", 1, "m", "d")]allowed, reason = should_allow_install(self._result("community", "caution", f))assert allowed is False- assert "Blocked" in reason# When --force CAN override the block, the error must point to it.assert "Use --force to override" in reason@@ -111,7 +109,6 @@ class TestShouldAllowInstall:f = [Finding("x", "critical", "c", "f", 1, "m", "d")]allowed, reason = should_allow_install(self._result("builtin", "dangerous", f))assert allowed is True- assert "builtin source" in reason@pytest.mark.parametrize("trust", ["community", "trusted"])@@ -119,7 +116,6 @@ class TestShouldAllowInstall:f = [Finding("x", "critical", "c", "f", 1, "m", "d")]allowed, reason = should_allow_install(self._result(trust, "dangerous", f), force=True)assert allowed is False- assert "Blocked" in reason# Error message MUST explain why --force didn't work, not invite a retry.assert "does not override" in reasonassert "Use --force to override" not in reason@@ -134,7 +130,6 @@ class TestShouldAllowInstall:f = [Finding("docker_pull", "medium", "supply_chain", "SKILL.md", 1, "docker pull img", "pulls Docker image")]allowed, reason = should_allow_install(self._result("agent-created", "caution", f))assert allowed is True- assert "agent-created" in reasondef test_dangerous_agent_created_asks(self):"""Agent-created skills with dangerous verdict return None (ask for confirmation)@@ -145,7 +140,6 @@ class TestShouldAllowInstall:f = [Finding("env_exfil_curl", "critical", "exfiltration", "SKILL.md", 1, "curl $TOKEN", "exfiltration")]allowed, reason = should_allow_install(self._result("agent-created", "dangerous", f))assert allowed is None- assert "Requires confirmation" in reasondef test_force_overrides_dangerous_for_agent_created(self):f = [Finding("x", "critical", "c", "f", 1, "m", "d")]@@ -153,7 +147,6 @@ class TestShouldAllowInstall:self._result("agent-created", "dangerous", f), force=True)assert allowed is True- assert "Force-installed" in reason# ---------------------------------------------------------------------------@@ -426,7 +419,6 @@ class TestFormatScanReport:report = format_scan_report(result)assert "bad-skill" in reportassert "DANGEROUS" in report- assert "BLOCKED" in reportassert "curl $KEY" in report@@ -458,11 +450,6 @@ class TestContentHash:# ----------------------------------------------------------------------------class TestUnicodeCharName:- def test_known_and_unknown_chars(self):- assert "zero-width space" in _unicode_char_name("")- assert "BOM" in _unicode_char_name("")- assert "U+" in _unicode_char_name("A") # 'A'# ---------------------------------------------------------------------------diff --git a/tests/tools/test_skills_guard_agent_config.py b/tests/tools/test_skills_guard_agent_config.pyindex 42da5becbae..ec0b9282d71 100644--- a/tests/tools/test_skills_guard_agent_config.py+++ b/tests/tools/test_skills_guard_agent_config.py@@ -24,7 +24,7 @@ from pathlib import Pathimport pytest-from tools.skills_guard import SCANNER_VERSION, scan_skill+from tools.skills_guard import scan_skilldef _scan(tmp_path: Path, content: str):@@ -37,8 +37,6 @@ def _scan(tmp_path: Path, content: str):# The scanner version moved past v1 precisely so cached v1 dangerous verdicts# for previously-blocked skills are invalidated and re-scanned. Later bumps# are expected whenever rules change; only regressing to v1 is a bug.-def test_scanner_version_bumped():- assert SCANNER_VERSION != "skills-guard-v1"class TestFalsePositivesUnblocked:@@ -182,22 +180,3 @@ class TestTruePositivesStillCaught:assert result.verdict == "dangerous"-class TestVerdictContract:- """Invariant: only critical findings produce 'dangerous' from these patterns."""-- @pytest.mark.parametrize(- "content,min_severity",- [- ("Edit AGENTS.md now.", "high"),- ("echo 'x' >> AGENTS.md", "critical"),- ("See docs/AGENTS.md.", None),- ],- )- def test_severity_drives_verdict(self, tmp_path, content, min_severity):- result = _scan(tmp_path, content)- if min_severity == "critical":- assert result.verdict == "dangerous"- elif min_severity == "high":- assert result.verdict in ("caution", "dangerous")- else:- assert result.verdict == "safe"diff --git a/tests/tools/test_skills_hub.py b/tests/tools/test_skills_hub.pyindex d9efc61a6a3..8ef31104e5f 100644--- a/tests/tools/test_skills_hub.py+++ b/tests/tools/test_skills_hub.py@@ -78,30 +78,6 @@ class TestSkillsShGroupings:}- def test_list_skills_stamps_category_from_sidecar(self):- auth = MagicMock()- src = GitHubSource(auth=auth)-- meta = SkillMeta(- name="cuopt-developer", description="d", source="github",- identifier="NVIDIA/skills/skills/cuopt-developer", trust_level="trusted",- )- contents = [{"type": "dir", "name": "cuopt-developer"}]- groupings = {"cuopt-developer": "Decision Optimization"}-- resp = MagicMock()- resp.status_code = 200- resp.json.return_value = contents-- with patch("tools.skills_hub._read_index_cache", return_value=None), \- patch("tools.skills_hub._write_index_cache"), \- patch.object(src, "_get_skillsh_groupings", return_value=groupings), \- patch.object(src, "inspect", return_value=meta), \- patch("tools.skills_hub.httpx.get", return_value=resp):- skills = src._list_skills_in_repo("NVIDIA/skills", "skills/")-- assert len(skills) == 1- assert skills[0].extra["category"] == "Decision Optimization"def test_list_skills_bucket_stamps_category_when_no_sidecar(self):# A tap-level bucket labels every skill when the repo ships no skills.sh.json@@ -249,7 +225,6 @@ class TestSkillsShSource:assert len(results) == 1assert results[0].source == "skills.sh"assert results[0].identifier == "skills-sh/vercel-labs/agent-skills/vercel-react-best-practices"- assert "skills.sh" in results[0].descriptionassert results[0].repo == "vercel-labs/agent-skills"assert results[0].path == "vercel-react-best-practices"assert results[0].extra["installs"] == 207679@@ -546,10 +521,7 @@ class TestUrlSource:"references/file?","references/file?.md","references/agent.v?.md",- "references/data.file?.md",- "references/backup.2026?.md","references/file?x.md",- "references/agent.v?x.md","references/file?[ab].md","references/file??.md","references/[ab].md",@@ -573,10 +545,7 @@ Complex cases are documented under `{glob_reference}`.[("templates/report.md?raw=1", "templates/report.md"),("references/LICENSE?download", "references/LICENSE"),- ("references/LICENSE?raw", "references/LICENSE"),("references/guide.md?view", "references/guide.md"),- ("references/guide.md?inline", "references/guide.md"),- ("references/guide.md?plain", "references/guide.md"),("references/guide.md?preview-mode", "references/guide.md"),("references/guide.md?view&inline&theme=dark", "references/guide.md"),("references/LICENSE?plain&download=1", "references/LICENSE"),@@ -1068,8 +1037,6 @@ class TestAppendAuditLog:content = log_file.read_text()assert "INSTALL" in contentassert "test-skill" in content- assert "github:trusted" in content- assert "pass" in content# ---------------------------------------------------------------------------# Official skills / binary assets@@ -1313,50 +1280,6 @@ class TestQuarantineBundleBinaryAssets:assert (q_path / "SKILL.md").read_text(encoding="utf-8").startswith("---")assert (q_path / "assets" / "neutts-cli" / "samples" / "jo.wav").read_bytes() == b"RIFF\x00\x01fakewav"- def test_quarantine_bundle_writes_text_files_without_newline_translation(self, tmp_path, monkeypatch):- """Text members must land on disk byte-for-byte as the bundle carries them.-- Path.write_text(newline=None) translates "\\n" to os.linesep on Windows, so a- CRLF copy became the installed content while bundle_content_hash re-encodes- the str as LF — every hub skill then reported update_available forever (#117181).- """- import pathlib-- import tools.skills_hub as hub- from tools.skills_guard import content_hash-- def windows_text_mode_write_text(self, data, encoding=None, errors=None, newline=None):- # Emulate the platform translation newline=None performs on Windows;- # newline="" is the documented opt-out quarantine must rely on.- if newline != "":- data = data.replace("\n", "\r\n")- self.write_bytes(data.encode(encoding or "utf-8"))-- monkeypatch.setattr(pathlib.Path, "write_text", windows_text_mode_write_text)-- hub_dir = tmp_path / "skills" / ".hub"- with patch.object(hub, "SKILLS_DIR", tmp_path / "skills"), \- patch.object(hub, "HUB_DIR", hub_dir), \- patch.object(hub, "LOCK_FILE", hub_dir / "lock.json"), \- patch.object(hub, "QUARANTINE_DIR", hub_dir / "quarantine"), \- patch.object(hub, "AUDIT_LOG", hub_dir / "audit.log"), \- patch.object(hub, "TAPS_FILE", hub_dir / "taps.json"), \- patch.object(hub, "INDEX_CACHE_DIR", hub_dir / "index-cache"):- bundle = SkillBundle(- name="crlfskill",- files={- "SKILL.md": "---\nname: crlfskill\n---\n\nBody line one.\nBody line two.\n",- "assets/binary.bin": b"\x00\x01raw",- },- source="official",- identifier="official/mlops/models/crlfskill",- trust_level="builtin",- )-- q_path = quarantine_bundle(bundle)-- assert (q_path / "SKILL.md").read_bytes() == bundle.files["SKILL.md"].encode("utf-8")- assert content_hash(q_path) == bundle_content_hash(bundle)@pytest.mark.windows_onlydef test_quarantine_bundle_hash_matches_bundle_on_windows(self, tmp_path):@@ -2089,20 +2012,6 @@ class TestParallelSearchSourcesTimeout:assert "fast" not in timed_out_idsassert any(r.source == "fast" for r in all_results)- def test_all_fast_sources_complete_without_timeout(self):- """Happy path: when every source finishes within budget, none are- flagged and all results are collected."""- a = _FakeSource("a", results=[self._meta("a")])- b = _FakeSource("b", results=[self._meta("b")])-- all_results, source_counts, timed_out_ids = parallel_search_sources(- [a, b], query="q", overall_timeout=5.0,- )-- assert timed_out_ids == []- assert source_counts.get("a") == 1- assert source_counts.get("b") == 1- assert len(all_results) == 2class TestIndexMissFallback:@@ -2305,14 +2214,3 @@ class TestGitHubSourceFetchMissingReferencedFile:assert "references/missing.md" not in bundle.files-class TestUrlSourceFetchMissingReferencedFile:- def test_fetch_skips_missing_referenced_file(self):- md = "---\nname: demo\ndescription: demo\n---\n\nSee `references/missing.md`.\n"- source = UrlSource()- with patch.object(source, "_fetch_text", return_value=md), \- patch.object(source, "_fetch_bytes", return_value=None):- bundle = source.fetch("https://example.com/skills/demo/SKILL.md")-- assert bundle is not None- assert bundle.name == "demo"- assert "references/missing.md" not in bundle.filesdiff --git a/tests/tools/test_skills_hub_browse_sh.py b/tests/tools/test_skills_hub_browse_sh.pyindex 0dc11e25a49..aa38606545b 100644--- a/tests/tools/test_skills_hub_browse_sh.py+++ b/tests/tools/test_skills_hub_browse_sh.py@@ -3,7 +3,7 @@import unittestfrom unittest.mock import patch-from tools.skills_hub_models import SkillBundle, SkillMeta+from tools.skills_hub_models import SkillMetafrom tools.skills_hub_sources import BrowseShSource@@ -54,8 +54,6 @@ class TestBrowseShSource(unittest.TestCase):def setUp(self):self.src = BrowseShSource()- def test_source_id(self):- self.assertEqual(self.src.source_id(), "browse-sh")@patch.object(BrowseShSource, "_fetch_catalog", return_value=SAMPLE_CATALOG)def test_search_returns_results(self, _mock_catalog):diff --git a/tests/tools/test_skills_hub_clawhub.py b/tests/tools/test_skills_hub_clawhub.pyindex 2d917a8900b..bfa3d99a4f1 100644--- a/tests/tools/test_skills_hub_clawhub.py+++ b/tests/tools/test_skills_hub_clawhub.py@@ -66,11 +66,6 @@ class TestClawHubSource(unittest.TestCase):self.assertEqual(results[0].name, "CalDAV Calendar")self.assertEqual(results[0].description, "Calendar integration")- self.assertGreaterEqual(mock_get.call_count, 2)- args, kwargs = mock_get.call_args_list[0]- self.assertTrue(args[0].endswith("/skills"))- self.assertEqual(kwargs["params"], {"search": "caldav", "limit": 5})-@patch("tools.skills_hub.httpx.get")def test_inspect_maps_display_name_and_summary(self, mock_get):@@ -137,26 +132,6 @@ class TestClawHubSource(unittest.TestCase):self.assertIsNotNone(meta)self.assertEqual(meta.extra.get("owner"), "thesethrose")- @patch("tools.skills_hub.httpx.get")- def test_inspect_tolerates_missing_owner(self, mock_get):- """inspect() should still work when the API omits owner."""- mock_get.return_value = _MockResponse(- status_code=200,- json_data={- "skill": {- "slug": "some-skill",- "displayName": "Some Skill",- "summary": "A skill",- "tags": {"latest": "1.0.0"},- },- "latestVersion": {"version": "1.0.0"},- },- )-- meta = self.src.inspect("some-skill")-- self.assertIsNotNone(meta)- self.assertNotIn("owner", meta.extra or {})@patch("tools.skills_hub_clawhub._guarded_http_stream")@patch("tools.skills_hub._ssrf_safe_http_get")@@ -196,7 +171,6 @@ class TestClawHubSource(unittest.TestCase):self.assertIn("SKILL.md", bundle.files)self.assertEqual(bundle.files["SKILL.md"], "# Skill")self.assertEqual(bundle.files["README.md"], "hello")- mock_safe_get.assert_called_once_with("https://files.example/skill-md", timeout=20, headers=None)@patch("tools.skills_hub.httpx.get")def test_fetch_falls_back_to_versions_list(self, mock_get):@@ -252,7 +226,6 @@ class TestClawHubSource(unittest.TestCase):bundle = self.src.fetch("caldav-calendar")self.assertIsNone(bundle)- self.assertEqual(mock_get.call_count, 2)mock_safe_get.assert_not_called()@patch("tools.skills_hub._write_index_cache")@@ -512,9 +485,9 @@ class TestClawHubCatalogWalkBounded(unittest.TestCase):with patch.object(ClawHubSource, "CATALOG_WALK_BUDGET_SECONDS", -1):results = self.src._load_catalog_index(max_items=0)- # No budget -> walks until the 750-page safety cap, not ~14 pages in 12s.- self.assertEqual(page_calls["n"], 750)- self.assertEqual(len(results), 750)+ # No budget -> keeps walking to the safety cap, not ~14 pages in 12s.+ self.assertGreater(page_calls["n"], 100)+ self.assertEqual(len(results), page_calls["n"])@patch("tools.skills_hub_clawhub.time.sleep")@patch("tools.skills_hub._write_index_cache")@@ -607,26 +580,6 @@ class TestFetchOwnerHandleRetry(unittest.TestCase):self.assertEqual(mock_get.call_count, 2)mock_sleep.assert_called_once_with(3.0)- @patch("tools.skills_hub.time.sleep")- @patch("tools.skills_hub.httpx.get")- def test_retries_on_429_without_retry_after_uses_exponential_backoff(self, mock_get, mock_sleep):- """On 429 without Retry-After, use exponential backoff (2s, 4s)."""- mock_get.side_effect = [- _MockResponse(status_code=429, headers={}),- _MockResponse(status_code=429, headers={}),- _MockResponse(- status_code=200,- json_data={"skill": {"slug": "test"}, "owner": {"handle": "bob"}},- ),- ]-- handle = self.src._fetch_owner_handle("test")-- self.assertEqual(handle, "bob")- self.assertEqual(mock_get.call_count, 3)- self.assertEqual(mock_sleep.call_count, 2)- mock_sleep.assert_any_call(2.0) # first backoff: 2s- mock_sleep.assert_any_call(4.0) # second backoff: 4s@patch("tools.skills_hub.time.sleep")@patch("tools.skills_hub.httpx.get")@@ -656,7 +609,7 @@ class TestFetchOwnerHandleRetry(unittest.TestCase):self.assertEqual(handle, "carol")self.assertEqual(mock_get.call_count, 2)- mock_sleep.assert_called_once_with(2.0)+ mock_sleep.assert_called_once()@patch("tools.skills_hub.time.sleep")@patch("tools.skills_hub.httpx.get")@@ -687,7 +640,7 @@ class TestFetchOwnerHandleRetry(unittest.TestCase):self.assertEqual(handle, "dave")self.assertEqual(mock_get.call_count, 2)- mock_sleep.assert_called_once_with(2.0)+ mock_sleep.assert_called_once()@patch("tools.skills_hub.time.sleep")@patch("tools.skills_hub.httpx.get")diff --git a/tests/tools/test_skills_sync.py b/tests/tools/test_skills_sync.pyindex b532881aac1..84dc88c5985 100644--- a/tests/tools/test_skills_sync.py+++ b/tests/tools/test_skills_sync.py@@ -14,12 +14,10 @@ from tools.skills_sync import (_read_skill_name,_write_manifest,_discover_bundled_skills,- _compute_relative_dest,_dir_hash,sync_skills,)from tools.skills_sync_bundled_ops import reset_bundled_skill-from tools.skills_sync_optional import restore_official_optional_skillclass TestReadWriteManifest:@@ -137,13 +135,6 @@ class TestReadSkillName:assert skills[0][0] == "audiocraft-audio-generation"-class TestComputeRelativeDest:- def test_preserves_category_structure(self):- bundled = Path("/repo/skills")- dest = _compute_relative_dest(Path("/repo/skills/mlops/axolotl"), bundled)- assert str(dest).endswith("mlops/axolotl")- # Flat (uncategorized) skills keep their own name.- assert _compute_relative_dest(Path("/repo/skills/simple"), bundled).name == "simple"class TestRmtreeWritableScopeGuard:@@ -606,7 +597,6 @@ class TestResetBundledSkill:assert untracked["ok"] is Falseassert untracked["action"] == "not_in_manifest"- assert "not a tracked bundled skill" in untracked["message"]# Tracked in the manifest, but no longer shipped upstream.ghost = skills_dir / "productivity" / "ghost-skill"@@ -696,7 +686,6 @@ class TestResetBundledSkill:# Restore failed, and the manifest must be left untouched.assert result["ok"] is Falseassert result["action"] == "not_reset"- assert "Manifest entry preserved" in result["message"]manifest_after = manifest_file.read_text()assert "google-workspace" in manifest_after# User copy is still on disk (we changed nothing).diff --git a/tests/tools/test_skills_sync_client.py b/tests/tools/test_skills_sync_client.pyindex 449194c9fdd..4c62f04e98a 100644--- a/tests/tools/test_skills_sync_client.py+++ b/tests/tools/test_skills_sync_client.py@@ -277,14 +277,6 @@ class TestAddressing:)assert len(addr.split(":", 1)[1]) == 64- def test_address_differs_from_local_truncated_namespace(self):- # The wire full-64-hex must NOT equal the local truncated 16-hex form.- data = b"hello world"- full = wire.wire_address(data)- truncated = "sha256:" + hashlib.sha256(data).hexdigest()[:16]- assert full != truncated- assert len(full.split(":")[1]) == 64- assert len(truncated.split(":")[1]) == 16def test_canonical_json_sorted_no_whitespace(self):out = wire.canonical_json_bytes({"b": 1, "a": 2})@@ -292,9 +284,6 @@ class TestAddressing:assert b" " not in outassert not out.endswith(b"\n")- def test_canonical_json_stable(self):- obj = {"type": "tree", "entries": [{"name": "x", "hash": "sha256:aa"}]}- assert wire.canonical_json_bytes(obj) == wire.canonical_json_bytes(dict(obj))# ---------------------------------------------------------------------------@@ -505,12 +494,6 @@ def synced_env(tmp_path, monkeypatch):class TestEndToEnd:- def test_capabilities_version_check(self, mock_server):- base, state = mock_server- client = ssc.SyncClient(base, "tok")- caps = client.capabilities()- assert caps["hsp_version"] == "1"- wire._check_version(caps) # no raisedef test_version_mismatch_raises(self, mock_server):base, state = mock_server@@ -1047,21 +1030,6 @@ class TestOrgEndpointScoping:def _admin(self, identity):return {**identity, "org_id": "org-1", "org_role": "ADMIN"}- def test_org_head_is_not_visible_on_the_personal_route(- self, mock_server, synced_env- ):- base, state = mock_server- home, skills, identity = synced_env- state.refs["refs/org/org-1/HEAD"] = "sha256:" + "a" * 64- client = ssc.SyncClient(base, identity["api_key"])-- personal = client.get_refs("refs/org/org-1/")- assert personal == [], (- "the personal refs route must not serve org refs — if it does, "- "the mock is more permissive than production and will hide bugs"- )- org = client.get_refs("refs/org/org-1/", org_scope=True)- assert [r["name"] for r in org] == ["refs/org/org-1/HEAD"]def test_second_propose_splices_onto_the_existing_org_head(self, mock_server, synced_env@@ -1091,31 +1059,11 @@ class TestOrgEndpointScoping:assert "alpha" in names and "devops" in namesassert commit["parents"], "second commit must descend from the first"- def test_pull_org_skills_sees_an_existing_org_head(- self, mock_server, synced_env- ):- """pull_org_skills used to report head=None for a populated org."""- base, state = mock_server- home, skills, identity = synced_env- admin = self._admin(identity)- client = ssc.SyncClient(base, identity["api_key"])- org.propose_skill("alpha", client, identity=admin)-- result = org.pull_org_skills(client=client, identity=admin)- assert result["ok"] is True- assert result["head"] == state.refs["refs/org/org-1/HEAD"], (- "pull must resolve the real org HEAD, not None"- )- assert result["updated"], "the org's skill must materialize"class TestEmptyActualConflict:"""A 409 with an empty ``actual`` means the ref does not exist."""- def test_conflict_actual_empty_becomes_none(self):- c = ssc.SyncConflict("")- assert c.actual is None- assert "does not exist" in str(c)def test_push_recovers_from_a_stale_local_head(self, mock_server, synced_env):"""Switching sync planes leaves a foreign head in local state.diff --git a/tests/tools/test_skills_tool.py b/tests/tools/test_skills_tool.pyindex 237285e26f0..c43ad5410b7 100644--- a/tests/tools/test_skills_tool.py+++ b/tests/tools/test_skills_tool.py@@ -2,6 +2,7 @@import jsonimport os+import sysfrom pathlib import Pathfrom unittest.mock import patch@@ -568,16 +569,13 @@ class TestSkillMatchesPlatform:def test_string_form_case_insensitive_and_unknown_platforms(self):- with patch("agent.skill_utils.sys") as mock_sys:- mock_sys.platform = "darwin"- # A single string value is treated as a one-element list.- assert skill_matches_platform({"platforms": "macos"}) is True- assert skill_matches_platform({"platforms": ["MacOS"]}) is True- assert skill_matches_platform({"platforms": ["MACOS"]}) is True-- mock_sys.platform = "linux"- assert skill_matches_platform({"platforms": "macos"}) is False- assert skill_matches_platform({"platforms": ["freebsd"]}) is False+ # Host-native: tag with the running platform (no sys.platform faking).+ host = sys.platform+ # A single string value is treated as a one-element list; case-insensitive.+ assert skill_matches_platform({"platforms": host.upper()}) is True+ assert skill_matches_platform({"platforms": [host.title()]}) is True+ assert skill_matches_platform({"platforms": "plan9"}) is False+ assert skill_matches_platform({"platforms": ["plan9"]}) is False# ---------------------------------------------------------------------------@@ -589,42 +587,17 @@ class TestFindAllSkillsPlatformFiltering:"""Test that _find_all_skills respects the platforms field."""def test_discovery_filters_on_platform(self, tmp_path):- with (- patch("tools.skills_tool.SKILLS_DIR", tmp_path),- patch("agent.skill_utils.sys") as mock_sys,- ):+ # Host-native: a skill tagged only for a platform that is never the+ # host is hidden; untagged and host-including skills are listed.+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path):_make_skill(tmp_path, "universal-skill")- _make_skill(tmp_path, "mac-only", frontmatter_extra="platforms: [macos]\n")-- mock_sys.platform = "linux"- linux = {s["name"] for s in _find_all_skills()}- mock_sys.platform = "darwin"- darwin = {s["name"] for s in _find_all_skills()}- mock_sys.platform = "win32"- win = {s["name"] for s in _find_all_skills()}-- assert linux == {"universal-skill"}- assert darwin == {"universal-skill", "mac-only"}- # Skills without a platforms field appear on every platform.- assert win == {"universal-skill"}-- def test_multi_platform_skill(self, tmp_path):- with (- patch("tools.skills_tool.SKILLS_DIR", tmp_path),- patch("agent.skill_utils.sys") as mock_sys,- ):+ _make_skill(tmp_path, "other-only", frontmatter_extra="platforms: [plan9]\n")_make_skill(- tmp_path, "cross-plat", frontmatter_extra="platforms: [macos, linux]\n"+ tmp_path, "cross-plat", frontmatter_extra=f"platforms: [plan9, {sys.platform}]\n")- mock_sys.platform = "darwin"- skills_darwin = _find_all_skills()- mock_sys.platform = "linux"- skills_linux = _find_all_skills()- mock_sys.platform = "win32"- skills_win = _find_all_skills()- assert len(skills_darwin) == 1- assert len(skills_linux) == 1- assert len(skills_win) == 0+ names = {s["name"] for s in _find_all_skills()}++ assert names == {"universal-skill", "cross-plat"}# ---------------------------------------------------------------------------diff --git a/tests/tools/test_slash_confirm.py b/tests/tools/test_slash_confirm.pyindex 6f0f5b49048..b0f31846fd0 100644--- a/tests/tools/test_slash_confirm.py+++ b/tests/tools/test_slash_confirm.py@@ -103,9 +103,6 @@ class TestClear:slash_confirm.clear("sess1")assert slash_confirm.get_pending("sess1") is None- def test_clear_missing_is_noop(self):- # Should not raise.- slash_confirm.clear("nobody")class TestClearIfStale:diff --git a/tests/tools/test_smart_approval_policy.py b/tests/tools/test_smart_approval_policy.pyindex cf3fef7115d..0ffdf7b640a 100644--- a/tests/tools/test_smart_approval_policy.py+++ b/tests/tools/test_smart_approval_policy.py@@ -110,24 +110,6 @@ class TestSmartApprovePolicyInjection(unittest.TestCase):assert _smart_approve("echo hi", "flagged") == "escalate"- @patch("agent.auxiliary_client._get_task_timeout")- @patch("tools.approval_context._get_approval_config")- @patch("agent.auxiliary_client.call_llm")- def test_smart_approve_passes_explicit_timeout(- self, mock_call_llm, mock_cfg, mock_task_timeout- ):- """Regression for #82846: the guardian call must pass an explicit- timeout instead of relying on the default resolution inside call_llm- (a defeated internal timeout silently froze agent turns in- production). The explicit value must equal what- auxiliary.approval.timeout resolves to."""- mock_call_llm.return_value = _make_response("APPROVE")- mock_cfg.return_value = {"mode": "smart"}- mock_task_timeout.return_value = 42.0-- assert _smart_approve("echo hi", "flagged") == "approve"- _, kwargs = mock_call_llm.call_args- assert kwargs.get("timeout") == 42.0@patch("tools.approval_context._get_approval_config")diff --git a/tests/tools/test_snapshot_session_id_leak.py b/tests/tools/test_snapshot_session_id_leak.pyindex 7c94ca9466a..ada8a5a75fb 100644--- a/tests/tools/test_snapshot_session_id_leak.py+++ b/tests/tools/test_snapshot_session_id_leak.py@@ -46,27 +46,6 @@ def test_regex_matches_bridged_session_vars():assert rx.search(line), f"{name} should be excluded from the snapshot"-def test_export_snippet_shape():- snippet = _export_dump_excluding_session_vars('"$__hermes_snap_tmp"')- assert "export -p" in snippet- # Unset-by-name (not line-grep): multi-line declare values must not leave- # continuation lines in the snapshot (issue #71296).- assert "unset" in snippet- assert "${!HERMES_SESSION_*}" in snippet- assert "${!HERMES_CRON_AUTO_DELIVER_*}" in snippet- assert "${!HERMES_BROWSER_CONTROL_*}" in snippet- assert "HERMES_UI_SESSION_ID" in snippet- assert "grep -vE" not in snippet- assert '"$__hermes_snap_tmp"' in snippet- # The redirection must be attached to a brace group wrapping the dump,- # NOT to a pipeline segment: a redirect on a pipeline segment expands the- # temp-path variable inside that segment's subshell (potentially- # inconsistently with the parent that expands the follow-up ``mv``- # operand), silently orphaning the dump and breaking snapshot env- # persistence entirely.- assert snippet.lstrip().startswith("{ ")- assert "|| true; }" in snippet- assert snippet.rstrip().endswith('> "$__hermes_snap_tmp"')# ---------------------------------------------------------------------------diff --git a/tests/tools/test_ssh_bulk_upload.py b/tests/tools/test_ssh_bulk_upload.pyindex bf41a2fb6e6..7eb030f188a 100644--- a/tests/tools/test_ssh_bulk_upload.py+++ b/tests/tools/test_ssh_bulk_upload.py@@ -7,7 +7,6 @@ from unittest.mock import MagicMock, patchimport pytestfrom tools.environments import ssh as ssh_env-from tools.environments.file_sync import quoted_mkdir_command, unique_parent_dirsfrom tools.environments.ssh import SSHEnvironment@@ -195,46 +194,8 @@ class TestSSHBulkUpload:mock_ssh.kill.assert_called_once()-class TestSSHBulkUploadWiring:- """Verify bulk_upload_fn is wired into FileSyncManager."""- def test_filesyncmanager_receives_bulk_upload_fn(self, monkeypatch):- """SSHEnvironment should pass _ssh_bulk_upload to FileSyncManager."""- monkeypatch.setattr(ssh_env.shutil, "which", lambda _name: "/usr/bin/ssh")- monkeypatch.setattr(ssh_env.SSHEnvironment, "_establish_connection", lambda self: None)- monkeypatch.setattr(ssh_env.SSHEnvironment, "_detect_remote_home", lambda self: "/root")- monkeypatch.setattr(ssh_env.SSHEnvironment, "_ensure_remote_dirs", lambda self: None)- monkeypatch.setattr(ssh_env.SSHEnvironment, "init_session", lambda self: None)- captured_kwargs = {}-- class FakeSyncManager:- def __init__(self, **kwargs):- captured_kwargs.update(kwargs)-- def sync(self, **kw):- pass-- monkeypatch.setattr(ssh_env, "FileSyncManager", FakeSyncManager)-- env = SSHEnvironment(host="h", user="u")-- assert "bulk_upload_fn" in captured_kwargs- assert captured_kwargs["bulk_upload_fn"] is not None- # Should be the bound method- assert callable(captured_kwargs["bulk_upload_fn"])---class TestSharedHelpers:- """Direct unit tests for file_sync.py helpers."""-- def test_quoted_mkdir_command_basic(self):- result = quoted_mkdir_command(["/a", "/b/c"])- assert result == "mkdir -p /a /b/c"--- def test_unique_parent_dirs_empty(self):- assert unique_parent_dirs([]) == []class TestSSHBulkUploadEdgeCases:diff --git a/tests/tools/test_ssh_environment.py b/tests/tools/test_ssh_environment.pyindex 44c687992f4..30dae4ff27d 100644--- a/tests/tools/test_ssh_environment.py+++ b/tests/tools/test_ssh_environment.py@@ -188,12 +188,6 @@ class TestControlSocketPath:class TestTerminalToolConfig:- def test_ssh_persistent_default_true(self, monkeypatch):- """SSH persistent defaults to True (via TERMINAL_PERSISTENT_SHELL)."""- monkeypatch.delenv("TERMINAL_SSH_PERSISTENT", raising=False)- monkeypatch.delenv("TERMINAL_PERSISTENT_SHELL", raising=False)- from tools.terminal_tool import _get_env_config- assert _get_env_config()["ssh_persistent"] is Truedef test_ssh_persistent_respects_config(self, monkeypatch):diff --git a/tests/tools/test_stage2_hook_symlink_chown.py b/tests/tools/test_stage2_hook_symlink_chown.pyindex fd68d78def7..6bd0f43e0f5 100644--- a/tests/tools/test_stage2_hook_symlink_chown.py+++ b/tests/tools/test_stage2_hook_symlink_chown.py@@ -1,7 +1,6 @@"""Regression tests for symlink-safe Docker stage2 ownership repair."""from __future__ import annotations-import reimport shutilimport subprocessfrom pathlib import Path@@ -101,28 +100,7 @@ def test_chown_helper_refuses_target_under_symlinked_home(assert "refusing recursive chown through symlinked path" in proc.stdout-def test_stage2_uses_symlink_safe_helper_for_hermes_home_trees(stage2_text: str) -> None:- assert 'chown_hermes_tree "$HERMES_HOME/$sub"' in stage2_text- assert 'chown_hermes_tree "$HERMES_HOME/profiles"' in stage2_text- assert 'chown_hermes_tree "$HERMES_HOME/cron"' in stage2_text- assert 'chown -R hermes:hermes "$HERMES_HOME/$sub"' not in stage2_text- assert 'chown -R hermes:hermes "$HERMES_HOME/profiles"' not in stage2_text- assert 'chown -R hermes:hermes "$HERMES_HOME/cron"' not in stage2_text-def test_stage2_skips_top_level_chown_for_symlinked_hermes_home(- stage2_text: str,-) -> None:- assert 'refuse_symlinked_path "chown" "$HERMES_HOME"' in stage2_text-def test_stage2_skips_recursive_repairs_when_tree_is_already_owned(- stage2_text: str,-) -> None:- assert "tree_has_non_hermes_owner() {" in stage2_text- assert 'if [ -e "$HERMES_HOME/$sub" ] && tree_has_non_hermes_owner "$HERMES_HOME/$sub"; then' in stage2_text- assert 'if [ -d "$HERMES_HOME/profiles" ] && tree_has_non_hermes_owner "$HERMES_HOME/profiles"; then' in stage2_text- # Sibling every-boot chown blocks carry the same warm-boot gate.- assert 'if [ -d "$HERMES_HOME/cron" ] && tree_has_non_hermes_owner "$HERMES_HOME/cron"; then' in stage2_text- assert 'if [ -d "$HERMES_HOME/platforms/pairing" ] && tree_has_non_hermes_owner "$HERMES_HOME/platforms/pairing"; then' in stage2_text- assert 'if [ -d "$HERMES_HOME/pairing" ] && tree_has_non_hermes_owner "$HERMES_HOME/pairing"; then' in stage2_textdiff --git a/tests/tools/test_startup_latency_regressions.py b/tests/tools/test_startup_latency_regressions.pyindex 9a793ed2179..e1d0400d793 100644--- a/tests/tools/test_startup_latency_regressions.py+++ b/tests/tools/test_startup_latency_regressions.py@@ -87,20 +87,7 @@ class TestAuxProbeMode:t.join()assert seen["active"] is False- def test_maybe_wrap_anthropic_passes_stub_through(self):- import agent.auxiliary_client as aux-- stub = aux._AuxProbeClientStub(base_url="https://api.anthropic.com")- out = aux._maybe_wrap_anthropic(stub, "m", "key", "https://api.anthropic.com")- assert out is stub-- def test_to_async_client_passes_stub_through(self):- import agent.auxiliary_client as aux- stub = aux._AuxProbeClientStub()- client, model = aux._to_async_client(stub, "m")- assert client is stub- assert model == "m"class TestVisionCheckUsesProbeMode:@@ -137,28 +124,8 @@ class TestLazyMcpSdk:assert proc.returncode == 0, proc.stderrassert "ok" in proc.stdout- def test_availability_flag_reflects_find_spec(self):- import importlib.util- from tools import mcp_tool-- expected = importlib.util.find_spec("mcp") is not None- assert mcp_tool._MCP_AVAILABLE is expected-- def test_ensure_mcp_sdk_binds_symbols(self):- import importlib.util- from tools import mcp_tool-- if importlib.util.find_spec("mcp") is None:- pytest.skip("mcp SDK not installed")- assert mcp_tool._ensure_mcp_sdk() is True- assert mcp_tool.ClientSession is not None- assert mcp_tool.stdio_client is not None- def test_ensure_respects_patched_unavailable(self):- from tools import mcp_tool- with patch.object(mcp_tool, "_MCP_AVAILABLE", False):- assert mcp_tool._ensure_mcp_sdk() is Falsedef test_lazy_symbol_getattr_resolves_via_ensure(self):import importlib.util@@ -211,20 +178,3 @@ class TestBannerUpdateCheckNonBlocking:assert "3 commits behind" in visibleassert "\x1b" not in visible and "[bold" not in visible- def test_deferred_notice_silent_when_up_to_date(self):- import hermes_cli.banner as banner-- printed = []-- def _fake_cprint(text):- printed.append(text)-- done = threading.Event()- with patch.object(banner, "_update_check_done", done), \- patch.object(banner, "_update_result", 0), \- patch.object(banner, "_deferred_update_notice_started", False), \- patch.object(banner, "cprint", _fake_cprint):- banner._defer_update_notice(max_wait=2.0)- done.set()- time.sleep(0.3)- assert not printeddiff --git a/tests/tools/test_stt_cloud_trim.py b/tests/tools/test_stt_cloud_trim.pyindex f93832d1168..d9c2302d9cc 100644--- a/tests/tools/test_stt_cloud_trim.py+++ b/tests/tools/test_stt_cloud_trim.py@@ -85,9 +85,6 @@ def _write_wav(path: Path, segments) -> str:class TestProviderGating:- def test_cloud_set_excludes_local_providers(self):- assert "local" not in CLOUD_STT_PROVIDERS- assert "local_command" not in CLOUD_STT_PROVIDERSdef test_cloud_set_covers_every_remote_builtin(self):# Invariant: every built-in that is not local-ish uploads audio and@@ -309,8 +306,3 @@ class TestTrimE2E:assert _trim_silence_for_cloud_stt(wav, {}) is Nonemock_encode.assert_not_called()- def test_disabled_config_uploads_original(self, tmp_path):- wav = _write_wav(- tmp_path / "pauses.wav", [("tone", 2), ("silence", 6), ("tone", 2)]- )- assert _trim_silence_for_cloud_stt(wav, {"cloud_trim_silence": False}) is Nonediff --git a/tests/tools/test_stt_default_language.py b/tests/tools/test_stt_default_language.pydeleted file mode 100644index 92787848c83..00000000000--- a/tests/tools/test_stt_default_language.py+++ /dev/null@@ -1,22 +0,0 @@-"""Default STT language contract.--Teknium (July 2026): the global ``stt.language`` DEFAULTS to "en" because-Whisper auto-detection frequently misidentifies short/accented clips-("STT transcribed the wrong language" class). Users opt back into-auto-detect with ``stt.language: ""``.-"""--from hermes_cli.config import DEFAULT_CONFIG-from tools.transcription_tools import _resolve_stt_language---class TestDefaultSttLanguage:- def test_default_config_pins_english(self):- assert DEFAULT_CONFIG["stt"]["language"] == "en"--- def test_per_provider_still_wins_over_default(self, monkeypatch):- monkeypatch.delenv("HERMES_LOCAL_STT_LANGUAGE", raising=False)- stt = dict(DEFAULT_CONFIG["stt"])- stt["groq"] = {"language": "he"}- assert _resolve_stt_language("groq", stt) == "he"diff --git a/tests/tools/test_stt_idle_unload.py b/tests/tools/test_stt_idle_unload.pyindex d98110ddb9b..827d057b1fb 100644--- a/tests/tools/test_stt_idle_unload.py+++ b/tests/tools/test_stt_idle_unload.py@@ -28,14 +28,11 @@ import timeimport wavefrom unittest.mock import MagicMock, patch-import pytestfrom tools.transcription_tools import (_get_idle_unload_seconds,- _touch_transcription_time,_unload_local_model,_start_idle_unload_watcher,- _IDLE_UNLOAD_CHECK_INTERVAL,)import tools.transcription_tools as tt@@ -52,8 +49,6 @@ class TestGetIdleUnloadSeconds:def test_explicit_value(self):assert _get_idle_unload_seconds({"unload_after_idle_seconds": 300}) == 300- def test_zero_means_never(self):- assert _get_idle_unload_seconds({"unload_after_idle_seconds": 0}) == 0def test_negative_clamped_to_zero(self):assert _get_idle_unload_seconds({"unload_after_idle_seconds": -5}) == 0@@ -61,8 +56,6 @@ class TestGetIdleUnloadSeconds:def test_garbage_falls_back_to_zero(self):assert _get_idle_unload_seconds({"unload_after_idle_seconds": "never"}) == 0- def test_none_falls_back_to_zero(self):- assert _get_idle_unload_seconds({"unload_after_idle_seconds": None}) == 0# ============================================================================@@ -86,16 +79,6 @@ class TestUnloadLocalModel:_unload_local_model()assert tt._local_model is None- def test_acquires_model_lock(self):- """The unload must hold _local_model_lock to prevent races with- concurrent transcriptions that are mid-load."""- mock_model = MagicMock(name="whisper_model")- with patch.object(tt, "_local_model", mock_model), \- patch.object(tt, "_local_model_name", "base"), \- patch.object(tt, "_local_model_lock") as mock_lock:- _unload_local_model()- mock_lock.__enter__.assert_called()- mock_lock.__exit__.assert_called()# ============================================================================@@ -103,15 +86,6 @@ class TestUnloadLocalModel:# ============================================================================-class TestTouchTranscriptionTime:- def test_sets_timestamp(self):- original = tt._last_transcription_time- try:- tt._last_transcription_time = 0.0- _touch_transcription_time()- assert tt._last_transcription_time > 0- finally:- tt._last_transcription_time = original# ============================================================================@@ -120,15 +94,6 @@ class TestTouchTranscriptionTime:class TestIdleUnloadWatcher:- def test_default_zero_does_not_start_thread(self):- """When unload_after_idle_seconds is 0, no watcher should be started."""- with patch.object(tt, "_local_model", MagicMock()), \- patch.object(tt, "_start_idle_unload_watcher") as mock_start:- # Simulate _transcribe_local's behavior: only start if > 0- idle_timeout = _get_idle_unload_seconds({"unload_after_idle_seconds": 0})- if idle_timeout > 0:- _start_idle_unload_watcher(idle_timeout)- mock_start.assert_not_called()def test_watcher_unloads_after_timeout(self):"""The watcher unloads the model after the configured idle period."""@@ -174,13 +139,6 @@ class TestIdleUnloadWatcher:tt._IDLE_UNLOAD_CHECK_INTERVAL = original_intervaltt._last_transcription_time = original_ts- def test_watcher_exits_when_model_already_none(self):- """If the model was unloaded by another path, the watcher exits."""- with patch.object(tt, "_local_model", None), \- patch.object(tt, "_IDLE_UNLOAD_CHECK_INTERVAL", 0.01), \- patch.object(tt, "_last_transcription_time", 0.0):- _start_idle_unload_watcher(timeout_seconds=1)- time.sleep(0.05)# No crash, no hang — watcher detected _local_model is None and exiteddef test_start_is_idempotent_while_watcher_alive(self):diff --git a/tests/tools/test_subagent_worktree.py b/tests/tools/test_subagent_worktree.pyindex 571c5f374a5..ec49de14c75 100644--- a/tests/tools/test_subagent_worktree.py+++ b/tests/tools/test_subagent_worktree.py@@ -239,13 +239,9 @@ class SubagentWorktreeTests(unittest.TestCase):branches = _git(["branch", "--list", info["branch"]], repo).stdoutself.assertNotEqual(branches.strip(), "")- def test_finalize_note_disclaims_only_the_unmeasured_field(self):- """A partial failure must not claim a MEASURED value is unknown.-- A bad base_commit fails `rev-list` while `status` still succeeds, so- ``dirty`` is a real measurement — the note should disclaim ``commits``- only, or it misreports in the other direction.- """+ def test_finalize_partial_inspection_failure_keeps_measured_dirty(self):+ """A bad base_commit fails `rev-list` while `status` still succeeds:+ ``dirty`` stays a real measurement and the worktree is kept."""repo = _make_repo(self.tmp)info = sw.create_subagent_worktree(str(repo), "partial")assert info is not None@@ -260,10 +256,6 @@ class SubagentWorktreeTests(unittest.TestCase):self.assertTrue(payload["dirty"])self.assertTrue(payload["inspection_failed"])self.assertFalse(payload["pruned"])- # The note names ONLY the unmeasured field.- self.assertIn("commits UNKNOWN", payload["note"])- self.assertNotIn("dirty UNKNOWN", payload["note"])- self.assertNotIn("commits/dirty", payload["note"])self.assertTrue((wt / "UNTRACKED.txt").exists())def test_finalize_keeps_worktree_when_base_commit_missing(self):@@ -299,19 +291,7 @@ class SubagentWorktreeTests(unittest.TestCase):# ── local_backend_active ───────────────────────────────────────────- def test_local_backend_active_local(self):- with mock.patch(- "hermes_cli.config.load_config_readonly",- return_value={"terminal": {"backend": "local"}},- ):- self.assertTrue(sw.local_backend_active())- def test_local_backend_active_docker(self):- with mock.patch(- "hermes_cli.config.load_config_readonly",- return_value={"terminal": {"backend": "docker"}},- ):- self.assertFalse(sw.local_backend_active())# ── context note ───────────────────────────────────────────────────@@ -321,7 +301,6 @@ class SubagentWorktreeTests(unittest.TestCase):)self.assertIn("/x/wt", note)self.assertIn("hermes-subagent/subagent-1", note)- self.assertIn("WORKTREE ISOLATION", note)class WorktreePayloadSchemaTests(unittest.TestCase):@@ -359,49 +338,8 @@ class WorktreePayloadSchemaTests(unittest.TestCase):self.assertIn(info["path"], unproven["note"])self.assertIn(info["branch"], unproven["note"])- def test_delegate_tool_fallback_uses_the_shared_factory(self):- """delegate_tool's fallback must emit the flagged schema, not the- creation-side metadata dict it used to leak."""- from tools import delegate_tool # noqa: F401 (import-safety check)-- repo = _make_repo(self.tmp)- info = sw.create_subagent_worktree(str(repo), "fallback")- assert info is not None-- # Drive the real helper the fallback calls.- payload = sw.unproven_worktree_payload(info, "finalize raised: boom")- self.assertEqual(- set(payload),- {- "path",- "branch",- "commits",- "dirty",- "pruned",- "inspection_failed",- "note",- },- )- self.assertFalse(payload["pruned"])- self.assertEqual(payload["commits"], 0)- self.assertFalse(payload["dirty"])---class DelegationConfigGateTests(unittest.TestCase):- def test_worktree_isolation_default_off(self):- from tools import delegate_tool-- with mock.patch.object(delegate_tool, "_load_config", return_value={}):- self.assertFalse(delegate_tool._get_worktree_isolation())- def test_worktree_isolation_enabled(self):- from tools import delegate_tool- with mock.patch.object(- delegate_tool, "_load_config",- return_value={"worktree_isolation": True},- ):- self.assertTrue(delegate_tool._get_worktree_isolation())if __name__ == "__main__":diff --git a/tests/tools/test_subprocess_home_isolation.py b/tests/tools/test_subprocess_home_isolation.pyindex 09eb6a79149..47ae0854a26 100644--- a/tests/tools/test_subprocess_home_isolation.py+++ b/tests/tools/test_subprocess_home_isolation.py@@ -10,8 +10,6 @@ See: https://github.com/NousResearch/hermes-agent/issues/36144See: https://github.com/NousResearch/hermes-agent/issues/29015"""-import os-import threadingfrom pathlib import Pathimport hermes_constants@@ -268,9 +266,6 @@ class TestSanitizeSubprocessEnvHomeInjection:class TestProfileBootstrap:"""Verify new profiles get a home/ subdirectory."""- def test_profile_dirs_includes_home(self):- from hermes_cli.profiles import _PROFILE_DIRS- assert "home" in _PROFILE_DIRSdef test_create_profile_bootstraps_home_dir(self, tmp_path, monkeypatch):"""create_profile() should create home/ inside the profile dir."""diff --git a/tests/tools/test_subprocess_stdin_guard.py b/tests/tools/test_subprocess_stdin_guard.pyindex 15f7482e5d0..c2b070e688c 100644--- a/tests/tools/test_subprocess_stdin_guard.py+++ b/tests/tools/test_subprocess_stdin_guard.py@@ -35,37 +35,6 @@ def test_all_tui_subprocess_calls_have_stdin():)-def test_oauth_setup_token_keeps_inherited_stdin():- """The interactive 'claude setup-token' login must NOT be muzzled.-- Forcing stdin=subprocess.DEVNULL here would feed the OAuth prompt EOF and- break interactive token setup. A blanket DEVNULL sweep over TUI-context- subprocess calls must leave this one inheriting stdin. Regression guard for- the over-application caught while salvaging the stdin-EOF fix.-- The call's owner moved from agent/anthropic_adapter.py into- agent/anthropic_credentials.py in the adapter godfile split; the guard- scans both seams so a future move fails loudly instead of going dark.- """- candidates = [- REPO_ROOT / "agent" / "anthropic_credentials.py",- REPO_ROOT / "agent" / "anthropic_adapter.py",- ]- sources = [p.read_text() for p in candidates if p.exists()]- owners = [- src for src in sources- if 'subprocess.run([claude_path, "setup-token"])' in src- ]- assert owners, (- "interactive setup-token call changed shape or moved; re-verify it "- "still inherits stdin (no stdin=subprocess.DEVNULL) and update this "- "guard's candidate list"- )- for src in sources:- assert 'subprocess.run([claude_path, "setup-token"], stdin' not in src, (- "setup-token must inherit stdin so the user can complete the OAuth "- "login prompt; do not add stdin=subprocess.DEVNULL"- )def test_inline_noqa_marker_exempts_a_call():diff --git a/tests/tools/test_subprocess_utf8_encoding.py b/tests/tools/test_subprocess_utf8_encoding.pydeleted file mode 100644index 72e2f8c52e3..00000000000--- a/tests/tools/test_subprocess_utf8_encoding.py+++ /dev/null@@ -1,68 +0,0 @@-"""Regression test for issue #53428 — subprocess.run(text=True) without-explicit ``encoding=`` triggers ``UnicodeDecodeError`` on Chinese Windows-(cp936/GBK default encoding).--PR #55339 covers 21 call sites in ``agent/``, ``gateway/``, ``cli.py``,-``cron/``, plus 5 more in ``tools/`` and ``hermes_cli/`` (main.py,-setup.py, tts_tool.py, transcription_tools.py). The two call sites it-misses — ``hermes_cli/onepassword_secrets_cli.py::_op_whoami`` and-``_op_version`` — are guarded here.--Without ``encoding=``, ``text=True`` decodes child output with-``locale.getpreferredencoding(False)`` — cp936 on Chinese Windows —-which crashes on non-GBK bytes (issues #47939, #53428, #57238).-"""--from __future__ import annotations--from pathlib import Path-from unittest.mock import patch, MagicMock---def _assert_utf8_kwargs(mock_run):- """Lift the encoding/errors kwargs out of the mock and assert them."""- assert mock_run.called, "subprocess.run was not called"- kwargs = mock_run.call_args.kwargs- assert kwargs.get("encoding") == "utf-8", (- f"subprocess.run called without encoding='utf-8' "- f"(got encoding={kwargs.get('encoding')!r}). "- f"On Chinese Windows (cp936), text=True without explicit encoding "- f"crashes with UnicodeDecodeError on non-GBK bytes. See #53428."- )- assert kwargs.get("errors") == "replace", (- f"subprocess.run called without errors='replace' "- f"(got errors={kwargs.get('errors')!r}). encoding='utf-8' alone "- f"still raises UnicodeDecodeError on non-UTF-8 bytes emitted by "- f"Windows-native CLIs. See #53428."- )---def test_op_whoami_passes_utf8_encoding(tmp_path):- """_op_whoami must pass encoding='utf-8', errors='replace' so op CLI- output containing non-ASCII account names doesn't crash on cp936."""- from hermes_cli import onepassword_secrets_cli as op_cli-- fake_binary = tmp_path / "op"- fake_binary.write_bytes(b"")- with patch.object(op_cli.subprocess, "run") as mock_run:- mock_run.return_value = MagicMock(- returncode=0, stdout="[email protected]", stderr=""- )- op_cli._op_whoami(fake_binary, account="")- _assert_utf8_kwargs(mock_run)---def test_op_version_passes_utf8_encoding(tmp_path):- """_op_version must pass encoding='utf-8', errors='replace' so op CLI- output containing non-ASCII bytes doesn't crash on cp936. Pairs with- _op_whoami — both run in the same setup/status CLI flow."""- from hermes_cli import onepassword_secrets_cli as op_cli-- fake_binary = tmp_path / "op"- fake_binary.write_bytes(b"")- with patch.object(op_cli.subprocess, "run") as mock_run:- mock_run.return_value = MagicMock(- returncode=0, stdout="2.24.0", stderr=""- )- op_cli._op_version(fake_binary)- _assert_utf8_kwargs(mock_run)diff --git a/tests/tools/test_symlink_prefix_confusion.py b/tests/tools/test_symlink_prefix_confusion.pydeleted file mode 100644index 80789129723..00000000000--- a/tests/tools/test_symlink_prefix_confusion.py+++ /dev/null@@ -1,144 +0,0 @@-"""Tests for the symlink boundary check prefix confusion fix in skills_guard.py.--Regression test: the original check used startswith() without a trailing-separator, so a symlink resolving to 'axolotl-backdoor/' passed the check-for 'axolotl/' because the string prefix matched. Now uses-Path.is_relative_to() which handles directory boundaries correctly.-"""--import pytest-from pathlib import Path---def _old_check_escapes(resolved: Path, skill_dir_resolved: Path) -> bool:- """The BROKEN check that used startswith without separator.-- Returns True when the path is OUTSIDE the skill directory.- """- return (- not str(resolved).startswith(str(skill_dir_resolved))- and resolved != skill_dir_resolved- )---def _new_check_escapes(resolved: Path, skill_dir_resolved: Path) -> bool:- """The FIXED check using is_relative_to().-- Returns True when the path is OUTSIDE the skill directory.- """- return not resolved.is_relative_to(skill_dir_resolved)---class TestPrefixConfusionRegression:- """The core bug: startswith() can't distinguish directory boundaries."""-- def test_old_check_misses_sibling_with_shared_prefix(self, tmp_path):- """Old startswith check fails on sibling dirs that share a prefix."""- skill_dir = tmp_path / "skills" / "axolotl"- sibling_file = tmp_path / "skills" / "axolotl-backdoor" / "evil.py"- skill_dir.mkdir(parents=True)- sibling_file.parent.mkdir(parents=True)- sibling_file.write_text("evil")-- resolved = sibling_file.resolve()- skill_dir_resolved = skill_dir.resolve()-- # Bug: old check says the file is INSIDE the skill dir- assert _old_check_escapes(resolved, skill_dir_resolved) is False--- def test_both_agree_on_completely_outside_path(self, tmp_path):- """Both checks block a path that's completely outside."""- skill_dir = tmp_path / "skills" / "axolotl"- outside_file = tmp_path / "etc" / "passwd"- skill_dir.mkdir(parents=True)- outside_file.parent.mkdir(parents=True)- outside_file.write_text("root:x:0:0")-- resolved = outside_file.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _old_check_escapes(resolved, skill_dir_resolved) is True- assert _new_check_escapes(resolved, skill_dir_resolved) is True-- def test_skill_dir_itself_allowed(self, tmp_path):- """Requesting the skill directory itself is fine."""- skill_dir = tmp_path / "skills" / "axolotl"- skill_dir.mkdir(parents=True)-- resolved = skill_dir.resolve()- skill_dir_resolved = skill_dir.resolve()-- # Both should allow the dir itself- assert _old_check_escapes(resolved, skill_dir_resolved) is False- assert _new_check_escapes(resolved, skill_dir_resolved) is False---def _can_symlink():- """Check if we can create symlinks (needs admin/dev-mode on Windows)."""- import tempfile- try:- with tempfile.TemporaryDirectory() as d:- src = Path(d) / "src"- src.write_text("x")- lnk = Path(d) / "lnk"- lnk.symlink_to(src)- return True- except OSError:- return False--[email protected](not _can_symlink(), reason="Symlinks need elevated privileges")-class TestSymlinkEscapeWithActualSymlinks:- """Test the full symlink scenario with real filesystem symlinks."""-- def test_symlink_to_sibling_prefix_dir_detected(self, tmp_path):- """A symlink from axolotl/ to axolotl-backdoor/ must be caught."""- skills = tmp_path / "skills"- skill_dir = skills / "axolotl"- sibling_dir = skills / "axolotl-backdoor"- skill_dir.mkdir(parents=True)- sibling_dir.mkdir(parents=True)-- malicious = sibling_dir / "malicious.py"- malicious.write_text("evil code")-- link = skill_dir / "helper.py"- link.symlink_to(malicious)-- resolved = link.resolve()- skill_dir_resolved = skill_dir.resolve()-- # Old check would miss this (prefix confusion)- assert _old_check_escapes(resolved, skill_dir_resolved) is False- # New check catches it- assert _new_check_escapes(resolved, skill_dir_resolved) is True-- def test_symlink_within_skill_dir_allowed(self, tmp_path):- """A symlink that stays within the skill directory is fine."""- skill_dir = tmp_path / "my-skill"- skill_dir.mkdir()- real_file = skill_dir / "real.py"- real_file.write_text("print('ok')")- link = skill_dir / "alias.py"- link.symlink_to(real_file)-- resolved = link.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _new_check_escapes(resolved, skill_dir_resolved) is False-- def test_symlink_to_parent_dir_blocked(self, tmp_path):- """A symlink pointing outside (to parent) is blocked."""- skill_dir = tmp_path / "skill"- skill_dir.mkdir()- outside = tmp_path / "secret.env"- outside.write_text("SECRET=123")-- link = skill_dir / "config.env"- link.symlink_to(outside)-- resolved = link.resolve()- skill_dir_resolved = skill_dir.resolve()-- assert _new_check_escapes(resolved, skill_dir_resolved) is Truediff --git a/tests/tools/test_sync_back_backends.py b/tests/tools/test_sync_back_backends.pyindex c99c1c7e708..f8a60e06bfc 100644--- a/tests/tools/test_sync_back_backends.py+++ b/tests/tools/test_sync_back_backends.py@@ -121,15 +121,6 @@ class TestSSHBulkDownload:assert "[email protected]" in cmd_str- def test_ssh_bulk_download_uses_120s_timeout(self, ssh_mock_env, tmp_path):- """The subprocess.run call should use a 120s timeout."""- dest = tmp_path / "backup.tar"-- with patch.object(subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as mock_run:- ssh_mock_env._ssh_bulk_download(dest)-- call_kwargs = mock_run.call_args- assert call_kwargs.kwargs.get("timeout") == 120 or call_kwargs[1].get("timeout") == 120def test_ssh_bulk_download_tolerates_only_socket_ignored_exit_2(self, ssh_mock_env, tmp_path):"""Live sockets are excluded up front, and an rc=2 whose stderr is solely@@ -164,35 +155,6 @@ class TestSSHBulkDownload:class TestSSHCleanup:"""Verify SSH cleanup() calls sync_back() before closing ControlMaster."""- def test_ssh_cleanup_calls_sync_back(self, monkeypatch):- """cleanup() should call sync_back() before SSH control socket teardown."""- monkeypatch.setattr(ssh_env.shutil, "which", lambda _name: "/usr/bin/ssh")- monkeypatch.setattr(ssh_env.SSHEnvironment, "_establish_connection", lambda self: None)- monkeypatch.setattr(ssh_env.SSHEnvironment, "_detect_remote_home", lambda self: "/home/u")- monkeypatch.setattr(ssh_env.SSHEnvironment, "_ensure_remote_dirs", lambda self: None)- monkeypatch.setattr(ssh_env.SSHEnvironment, "init_session", lambda self: None)-- call_order = []-- class TrackingSyncManager:- def __init__(self, **kwargs):- pass-- def sync(self, **kw):- pass-- def sync_back(self):- call_order.append("sync_back")-- monkeypatch.setattr(ssh_env, "FileSyncManager", TrackingSyncManager)-- env = SSHEnvironment(host="h", user="u")- # Ensure control_socket does not exist so cleanup skips the SSH exit call- env.control_socket = Path("/nonexistent/socket")-- env.cleanup()-- assert "sync_back" in call_orderdef test_ssh_cleanup_calls_sync_back_before_control_exit(self, monkeypatch):"""sync_back() must run before the ControlMaster exit command."""@@ -261,24 +223,6 @@ class TestModalBulkDownload:assert "--exclude='*.sock'" in args[2]- def test_modal_bulk_download_uses_120s_timeout(self, tmp_path):- """run_coroutine should be called with timeout=120."""- env = _make_mock_modal_env()- _wire_modal_download(env, tar_bytes=b"data")-- run_kwargs = {}- original_run = env._worker.run_coroutine-- def tracking_run(coro, **kwargs):- run_kwargs.update(kwargs)- return original_run(coro, **kwargs)-- env._worker.run_coroutine = tracking_run- dest = tmp_path / "backup.tar"-- env._modal_bulk_download(dest)-- assert run_kwargs.get("timeout") == 120class TestModalCleanup:@@ -385,61 +329,3 @@ class TestDaytonaCleanup:# =====================================================================-class TestBulkDownloadWiring:- """Verify each backend passes bulk_download_fn to FileSyncManager."""-- def test_ssh_passes_bulk_download_fn(self, monkeypatch):- """SSHEnvironment should pass _ssh_bulk_download to FileSyncManager."""- monkeypatch.setattr(ssh_env.shutil, "which", lambda _name: "/usr/bin/ssh")- monkeypatch.setattr(ssh_env.SSHEnvironment, "_establish_connection", lambda self: None)- monkeypatch.setattr(ssh_env.SSHEnvironment, "_detect_remote_home", lambda self: "/root")- monkeypatch.setattr(ssh_env.SSHEnvironment, "_ensure_remote_dirs", lambda self: None)- monkeypatch.setattr(ssh_env.SSHEnvironment, "init_session", lambda self: None)-- captured_kwargs = {}-- class CaptureSyncManager:- def __init__(self, **kwargs):- captured_kwargs.update(kwargs)-- def sync(self, **kw):- pass-- monkeypatch.setattr(ssh_env, "FileSyncManager", CaptureSyncManager)-- SSHEnvironment(host="h", user="u")-- assert "bulk_download_fn" in captured_kwargs- assert callable(captured_kwargs["bulk_download_fn"])--- def test_daytona_passes_bulk_download_fn(self, monkeypatch):- """DaytonaEnvironment should pass _daytona_bulk_download to FileSyncManager."""- captured_kwargs = {}-- def capture_fsm(**kwargs):- captured_kwargs.update(kwargs)- return type("M", (), {"sync": lambda self, **k: None})()-- monkeypatch.setattr(daytona_env, "FileSyncManager", capture_fsm)-- env = object.__new__(daytona_env.DaytonaEnvironment)- env._sandbox = MagicMock()- env._remote_home = "/root"- env._lock = __import__("threading").Lock()- env._persistent = True- env._task_id = "test"- env._daytona = MagicMock()-- # Replicate the wiring done in __init__- from tools.environments.file_sync import iter_sync_files- env._sync_manager = daytona_env.FileSyncManager(- get_files_fn=lambda: iter_sync_files(f"{env._remote_home}/.hermes"),- upload_fn=env._daytona_upload,- delete_fn=env._daytona_delete,- bulk_upload_fn=env._daytona_bulk_upload,- bulk_download_fn=env._daytona_bulk_download,- )-- assert "bulk_download_fn" in captured_kwargs- assert callable(captured_kwargs["bulk_download_fn"])diff --git a/tests/tools/test_terminal_backend_unavailable_reason.py b/tests/tools/test_terminal_backend_unavailable_reason.pyindex 1353b185c2e..95ce8cae7f2 100644--- a/tests/tools/test_terminal_backend_unavailable_reason.py+++ b/tests/tools/test_terminal_backend_unavailable_reason.py@@ -30,12 +30,12 @@ def test_docker_daemon_probe_failure_captures_daemon_reason(monkeypatch):monkeypatch.setattr(backends.subprocess, "run",lambda *a, **k: subprocess.CompletedProcess(a[0], 1, b"", b""))assert backends._check_requirements("docker", {}) is False- assert "daemon is not running" in backends.terminal_backend_unavailable_reason()+ assert backends.terminal_backend_unavailable_reason()def test_ssh_unconfigured_captures_reason():assert backends._check_requirements("ssh", {"ssh_host": "", "ssh_user": ""}) is False- assert "SSH host and user are not configured" in backends.terminal_backend_unavailable_reason()+ assert backends.terminal_backend_unavailable_reason()def test_successful_check_clears_reason():diff --git a/tests/tools/test_terminal_compound_background.py b/tests/tools/test_terminal_compound_background.pyindex c0a1bb97b65..aac682e2721 100644--- a/tests/tools/test_terminal_compound_background.py+++ b/tests/tools/test_terminal_compound_background.py@@ -42,8 +42,6 @@ class TestPreserved:# No compound — just background a single command. Works fine as-is.assert rewrite("sleep 5 &") == "sleep 5 &"- def test_plain_server_background(self):- assert rewrite("python3 -m http.server 0 &") == "python3 -m http.server 0 &"def test_whitespace_only(self):@@ -152,9 +150,6 @@ class TestTrailingStatementSeparator:# command between `;` and `;;`, which bash rejects.assert rewrite("case $x in p) b && c & ;; esac") == "case $x in p) b && { c & } ;; esac"- def test_separator_is_idempotent(self):- once = rewrite("echo hi && sleep 5 & echo done")- assert rewrite(once) == oncedef test_second_background_then_trailing(self):assert rewrite("echo a && sleep 5 & echo b & echo c") == (diff --git a/tests/tools/test_terminal_config_env_sync.py b/tests/tools/test_terminal_config_env_sync.pyindex 021c8e46c58..59b6cbc9852 100644--- a/tests/tools/test_terminal_config_env_sync.py+++ b/tests/tools/test_terminal_config_env_sync.py@@ -27,30 +27,6 @@ import astimport inspect-def _extract_dict_values(source: str, dict_name: str) -> set[str]:- """Return the set of *value* strings in `dict_name = { "k": "VALUE", ... }`.-- We parse the source with ast (so multi-line dicts and comments are- handled) instead of regex. The first matching assignment wins.- """- tree = ast.parse(source)- for node in ast.walk(tree):- if not isinstance(node, ast.Assign):- continue- targets = [t for t in node.targets if isinstance(t, ast.Name)]- if not any(t.id == dict_name for t in targets):- continue- if not isinstance(node.value, ast.Dict):- continue- out: set[str] = set()- for k, v in zip(node.value.keys, node.value.values):- if isinstance(k, ast.Constant) and isinstance(v, ast.Constant):- if isinstance(v.value, str):- out.add(v.value)- return out- raise AssertionError(f"Could not find `{dict_name} = {{...}}` literal in source")--def _extract_dict_keys(source: str, dict_name: str) -> set[str]:"""Return the set of *key* strings in `dict_name = { "KEY": "v", ... }`."""tree = ast.parse(source)@@ -117,16 +93,6 @@ _CLI_ONLY_OK = frozenset({})-def _terminal_tool_env_var_names() -> set[str]:- """All TERMINAL_* env vars actually consumed by terminal_tool."""- import tools.terminal_tool as tt- source = inspect.getsource(tt)- # Naive scan: every os.getenv("TERMINAL_X", ...) and _parse_env_var("TERMINAL_X", ...).- import re- pat = re.compile(r'["\'](TERMINAL_[A-Z0-9_]+)["\']')- return set(pat.findall(source))--def test_cli_and_gateway_env_maps_agree():"""cli.py and gateway/run.py must bridge the same set of terminal keys.@@ -159,174 +125,16 @@ def test_cli_and_gateway_env_maps_agree():)-def test_save_config_set_supports_critical_bridged_keys():- """``hermes config set terminal.X true`` must propagate to .env for- known-critical keys. This used to be an all-keys invariant but the SSH- terminal keys (ssh_*) aren't in _config_to_env_sync and are instead- handled via the separate api_keys TERMINAL_SSH_* fallback path or- user-edits-yaml-directly.-- Until those gaps are audited and fixed, pin the specific keys that are- load-bearing for the docker backend so the bugs we fixed cannot silently- regress. (docker_volumes / docker_forward_env, previously listed here as- gaps, are now bridged — see the dedicated tests below.)+def test_save_config_set_bridges_every_cli_terminal_key():+ """``hermes config set terminal.X`` must propagate every key the CLI+ startup path bridges, so a config-set value takes effect without restart."""save_keys = _save_config_env_sync_keys()- required = {- "docker_run_as_host_user",- "docker_mount_cwd_to_workspace",- "backend",- "docker_image",- "container_cpu",- "container_memory",- "container_disk",- "container_persistent",- }- missing = required - save_keys+ # cwd is bridged separately by set_config_value; home_mode is CLI-only.+ exempt = _CLI_ONLY_OK | {"cwd", "home_mode"}+ missing = (_cli_env_map_keys() - exempt) - save_keysassert not missing, (- f"`hermes config set terminal.X` doesn't sync these load-bearing "- f"keys to .env: {sorted(missing)}. Add them to TERMINAL_CONFIG_ENV_MAP "- f"in hermes_cli/config.py (set_config_value bridges through it)."+ f"`hermes config set terminal.X` doesn't sync these keys to .env: "+ f"{sorted(missing)}. Add them to TERMINAL_CONFIG_ENV_MAP in "+ f"hermes_cli/config.py (set_config_value bridges through it).")---def test_docker_run_as_host_user_is_bridged_everywhere():- """Explicit pin for the bug we just fixed.-- docker_run_as_host_user was added to terminal_tool._get_env_config and- DockerEnvironment but NOT to cli.py's env_mappings or gateway/run.py's- _terminal_env_map, so ``terminal.docker_run_as_host_user: true`` in- config.yaml had no effect at runtime. This guard makes the regression- impossible to reintroduce silently.- """- assert "docker_run_as_host_user" in _cli_env_map_keys()- assert "docker_run_as_host_user" in _gateway_env_map_keys()- assert "docker_run_as_host_user" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_RUN_AS_HOST_USER" in _terminal_tool_env_var_names()---def test_docker_mount_cwd_to_workspace_is_bridged_everywhere():- """Same regression class — docker_mount_cwd_to_workspace was missing from- gateway/run.py's _terminal_env_map until the docker_run_as_host_user- audit caught it.- """- assert "docker_mount_cwd_to_workspace" in _cli_env_map_keys()- assert "docker_mount_cwd_to_workspace" in _gateway_env_map_keys()- assert "docker_mount_cwd_to_workspace" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE" in _terminal_tool_env_var_names()---def test_docker_env_is_bridged_everywhere():- """Regression pin for docker_env config key being silently ignored.-- ``terminal.docker_env`` in config.yaml specifies extra env vars to inject- into the Docker container at runtime. The key was present in- _create_environment's container_config consumer (line ~1130) but never- bridged from config.yaml to TERMINAL_DOCKER_ENV, so the dict was always- empty regardless of what the user set. Guard all four bridging points so- this cannot regress.- """- assert "docker_env" in _cli_env_map_keys()- assert "docker_env" in _gateway_env_map_keys()- assert "docker_env" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_ENV" in _terminal_tool_env_var_names()---def test_docker_extra_args_is_bridged_everywhere():- """Regression pin for docker_extra_args config key being silently ignored.-- ``terminal.docker_extra_args`` in config.yaml passes extra flags verbatim- to ``docker run`` (e.g. ``--gpus=all``, ``--shm-size=16g``). The key was- present in DEFAULT_CONFIG, TERMINAL_CONFIG_ENV_MAP (so ``hermes config- set`` bridged it), terminal_tool._get_env_config (reads- TERMINAL_DOCKER_EXTRA_ARGS), and DockerEnvironment (applies extra_args) --- but it was MISSING from cli.py's env_mappings and gateway/run.py's- _terminal_env_map. So a user who hand-edited config.yaml had their GPU /- shm-size flags silently dropped on the CLI and gateway/desktop paths,- while ``image``/``volumes`` (which were in those maps) bridged fine --- producing the "Hermes partially reads the Docker config" symptom. Guard- all four bridging points so this cannot regress.- """- assert "docker_extra_args" in _cli_env_map_keys()- assert "docker_extra_args" in _gateway_env_map_keys()- assert "docker_extra_args" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_EXTRA_ARGS" in _terminal_tool_env_var_names()---def test_docker_persist_across_processes_is_bridged_everywhere():- """Regression pin for the cross-process container reuse toggle.-- ``terminal.docker_persist_across_processes`` (issue #20561) controls- whether ``DockerEnvironment.__init__`` probes for and reuses an existing- labeled container at startup, and whether ``cleanup()`` removes the- container on Hermes exit or just stops it (keeping it for the next- process). Same four-bridge invariant as docker_run_as_host_user /- docker_env / docker_mount_cwd_to_workspace — drift between any of the- four sites means ``terminal.docker_persist_across_processes: false`` in- config.yaml silently does nothing for that entry point, leaving the- user unable to opt out of the documented "ONE long-lived container- shared across sessions" behavior.- """- assert "docker_persist_across_processes" in _cli_env_map_keys()- assert "docker_persist_across_processes" in _gateway_env_map_keys()- assert "docker_persist_across_processes" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES" in _terminal_tool_env_var_names()---def test_docker_orphan_reaper_is_bridged_everywhere():- """Regression pin for the startup orphan reaper toggle (issue #20561).-- ``terminal.docker_orphan_reaper`` controls whether Hermes sweeps stale- Exited containers from prior SIGKILL'd processes at startup. Same- four-site bridge invariant — drift means- ``terminal.docker_orphan_reaper: false`` silently does nothing for one- entry point, and the reaper either runs when the operator disabled it- or fails to run when they enabled it.- """- assert "docker_orphan_reaper" in _cli_env_map_keys()- assert "docker_orphan_reaper" in _gateway_env_map_keys()- assert "docker_orphan_reaper" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_ORPHAN_REAPER" in _terminal_tool_env_var_names()---def test_docker_volumes_is_bridged_everywhere():- """Regression pin for ``terminal.docker_volumes`` being silently dropped by- ``hermes config set``.-- The JSON list of ``host:container`` bind mounts was bridged by cli.py and- gateway/run.py and consumed by terminal_tool (via json.loads), but was- missing from set_config_value's _config_to_env_sync. So- ``hermes config set terminal.docker_volumes '["/host:/workspace"]'`` wrote- config.yaml yet left the running process's TERMINAL_DOCKER_VOLUMES stale —- the mounts didn't apply until a full restart. Same four-site bridge- invariant as docker_env / docker_run_as_host_user.- """- assert "docker_volumes" in _cli_env_map_keys()- assert "docker_volumes" in _gateway_env_map_keys()- assert "docker_volumes" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_VOLUMES" in _terminal_tool_env_var_names()---def test_docker_forward_env_is_bridged_everywhere():- """Regression pin for ``terminal.docker_forward_env`` — the sibling gap to- docker_volumes.-- The JSON list of host env-var names forwarded into the container was- bridged by cli.py and gateway/run.py and consumed by terminal_tool (via- json.loads), but missing from set_config_value's _config_to_env_sync, so- ``hermes config set terminal.docker_forward_env '["GITHUB_TOKEN"]'`` had no- effect on the running process until restart.- """- assert "docker_forward_env" in _cli_env_map_keys()- assert "docker_forward_env" in _gateway_env_map_keys()- assert "docker_forward_env" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_FORWARD_ENV" in _terminal_tool_env_var_names()---def test_docker_snap_compat_is_bridged_everywhere():- """#9730: ``terminal.docker_snap_compat`` must reach the container on the CLI, gateway and- ``hermes config set`` paths, like every other docker_* key (see docker_extra_args above)."""- assert "docker_snap_compat" in _cli_env_map_keys()- assert "docker_snap_compat" in _gateway_env_map_keys()- assert "docker_snap_compat" in _save_config_env_sync_keys()- assert "TERMINAL_DOCKER_SNAP_COMPAT" in _terminal_tool_env_var_names()diff --git a/tests/tools/test_terminal_degraded_mode.py b/tests/tools/test_terminal_degraded_mode.pyindex da872302d0b..2cff449698f 100644--- a/tests/tools/test_terminal_degraded_mode.py+++ b/tests/tools/test_terminal_degraded_mode.py@@ -14,7 +14,6 @@ docs-only evidence).import jsonimport subprocess-from unittest.mock import MagicMockimport pytest@@ -80,12 +79,6 @@ class TestExceptionClassification:with pytest.raises(EnvironmentConnectionError):SSHEnvironment(host="unreachable.invalid", user="nobody")- def test_docker_missing_executable_raises_connection_error(self, monkeypatch):- from tools.environments import docker as docker_env-- monkeypatch.setattr(docker_env, "find_docker", lambda: None)- with pytest.raises(EnvironmentConnectionError):- docker_env._ensure_docker_available()def test_docker_daemon_timeout_raises_connection_error(self, monkeypatch):from tools.environments import docker as docker_env@@ -99,12 +92,6 @@ class TestExceptionClassification:with pytest.raises(EnvironmentConnectionError):docker_env._ensure_docker_available()- def test_connection_error_is_a_runtime_error(self):- # Existing catchers of RuntimeError must keep working unchanged.- assert issubclass(EnvironmentConnectionError, RuntimeError)- err = EnvironmentConnectionError("boom")- assert err.reason == "boom"- assert err.retry_hint # non-empty default hintclass TestDegradedToolResult:@@ -201,23 +188,3 @@ class TestFailModePreservesRaiseBehavior:assert r["status"] == "degraded"-class TestConfigBridging:- def test_degraded_mode_is_bridged_everywhere(self):- """terminal.degraded_mode must ride every config->env bridge path,- same four-site invariant as the docker_* keys."""- from tests.tools.test_terminal_config_env_sync import (- _cli_env_map_keys,- _gateway_env_map_keys,- _save_config_env_sync_keys,- _terminal_tool_env_var_names,- )-- assert "degraded_mode" in _cli_env_map_keys()- assert "degraded_mode" in _gateway_env_map_keys()- assert "degraded_mode" in _save_config_env_sync_keys()- assert "TERMINAL_DEGRADED_MODE" in _terminal_tool_env_var_names()-- def test_default_config_carries_degraded_mode(self):- from hermes_cli.config_defaults import DEFAULT_CONFIG-- assert DEFAULT_CONFIG["terminal"].get("degraded_mode") == "warn"diff --git a/tests/tools/test_terminal_env_bridge.py b/tests/tools/test_terminal_env_bridge.pyindex 92c5a88f566..1d69f46d26e 100644--- a/tests/tools/test_terminal_env_bridge.py+++ b/tests/tools/test_terminal_env_bridge.py@@ -117,24 +117,6 @@ def test_defaults_backfill_when_neither_config_nor_env_selects_backend():assert os.environ["TERMINAL_ENV"] == "local"-def test_bridge_only_attempted_once(monkeypatch):- calls = []-- import hermes_cli.config as config_mod-- real = config_mod.apply_terminal_config_to_env-- def _counting(*args, **kwargs):- calls.append(1)- return real(*args, **kwargs)-- monkeypatch.setattr(config_mod, "apply_terminal_config_to_env", _counting)- _write_config("{}\n")-- terminal_tool._get_env_config()- terminal_tool._get_env_config()-- assert len(calls) == 1def test_bridge_config_failure_does_not_crash(monkeypatch):diff --git a/tests/tools/test_terminal_environment_recreated_notice.py b/tests/tools/test_terminal_environment_recreated_notice.pyindex e248b6989a0..30c14d0a7e2 100644--- a/tests/tools/test_terminal_environment_recreated_notice.py+++ b/tests/tools/test_terminal_environment_recreated_notice.py@@ -49,7 +49,6 @@ def test_docker_recovery_marks_pending_and_finalizer_warns(monkeypatch):flagged = json.loads(finalize_foreground_result(result={"output": "hi", "returncode": 0, "environment_recreated": True}, **common))assert "recreated" in flagged.get("environment_recreated", "")- assert "may be lost" in flagged["environment_recreated"]clean = json.loads(finalize_foreground_result(result={"output": "hi", "returncode": 0}, **common))diff --git a/tests/tools/test_terminal_exit_semantics.py b/tests/tools/test_terminal_exit_semantics.pyindex 0a63cc52be9..f0fd69edc04 100644--- a/tests/tools/test_terminal_exit_semantics.py+++ b/tests/tools/test_terminal_exit_semantics.py@@ -38,10 +38,6 @@ class TestInterpretExitCode:assert result is not Noneassert "differ" in result.lower()- def test_colordiff_files_differ(self):- result = _interpret_exit_code("colordiff file1 file2", 1)- assert result is not None- assert "differ" in result.lower()# ---- test / [: exit 1 = condition false ----diff --git a/tests/tools/test_terminal_foreground_timeout_cap.py b/tests/tools/test_terminal_foreground_timeout_cap.pyindex b43c4941b9a..5bcabc2ab7e 100644--- a/tests/tools/test_terminal_foreground_timeout_cap.py+++ b/tests/tools/test_terminal_foreground_timeout_cap.py@@ -54,14 +54,6 @@ class TestForegroundTimeoutCap:time.sleep(0.05)assert marker.read_text().count("x") == 1 # ran exactly once, in the background- def test_shell_backgrounding_is_still_refused(self):- """`&`/nohup need the command rewritten; the tool cannot do that safely, so it still refuses."""- from tools.terminal_tool import terminal_tool-- with patch("tools.terminal_tool._get_env_config", return_value=_make_env_config()), \- patch("tools.terminal_tool._start_cleanup_thread"):- result = json.loads(terminal_tool(command="sleep 5 &"))- assert "'&' backgrounding" in result["error"]def test_zero_timeout_rejected(self):"""timeout=0 must be rejected, not silently coerced to the default."""@@ -156,20 +148,6 @@ class TestForegroundTimeoutCap:assert "error" not in result or result["error"] is None-class TestForegroundMaxTimeoutConstant:- """Verify the FOREGROUND_MAX_TIMEOUT constant and schema."""-- def test_default_value_is_600(self):- """Default FOREGROUND_MAX_TIMEOUT is 600 when env var is not set."""- from tools.terminal_tool import FOREGROUND_MAX_TIMEOUT- assert FOREGROUND_MAX_TIMEOUT == 600-- def test_schema_mentions_max(self):- """Tool schema description should mention the max timeout."""- from tools.terminal_tool import TERMINAL_SCHEMA, FOREGROUND_MAX_TIMEOUT- timeout_desc = TERMINAL_SCHEMA["parameters"]["properties"]["timeout"]["description"]- assert str(FOREGROUND_MAX_TIMEOUT) in timeout_desc- assert "background process" in timeout_descclass TestPromotionKeepsTheDetachmentGuard:@@ -185,11 +163,3 @@ class TestPromotionKeepsTheDetachmentGuard:assert "'&' backgrounding" in result["error"]assert "nohup" in result2["error"]- def test_note_does_not_promise_a_notification_the_session_cannot_receive(self):- from tools.terminal_tool import _with_promoted_note-- kept = json.loads(_with_promoted_note(json.dumps({"session_id": "proc_x", "error": None, "notify_on_complete": True}), 900))- assert "arrives as a notification" in kept["promoted_from_foreground"]- dropped = json.loads(_with_promoted_note(json.dumps({"session_id": "proc_x", "error": None, "notify_on_complete": False}), 900))- assert "cannot receive completion notifications" in dropped["promoted_from_foreground"]- assert "poll" in dropped["promoted_from_foreground"]diff --git a/tests/tools/test_terminal_heredoc_background_guard.py b/tests/tools/test_terminal_heredoc_background_guard.pyindex 0da78ea6c0a..785957b411f 100644--- a/tests/tools/test_terminal_heredoc_background_guard.py+++ b/tests/tools/test_terminal_heredoc_background_guard.py@@ -25,7 +25,6 @@ hiding a real background operator is not.import pytestfrom tools.shell_heredoc import strip_inert_heredoc_bodies-from tools.terminal_tool_guards import _strip_quotesfrom tools.terminal_tool import (_foreground_background_guidance as guidance,)@@ -51,9 +50,6 @@ class TestInertQuotedHeredocPayloadAllowed:cmd = "python3 <<'EOF'" + NL + "z = a " + AMP + " b" + NL + "print(z)" + NL + "EOF"assert guidance(cmd) is None- def test_cat_literal_ui_text_in_body(self):- cmd = "cat <<'EOF'" + NL + "About FaceTime " + AMP + " Privacy" + NL + "EOF"- assert guidance(cmd) is Nonedef test_double_quoted_delimiter(self):cmd = 'cat <<"EOF"' + NL + "foo " + AMP + " bar" + NL + "EOF"@@ -251,27 +247,11 @@ class TestRealBackgroundingStillBlocked:)assert guidance(cmd) is not None- def test_background_after_cat_heredoc_redirect(self):- cmd = (- "cat <<'EOF' > f.txt" + NL + "payload" + NL + "EOF" + NL- + "long_running " + AMP- )- assert guidance(cmd) is not Noneclass TestStripHelpers:"""Direct unit checks on the masking helpers."""- def test_inert_body_removed_shell_tail_preserved(self):- cmd = (- "python3 - <<'PY'" + NL- + "x = left " + AMP + " right" + NL- + "PY" + NL- + "sleep 10 " + AMP- )- stripped = _strip_quotes(cmd)- assert "x = left " + AMP + " right" not in stripped- assert "sleep 10 " + AMP in strippeddef test_masking_preserves_line_structure(self):cmd = (diff --git a/tests/tools/test_terminal_hints.py b/tests/tools/test_terminal_hints.pyindex e05a8cec103..ff773fdb8e3 100644--- a/tests/tools/test_terminal_hints.py+++ b/tests/tools/test_terminal_hints.py@@ -1,9 +1,7 @@"""Tests for tools/terminal_hints.py — output-pattern failure hints."""-import jsonfrom unittest.mock import patch as mock_patch-import pytestfrom tools.terminal_hints import annotate_failure, annotate_masked_success@@ -32,7 +30,6 @@ class TestGhUnknownJsonField:out = 'Unknown JSON field: "authorAssociation"\nAvailable fields:\n additions\n author'hint = annotate_failure("gh pr view 1 --json authorAssociation", 1, out)assert "authorAssociation" in hint- assert "valid field list" in hintclass TestCommandNotFound:@@ -50,7 +47,6 @@ class TestCommandNotFound:out = "bash: line 3: shellcheck: command not found"hint = annotate_failure("shellcheck s.sh", 127, out)assert "shellcheck" in hint- assert "which" in hintclass TestModuleNotFound:@@ -59,7 +55,6 @@ class TestModuleNotFound:"ModuleNotFoundError: No module named 'requests'")hint = annotate_failure("python3 x.py", 1, out)assert "requests" in hint- assert "venv" in hintdef test_dotted_module(self):out = "ImportError: No module named 'hermes_cli.main'"@@ -68,10 +63,6 @@ class TestModuleNotFound:class TestGitShapes:- def test_merge_conflict(self):- out = "Auto-merging a.py\nCONFLICT (content): Merge conflict in a.py\nAutomatic merge failed; fix conflicts and then commit the result."- hint = annotate_failure("git merge feature", 1, out)- assert "Do not retry" in hintdef test_branch_already_exists(self):out = "fatal: a branch named 'fix/x' already exists"@@ -101,25 +92,6 @@ class TestBoundedScan:assert annotate_failure("x", 1, "boom") is None-class TestTerminalIntegration:- """The hint lands in the terminal result dict under 'hint'."""-- def test_hint_field_wired(self):- # Exercise the wiring path shape without a live environment: the- # result assembly guards on returncode != 0 and no exit_note.- from tools import terminal_tool_result- # simulate: interpret gives None, hints give a value- note = terminal_tool_result._interpret_exit_code("python x.py", 127)- assert note is None- hint = annotate_failure("python x.py", 127, "bash: python: command not found")- assert hint and "python3" in hint-- def test_exit_note_suppresses_pattern_hint(self):- # grep exit 1 is informational; annotate_failure must not be reached- # for it in the wiring (exit_note wins). Just verify the semantics- # table still covers it.- from tools import terminal_tool_result- assert terminal_tool_result._interpret_exit_code("grep foo bar.txt", 1) is not Noneclass TestMaskedSuccess:@@ -135,12 +107,9 @@ class TestMaskedSuccess:hint = annotate_masked_success("cargo build --release 2>&1 | tail -20", self._fail_out())- assert hint and "last pipeline command" in hint-- def test_pipe_head_flagged(self):- hint = annotate_masked_success("cargo check | head -50", self._fail_out())assert hint is not None+def test_or_echo_fallback_flagged(self):hint = annotate_masked_success('cargo build || echo "BUILD FAILED"',diff --git a/tests/tools/test_terminal_none_command_guard.py b/tests/tools/test_terminal_none_command_guard.pyindex e1c8e2864a1..9e86a85f130 100644--- a/tests/tools/test_terminal_none_command_guard.py+++ b/tests/tools/test_terminal_none_command_guard.py@@ -3,14 +3,8 @@import jsonfrom tools.terminal_tool import terminal_tool-from tools.terminal_tool_sudo import _transform_sudo_command-def test_transform_sudo_command_none_returns_cleanly():- transformed, sudo_stdin = _transform_sudo_command(None)-- assert transformed is None- assert sudo_stdin is Nonedef test_terminal_tool_none_command_returns_clean_error():@@ -18,5 +12,4 @@ def test_terminal_tool_none_command_returns_clean_error():assert result["exit_code"] == -1assert result["status"] == "error"- assert "expected string" in result["error"].lower()- assert "nonetype" in result["error"].lower()+ assert result["error"]diff --git a/tests/tools/test_terminal_requirements.py b/tests/tools/test_terminal_requirements.pyindex a5b0066806d..a89a9f973b8 100644--- a/tests/tools/test_terminal_requirements.py+++ b/tests/tools/test_terminal_requirements.py@@ -1,7 +1,6 @@import importlibimport logging-import pytestterminal_tool_module = importlib.import_module("tools.terminal_tool")@@ -136,15 +135,6 @@ def test_vercel_backend_accepts_token_tuple_auth(monkeypatch):assert terminal_tool_module.check_terminal_requirements() is True[email protected]("runtime", ["node24", "node22", "python3.13"])-def test_vercel_backend_accepts_supported_runtimes(monkeypatch, runtime):- _clear_terminal_env(monkeypatch)- monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")- monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", runtime)- monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())-- assert terminal_tool_module.check_terminal_requirements() is Truedef test_vercel_backend_accepts_blank_runtime(monkeypatch):@@ -170,7 +160,6 @@ def test_vercel_backend_rejects_unsupported_runtime(monkeypatch, caplog):assert ok is Falseassert any("Vercel Sandbox runtime 'node20' is not supported" in record.getMessage()- and "node24, node22, python3.13" in record.getMessage()for record in caplog.records)diff --git a/tests/tools/test_terminal_self_repo_guard.py b/tests/tools/test_terminal_self_repo_guard.pyindex ff3fb0b2137..626c4c20491 100644--- a/tests/tools/test_terminal_self_repo_guard.py+++ b/tests/tools/test_terminal_self_repo_guard.py@@ -68,7 +68,6 @@ class TestSelfRepoGuardWiring:config = _make_env_config(cwd=str(repo))result, env = _run("git checkout pr-51020", config, monkeypatch, repo)assert result["status"] == "blocked"- assert "mix module versions" in result["error"]assert str(repo) in result["error"]env.execute.assert_not_called()diff --git a/tests/tools/test_terminal_signal_exit.py b/tests/tools/test_terminal_signal_exit.pyindex aa3772d5eaf..0790d0c86f7 100644--- a/tests/tools/test_terminal_signal_exit.py+++ b/tests/tools/test_terminal_signal_exit.py@@ -18,19 +18,12 @@ class TestInterpretSignalExit:(-9, "SIGKILL"),(-11, "SIGSEGV"),(-15, "SIGTERM"),- (-6, "SIGABRT"),- (-8, "SIGFPE"),- (-13, "SIGPIPE"),])def test_negative_known_signals(self, code, expect):note = _interpret_signal_exit(code)assert note is not Noneassert expect in note- assert "terminated by" in note.lower()- def test_negative_oom_mentions_oom(self):- note = _interpret_signal_exit(-9)- assert "OOM" in notedef test_negative_unknown_signal_still_reports(self):# signum without a curated note still yields a generic note.@@ -44,15 +37,11 @@ class TestInterpretSignalExit:(137, "SIGKILL"),(139, "SIGSEGV"),(143, "SIGTERM"),- (134, "SIGABRT"),- (141, "SIGPIPE"),])def test_shell_band_known_signals(self, code, expect):note = _interpret_signal_exit(code)assert note is not Noneassert expect in note- # Hedged: a program can legitimately exit with these codes.- assert "usually" in notedef test_shell_band_uncurated_signum_returns_none(self):# 128+signum for a signum outside the curated table must stay@@ -78,9 +67,6 @@ class TestSignalExitWiring:note = _interpret_exit_code("python3 crash.py", -11)assert note is not None and "SIGSEGV" in note- def test_shell_band_via_interpret_exit_code(self):- note = _interpret_exit_code("./run_build.sh", 137)- assert note is not None and "SIGKILL" in notedef test_signal_note_wins_over_command_semantics(self):# A grep killed by SIGKILL must report the signal, not "no matches".diff --git a/tests/tools/test_terminal_task_cwd.py b/tests/tools/test_terminal_task_cwd.pyindex 95ed40f5ed0..58fc0e9cbcc 100644--- a/tests/tools/test_terminal_task_cwd.py+++ b/tests/tools/test_terminal_task_cwd.py@@ -165,15 +165,9 @@ def test_background_command_prefers_recorded_session_cwd_over_init_time_cwd(monk# session_key falls back to the raw task_id when no gateway contextvar is set# (it doesn't propagate to tool-worker threads), so process.kill / stop can# still find and terminate this background process.- assert registry.calls == [{- "command": "sleep 1",- "cwd": "/workspace/live",- "task_id": task_id,- "owner_task_id": task_id,- "session_key": task_id,- "env_vars": {},- "use_pty": False,- }]+ assert len(registry.calls) == 1+ assert registry.calls[0]["cwd"] == "/workspace/live"+ assert registry.calls[0]["session_key"] == task_iddef test_host_local_background_command_bypasses_configured_backend(tmp_path, monkeypatch):diff --git a/tests/tools/test_terminal_timeout_output.py b/tests/tools/test_terminal_timeout_output.pyindex 52823581fc8..9768011478b 100644--- a/tests/tools/test_terminal_timeout_output.py+++ b/tests/tools/test_terminal_timeout_output.py@@ -16,12 +16,3 @@ class TestTimeoutPreservesPartialOutput:assert "hello from test" in result["output"]assert "timed out" in result["output"].lower()- def test_timeout_with_no_output(self):- """A command that produces nothing before timeout should still- return a clean timeout message."""- env = LocalEnvironment()- result = env.execute("sleep 30", timeout=1)-- assert result["returncode"] == 124- assert "timed out" in result["output"].lower()- assert not result["output"].startswith("\n")diff --git a/tests/tools/test_terminal_tool.py b/tests/tools/test_terminal_tool.pyindex 40c62fcb7d4..9b73168886a 100644--- a/tests/tools/test_terminal_tool.py+++ b/tests/tools/test_terminal_tool.py@@ -23,34 +23,10 @@ def test_searching_for_sudo_does_not_trigger_rewrite(monkeypatch):assert sudo_stdin is None-def test_terminal_schema_advertises_persistent_env_state():- description = terminal_tool.TERMINAL_TOOL_DESCRIPTION- assert "exported environment variables persist between calls" in description- assert "activate a virtualenv" in description- assert "once per session" in description-def test_printf_literal_sudo_does_not_trigger_rewrite(monkeypatch):- monkeypatch.delenv("SUDO_PASSWORD", raising=False)- monkeypatch.delenv("HERMES_INTERACTIVE", raising=False)-- command = "printf '%s\\n' sudo"- transformed, sudo_stdin = terminal_tool_sudo._transform_sudo_command(command)-- assert transformed == command- assert sudo_stdin is None--def test_non_command_argument_named_sudo_does_not_trigger_rewrite(monkeypatch):- monkeypatch.delenv("SUDO_PASSWORD", raising=False)- monkeypatch.delenv("HERMES_INTERACTIVE", raising=False)-- command = "grep -n sudo README.md"- transformed, sudo_stdin = terminal_tool_sudo._transform_sudo_command(command)-- assert transformed == command- assert sudo_stdin is Nonedef test_actual_sudo_command_uses_configured_password(monkeypatch):diff --git a/tests/tools/test_terminal_tool_exception_redaction.py b/tests/tools/test_terminal_tool_exception_redaction.pyindex 5862adb882f..0f6097ca715 100644--- a/tests/tools/test_terminal_tool_exception_redaction.py+++ b/tests/tools/test_terminal_tool_exception_redaction.py@@ -27,7 +27,6 @@ def test_generic_exception_result_redacts_error_and_traceback(monkeypatch):assert SECRET not in result["traceback"]# The redaction must mask the value, not drop the message entirely.assert "OPENAI_API_KEY=" in result["error"]- assert "Failed to execute command" in result["error"]def test_degraded_fail_mode_result_redacts_error_and_traceback(monkeypatch):diff --git a/tests/tools/test_terminal_tool_requirements.py b/tests/tools/test_terminal_tool_requirements.pyindex 39797f7c6af..eca0c3d987e 100644--- a/tests/tools/test_terminal_tool_requirements.py+++ b/tests/tools/test_terminal_tool_requirements.py@@ -113,38 +113,6 @@ class TestCheckFnTransientFailureSuppression:# Different fn so last-good for `good` doesn't apply; bad has no success.assert reg._check_fn_cached(bad) is False- def test_expected_false_reprobe_logs_info_but_probe_exception_stays_warning(- self, monkeypatch, caplog- ):- import tools.registry as reg-- calls = {"count": 0}-- def unavailable():- calls["count"] += 1- return False-- def broken():- raise RuntimeError("probe failed")-- clock = {"now": 1000.0}- monkeypatch.setattr(reg.time, "monotonic", lambda: clock["now"])-- with caplog.at_level(logging.INFO, logger="tools.registry"):- assert reg._check_fn_cached(unavailable) is False- clock["now"] += reg._CHECK_FN_TTL_SECONDS + 1- assert reg._check_fn_cached(unavailable) is False- assert reg._check_fn_cached(broken) is False-- expected_false = [- record for record in caplog.records if "returned False" in record.getMessage()- ]- raised = [record for record in caplog.records if "raised" in record.getMessage()]- assert calls["count"] == 2- assert [record.levelno for record in expected_false] == [logging.INFO, logging.INFO]- assert len(raised) == 1- assert raised[0].levelno == logging.WARNING- assert raised[0].exc_info is not Nonedef test_core_tool_drop_after_success_warns_once_never_configured_stays_info(self, monkeypatch, caplog):@@ -452,20 +420,6 @@ class TestUnscopedSecretReadLogging:crashed check_fn (WARNING + traceback); an unscoped read reported whilethe scope was *resolved* is a genuinely lost scope and stays loud."""- def test_raising_check_fn_logs_traceback_on_cached_path(self, caplog):- """A check_fn that raises is a probe bug, not "nothing configured": the verdict log must- carry the traceback so a silently stripped toolset is diagnosable from agent.log (#87950)."""- import logging-- import tools.registry as reg-- def probe():- raise RuntimeError("resolver exploded")-- with caplog.at_level(logging.WARNING, logger="tools.registry"):- assert reg._check_fn_cached(probe) is False- verdicts = [r for r in caplog.records if "dependent tools will be unavailable" in r.getMessage()]- assert verdicts and all(r.exc_info and r.exc_info[0] is RuntimeError for r in verdicts)def test_expected_fail_closed_probe_is_quiet_but_lost_scope_stays_loud(self, caplog):"""The verdict comes from the LIVE scope at the catch site (#110635): unscoped caller →diff --git a/tests/tools/test_termux_api_detection.py b/tests/tools/test_termux_api_detection.pyindex c1406c4585a..4016e0df999 100644--- a/tests/tools/test_termux_api_detection.py+++ b/tests/tools/test_termux_api_detection.py@@ -22,9 +22,7 @@ from __future__ import annotationsimport subprocessfrom types import SimpleNamespace-from unittest.mock import MagicMock-import pytest# ── Helpers ────────────────────────────────────────────────────────────────@@ -203,10 +201,6 @@ class TestDetectAudioEnvironmentTermuxFallback:"when probes are inconclusive but the binary works (issue "f"#31015). warnings={result['warnings']!r}")- assert any(- "Termux:API microphone recording available" in n- for n in result.get("notices", [])- )def test_clean_probes_no_match_still_blocks(self, monkeypatch):"""The genuine "CLI installed without the app" case still blocksdiff --git a/tests/tools/test_threaded_process_handle.py b/tests/tools/test_threaded_process_handle.pyindex 3b6a7551a03..e50cb3586a0 100644--- a/tests/tools/test_threaded_process_handle.py+++ b/tests/tools/test_threaded_process_handle.py@@ -19,16 +19,6 @@ class TestBasicExecution:assert "hello world" in output- def test_empty_output(self):- def exec_fn():- return ("", 0)-- handle = _ThreadedProcessHandle(exec_fn)- handle.wait(timeout=5)-- assert handle.returncode == 0- output = handle.stdout.read()- assert output == ""class TestPolling:@@ -46,13 +36,6 @@ class TestPolling:handle.wait(timeout=5)assert handle.poll() == 0- def test_poll_returns_returncode_when_done(self):- def exec_fn():- return ("ok", 0)-- handle = _ThreadedProcessHandle(exec_fn)- handle.wait(timeout=5)- assert handle.poll() == 0class TestCancelFn:diff --git a/tests/tools/test_threat_patterns.py b/tests/tools/test_threat_patterns.pyindex f43a2e9d59a..74675e6ee5b 100644--- a/tests/tools/test_threat_patterns.py+++ b/tests/tools/test_threat_patterns.py@@ -10,7 +10,6 @@ import timeimport pytestfrom tools.threat_patterns import (- INVISIBLE_CHARS,MAX_SCAN_CHARS,first_threat_message,scan_for_threats,@@ -236,10 +235,6 @@ class TestInvisibleUnicode:assert any(f.startswith("invisible_unicode_U+200B") for f in findings)- def test_invisible_chars_set_is_frozenset(self):- # Pin: should be immutable so callers can't accidentally mutate the- # shared set.- assert isinstance(INVISIBLE_CHARS, frozenset)# =========================================================================@@ -281,7 +276,6 @@ class TestFirstThreatMessage:msg = first_threat_message("hello\u200b", scope="strict")assert msg is not Noneassert "U+200B" in msg- assert "invisible unicode" in msg.lower()# =========================================================================diff --git a/tests/tools/test_tip_tool.py b/tests/tools/test_tip_tool.pyindex d8c9098a67d..e5e33fb91df 100644--- a/tests/tools/test_tip_tool.py+++ b/tests/tools/test_tip_tool.py@@ -5,7 +5,6 @@ import jsonimport pytestfrom tools import tip_tool as tt-from tools.registry import registry@pytest.fixture@@ -21,23 +20,9 @@ def emitted(monkeypatch):return sent-def test_lives_in_the_gui_surface_toolset(monkeypatch):- """Scoped by toolset, not by the backend's env — see AGENTS.md."""- monkeypatch.delenv("HERMES_DESKTOP", raising=False)- entry = registry.get_entry("show_tip")- assert entry is not None- assert entry.toolset == "desktop_ui"-def test_answers_to_the_appearance_switch():- """Tips off has to mean the model never sees the tool. See- tests/tools/test_display_toggles.py for the config end of it."""- entry = registry.get_entry("show_tip")-- assert entry is not None- assert entry.check_fn is tt.check_tips_enabled-def test_requires_the_desktop_bridge(monkeypatch):"""Outside the desktop GUI there is no emitter — a clear error, no crash."""diff --git a/tests/tools/test_tirith_security.py b/tests/tools/test_tirith_security.pyindex 261b34b9ede..a77275bd5fa 100644--- a/tests/tools/test_tirith_security.py+++ b/tests/tools/test_tirith_security.py@@ -764,18 +764,6 @@ class TestEmojiVariationSelectorSuppression:assert result["findings"] == findings-class TestIsAppTldFinding:- """Unit tests for the _is_app_tld_finding helper."""-- @pytest.mark.parametrize("finding, expected", [- ({"rule_id": "lookalike_tld", "value": ".APP"}, True), # case-insensitive- ({"rule_id": "lookalike_tld", "message": "Domain uses '.app' TLD"}, True),- ({"rule_id": "shortened_url", "value": ".app"}, False), # wrong rule_id- ({"rule_id": "lookalike_tld", "value": ".zip"}, False), # other TLD- ])- def test_app_tld_detection(self, finding, expected):- from tools.tirith_security import _is_app_tld_finding- assert _is_app_tld_finding(finding) is expected# ---------------------------------------------------------------------------diff --git a/tests/tools/test_todo_nested.py b/tests/tools/test_todo_nested.pyindex 98b936b6a4a..5d61ee27639 100644--- a/tests/tools/test_todo_nested.py+++ b/tests/tools/test_todo_nested.py@@ -122,12 +122,6 @@ class TestNestedInjection:])assert store.format_for_injection() is None- def test_flat_injection_unchanged(self):- store = TodoStore()- store.write([_item("a", status="in_progress"), _item("b")])- text = store.format_for_injection()- assert text is not None- assert text.split("\n")[1] == "- [>] a. task a (in_progress)"class TestOrderGuard:@@ -140,22 +134,9 @@ class TestOrderGuard:])assert [i["id"] for i in items] == ["a", "b", "b1"]- def test_flat_list_still_reordered(self):- store = TodoStore()- items = store.write([- _item("a", status="pending"),- _item("b", status="in_progress"),- ])- assert [i["id"] for i in items] == ["b", "a"]class TestToolRoundTrip:- def test_parent_survives_json(self):- store = TodoStore()- out = todo_tool(todos=[_item("a"), _item("a1", parent="a")], store=store)- data = json.loads(out)- assert data["todos"][1]["parent"] == "a"- assert data["summary"]["total"] == 2def test_hydration_replay_preserves_parent(self):# Simulate _hydrate_todo_store: write the previous tool result'sdiff --git a/tests/tools/test_todo_schema_diet.py b/tests/tools/test_todo_schema_diet.pydeleted file mode 100644index 9c84396a115..00000000000--- a/tests/tools/test_todo_schema_diet.py+++ /dev/null@@ -1,50 +0,0 @@-"""todo schema diet contract (#95681).--Pins the dedup: item shape and merge semantics are taught ONLY by the-parameter schema (types/enum/required), never re-spelled in the-description — and the load-bearing behavioral teachings survive.-"""-import os-import sys-import unittest--sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))--from tools.todo_tool import TODO_SCHEMA---class TestTodoSchemaDiet(unittest.TestCase):- def test_description_does_not_respell_param_structure(self):- desc = TODO_SCHEMA["description"]- # The old '{id: string, content: string, status: ...}' spell-out- # and the 'Writing:' merge bullets duplicated the param schema.- self.assertNotIn("{id:", desc)- self.assertNotIn("Writing:", desc)- self.assertNotIn("merge=", desc)- self.assertNotIn("pending|in_progress", desc)-- def test_param_schema_is_the_single_structure_source(self):- item = TODO_SCHEMA["parameters"]["properties"]["todos"]["items"]- self.assertEqual(item["required"], ["id", "content", "status"])- self.assertEqual(- item["properties"]["status"]["enum"],- ["pending", "in_progress", "completed", "cancelled"],- )- merge_desc = TODO_SCHEMA["parameters"]["properties"]["merge"]["description"]- self.assertIn("replace the entire list", merge_desc)- self.assertIn("update existing items by id", merge_desc)-- def test_behavioral_teachings_survive(self):- """The parts that fight real model failure modes must not be- dieted away: enumerate-all-N, one in_progress, verified-done,- cancel-and-revise."""- desc = TODO_SCHEMA["description"]- self.assertIn("enumerate every instance", desc)- self.assertIn("ONE item in_progress", desc)- self.assertIn("verified done", desc)- self.assertIn("cancel it and add a revised item", desc)- self.assertIn("3+ steps", desc)---if __name__ == "__main__":- unittest.main()diff --git a/tests/tools/test_todo_tool.py b/tests/tools/test_todo_tool.pyindex e7b6bb1b128..c7f65fe0e83 100644--- a/tests/tools/test_todo_tool.py+++ b/tests/tools/test_todo_tool.py@@ -77,7 +77,6 @@ class TestFormatForInjection:assert "[>]" in textassert "Next" in textassert "Working" in text- assert "context compression" in text.lower()class TestMergeMode:@@ -199,14 +198,3 @@ class TestTodoStoreBounds:])assert len(store.read()) == MAX_TODO_ITEMS- def test_normal_list_is_unchanged(self):- """No regression: ordinary plans pass through untouched (no marker,- same content, same order)."""- store = TodoStore()- store.write([- {"id": "1", "content": "write the report", "status": "in_progress"},- {"id": "2", "content": "review PR", "status": "pending"},- ])- items = store.read()- assert [i["content"] for i in items] == ["write the report", "review PR"]- assert "[truncated]" not in items[0]["content"]diff --git a/tests/tools/test_tool_backend_helpers.py b/tests/tools/test_tool_backend_helpers.pyindex 2fc76dd76e8..92bff6b7383 100644--- a/tests/tools/test_tool_backend_helpers.py+++ b/tests/tools/test_tool_backend_helpers.py@@ -23,7 +23,6 @@ from tools.tool_backend_helpers import (managed_nous_tools_enabled,nous_tool_gateway_unavailable_message,normalize_browser_cloud_provider,- normalize_modal_mode,prefers_gateway,resolve_modal_backend_state,resolve_openai_audio_api_key,@@ -96,10 +95,6 @@ class TestNormalizeBrowserCloudProvider:assert normalize_browser_cloud_provider(None) == "local"- def test_integer_coerced(self):- result = normalize_browser_cloud_provider(42)- assert isinstance(result, str)- assert result == "42"# ---------------------------------------------------------------------------@@ -120,13 +115,6 @@ class TestCoerceModalMode:assert coerce_modal_mode(" managed ") == "managed"-class TestNormalizeModalMode:- """normalize_modal_mode is an alias for coerce_modal_mode."""-- def test_delegates_to_coerce(self):- assert normalize_modal_mode("direct") == coerce_modal_mode("direct")- assert normalize_modal_mode(None) == coerce_modal_mode(None)- assert normalize_modal_mode("bogus") == coerce_modal_mode("bogus")# ---------------------------------------------------------------------------diff --git a/tests/tools/test_tool_output_limits.py b/tests/tools/test_tool_output_limits.pyindex 84c1f976507..df9fdfa3637 100644--- a/tests/tools/test_tool_output_limits.py+++ b/tests/tools/test_tool_output_limits.py@@ -33,10 +33,6 @@ def _reset_limits_cache():class TestDefaults:- def test_defaults_match_previous_hardcoded_values(self):- assert tol.DEFAULT_MAX_BYTES == 50_000- assert tol.DEFAULT_MAX_LINES == 2000- assert tol.DEFAULT_MAX_LINE_LENGTH == 2000def test_get_limits_returns_defaults_when_load_config_raises(self):diff --git a/tests/tools/test_tool_result_storage.py b/tests/tools/test_tool_result_storage.pyindex ebceb176b59..4481bc2189a 100644--- a/tests/tools/test_tool_result_storage.py+++ b/tests/tools/test_tool_result_storage.py@@ -4,7 +4,6 @@ import pytestfrom unittest.mock import MagicMock, patchfrom tools.budget_config import (- DEFAULT_RESULT_SIZE_CHARS,DEFAULT_PREVIEW_SIZE_CHARS,BudgetConfig,)@@ -196,21 +195,12 @@ class TestBuildPersistedMessage:)assert msg.startswith(PERSISTED_OUTPUT_TAG)assert msg.endswith(PERSISTED_OUTPUT_CLOSING_TAG)- assert "50,000 characters" in msgassert "/tmp/hermes-results/test123.txt" in msgassert "read_file" in msgassert "first 100 chars..." in msgassert "..." in msg # has_more indicator- def test_large_size_shows_mb(self):- msg = _build_persisted_message(- preview="x",- has_more=True,- original_size=2_000_000,- file_path="/tmp/hermes-results/big.txt",- )- assert "MB" in msg# ── maybe_persist_tool_result ─────────────────────────────────────────@@ -354,21 +344,16 @@ class TestEnforceTurnBudget:class TestPerToolThresholds:"""Verify registry wiring for per-tool thresholds."""- def test_registry_has_get_max_result_size(self):- from tools.registry import registry- assert hasattr(registry, "get_max_result_size")- def test_read_file_registry_cap_is_100k(self):- """Regression test: read_file must have a 100_000 char registry cap (Layer 2 safety net)."""+ def test_read_file_registry_cap_is_finite(self):+ """read_file must keep a finite registry cap (Layer 2 safety net)."""from tools.registry import registrytry:import tools.file_tools # noqa: F401val = registry.get_max_result_size("read_file")- assert val == 100_000, (- f"read_file registry cap must be 100_000, got {val!r}. "- "float('inf') is not allowed — it disables the Layer 2 result-size guard."- )+ # float('inf') disables the Layer 2 result-size guard.+ assert 0 < val < float("inf"), valexcept ImportError:pytest.skip("file_tools not importable in test env")@@ -377,7 +362,7 @@ class TestPerToolThresholds:try:import tools.file_tools # noqa: F401val = registry.get_max_result_size("search_files")- assert val == 100_000+ assert 0 < val < float("inf"), valexcept ImportError:pytest.skip("file_tools not importable in test env")@@ -535,18 +520,3 @@ class TestSpillover:# ── recovery hint in the persisted preview ────────────────────────────-class TestRecoveryHint:- def test_preview_teaches_recovery_not_refetch(self):- msg = _build_persisted_message(- preview="preview text",- has_more=True,- original_size=60_000,- file_path="/tmp/hermes-results/r.txt",- )- assert "Recovery:" in msg- assert "execute_code" in msg- assert "re-request" in msg- # Structure preserved: tag, size, path, read_file guidance all intact.- assert msg.startswith(PERSISTED_OUTPUT_TAG)- assert msg.endswith(PERSISTED_OUTPUT_CLOSING_TAG)- assert "read_file" in msgdiff --git a/tests/tools/test_tool_search.py b/tests/tools/test_tool_search.pyindex d5834f068c4..9c19eba5933 100644--- a/tests/tools/test_tool_search.py+++ b/tests/tools/test_tool_search.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport jsonimport osimport sys-from typing import List, Dict, Any+from typing import Dict, Anyimport pytest@@ -40,11 +40,6 @@ def _td(name: str, description: str = "", properties: Dict[str, Any] | None = Noclass TestConfigParsing:- def test_default_when_missing(self):- from tools.tool_search import ToolSearchConfig- cfg = ToolSearchConfig.from_raw(None)- assert cfg.enabled == "auto"- assert cfg.threshold_pct == 5.0def test_defer_default_is_the_registered_list_and_a_user_list_replaces_it(self, caplog):"""#116404: the curated deferral set lives in DEFAULT_CONFIG (so ``hermes config set``@@ -62,8 +57,7 @@ class TestConfigParsing:with caplog.at_level("WARNING", logger="tools.tool_search"):assert ToolSearchConfig.from_raw({"defer": "todo_list"}).effective_defer_tools == configured- assert any("tools.tool_search.defer" in r.getMessage() and "expected a YAML list" in r.getMessage()- for r in caplog.records)+ assert any(r.levelname == "WARNING" for r in caplog.records)def test_bool_true_maps_to_auto(self):from tools.tool_search import ToolSearchConfig@@ -90,11 +84,9 @@ class TestClassification:def test_core_tools_never_defer(self):"""The critical invariant from the OpenClaw report."""from tools.tool_search import is_deferrable_tool_name- # Sample of core tools from _HERMES_CORE_TOOLS.- for core_name in ["terminal", "read_file", "write_file", "patch",- "search_files", "todo", "memory", "browser_navigate",- "web_search", "session_search", "clarify",- "execute_code", "delegate_task", "send_message"]:+ from toolsets import _HERMES_CORE_TOOLS+ assert _HERMES_CORE_TOOLS+ for core_name in _HERMES_CORE_TOOLS:assert not is_deferrable_tool_name(core_name), (f"Core tool '{core_name}' must NEVER be deferrable")@@ -106,35 +98,18 @@ class TestClassification:def test_gui_surface_tools_never_defer(self):"""Session-gated GUI tools stay direct and stay off the global core list."""- from tools.registry import discover_builtin_tools- from tools.tool_search import is_deferrable_tool_name+ from tools.registry import discover_builtin_tools, registry+ from tools.tool_search import _DIRECT_SURFACE_TOOLSETS, is_deferrable_tool_namefrom toolsets import _HERMES_CORE_TOOLSdiscover_builtin_tools()- for name in ("read_window_below", "apply_layout", "project_list"):+ surface = [n for n, ts in registry.get_tool_to_toolset_map().items()+ if ts in _DIRECT_SURFACE_TOOLSETS]+ assert surface+ for name in surface:assert not is_deferrable_tool_name(name), nameassert name not in _HERMES_CORE_TOOLS- def test_gui_surface_defers_by_default(self):- """2026-08 core-deferral reversal: the curated defer set (GUI surface- included) hides behind the bridge BY DEFAULT. project tools not in- the defer set stay direct."""- from tools.registry import discover_builtin_tools- from tools.tool_search import ToolSearchConfig, assemble_tool_defs-- discover_builtin_tools()- assembled = assemble_tool_defs(- [_td(name, f"GUI {name}") for name in- {"read_window_below", "apply_layout", "project_list"}],- context_length=200_000,- config=ToolSearchConfig.from_raw({"enabled": "on"}),- )- assert assembled.activated- names = {td["function"]["name"] for td in assembled.tool_defs}- assert "read_window_below" not in names- assert "apply_layout" not in names- # project_list is NOT in the curated defer set → stays direct.- assert "project_list" in namesdef test_defer_override_restores_legacy_direct_gui(self):"""tools.tool_search.defer: [] restores the everything-eager legacy:@@ -191,41 +166,7 @@ class TestClassification:# computer_use IS in the curated defer set → behind the bridge.assert "computer_use" not in names- def test_clarify_stays_eager_by_default(self):- """PR #97979 A/B verdict (288 runs, 3 model tiers): clarify deferred- collapsed structured ask-the-user usage 18/18 → 7/18 (gpt-terra 0/6);- models fell back to plain-text questions. The ask-the-user affordance- must stay ambient — clarify is NOT in the curated default defer set,- and assembles as a direct tool even when the bridge is active."""- from tools.registry import discover_builtin_tools- from tools.tool_search import (- _DEFAULT_DEFERRED_TOOLS,- ToolSearchConfig,- assemble_tool_defs,- )-- assert "clarify" not in _DEFAULT_DEFERRED_TOOLS- discover_builtin_tools()- assembled = assemble_tool_defs(- [- _td("clarify", "Ask the user clarifying questions"),- _td("computer_use", "Drive the OS"),- ],- context_length=200_000,- config=ToolSearchConfig.from_raw({"enabled": "on"}),- )- assert assembled.activated # computer_use still activates the bridge- names = {td["function"]["name"] for td in assembled.tool_defs}- assert "clarify" in names- assert "computer_use" not in names-- def test_unknown_tool_not_deferrable(self):- """Defensive: a tool name we cannot resolve to a registry entry must- not be claimed as deferrable. This protects against the OpenClaw- cron regression where unresolved tools were silently dropped."""- from tools.tool_search import is_deferrable_tool_name- assert not is_deferrable_tool_name("xx_definitely_not_a_tool_xx")def test_classify_keeps_unknown_in_visible(self):"""A tool we can't classify stays visible — never silently dropped.@@ -385,23 +326,8 @@ class TestAssembly:assert not result.activatedassert {t["function"]["name"] for t in result.tool_defs} == {"terminal", "read_file"}- @staticmethod- def _register_mcp(name):- from tools.registry import registry-- def _handler(args, task_id=None, **kw):- return json.dumps({"ok": True})-- registry.register(- name=name,- handler=_handler,- schema=_td(name, "Deferred capability description.")["function"],- toolset="mcp-tiertest",- )--def test_idempotent_when_bridge_already_present(self):- from tools.tool_search import assemble_tool_defs, ToolSearchConfig, BRIDGE_TOOL_NAMES+ from tools.tool_search import assemble_tool_defs, ToolSearchConfigdefs = [_td("terminal", "Run shell"), _td("tool_search", "old")]result = assemble_tool_defs(defs,@@ -437,7 +363,6 @@ class TestBridgeDispatch:parsed = json.loads(tool_search.dispatch_tool_search({"queries": over}, current_tool_defs=[], config=cfg))assert "error" in parsed- assert "too many queries" in parsed["error"]def test_empty_search_keeps_connected_sources_discoverable(self):from tools.registry import registry@@ -465,8 +390,7 @@ class TestBridgeDispatch:assert group["available_sources"] == [{"name": "recovery-catalog", "tool_count": 1},]- assert "remain available" in group["hint"]- assert "before concluding" in group["hint"]+ assert group["hint"]assert "available_sources" not in result@@ -488,7 +412,6 @@ class TestBridgeDispatch:"arguments": {},})assert err is not None- assert "bridge tool" in err.lower()@pytest.mark.parametrize("raw_args", ["", " \n", None])def test_resolve_underlying_call_treats_blank_arguments_as_no_arguments(self, raw_args):@@ -499,7 +422,7 @@ class TestBridgeDispatch:name, args, err = resolve_underlying_call({"calls": [{"name": "todo_list", "arguments": raw_args}]})assert (name, args, err) == ("todo_list", {}, None)_, _, err = resolve_underlying_call({"calls": [{"name": "todo_list", "arguments": '{"todos": ['}]})- assert err and "not valid JSON" in err+ assert err# ---------------------------------------------------------------------------@@ -508,17 +431,6 @@ class TestBridgeDispatch:class TestHandleFunctionCallIntegration:- def test_tool_search_dispatch_through_handle_function_call(self):- """The dispatcher recognizes the bridge tool by name."""- import model_tools- result = model_tools.handle_function_call(- function_name="tool_search",- function_args={"queries": ["nothing matches this"]},- )- parsed = json.loads(result)- # Without a real registry, the matches will be empty, but the- # dispatch path completed without error.- assert "results" in parsed or "error" in parseddef test_tool_search_emits_one_terminal_hook(self, monkeypatch):"""Inline bridge results still complete the tool lifecycle."""@@ -575,32 +487,6 @@ class TestRegression_OpenClawCron84141:every core tool survives."""- def test_core_tool_survives_alongside_many_mcp_tools(self):- from tools.tool_search import (- assemble_tool_defs, ToolSearchConfig, BRIDGE_TOOL_NAMES,- classify_tools,- )- # 1 core tool + 50 unknown/MCP-shaped tools (deferrable).- defs = [_td("terminal", "Run shell commands")]- # Pad with fake "deferrable" tools — without registry registration,- # classify_tools puts them in 'visible'. So instead, we just verify- # the core-tool side: terminal stays in visible regardless.- visible, deferrable = classify_tools(defs)- assert any(- (td.get("function") or {}).get("name") == "terminal"- for td in visible- ), "Core tool 'terminal' was wrongly classified as deferrable"-- # Now force activation and check the resulting tool-defs list.- result = assemble_tool_defs(- defs,- context_length=200_000,- config=ToolSearchConfig.from_raw({"enabled": "on"}),- )- names = {(t.get("function") or {}).get("name") for t in result.tool_defs}- # terminal must be present; bridges are only added if there are- # deferrable tools to put behind them.- assert "terminal" in namesdef test_unwrap_rejects_core_tool_attempt(self):"""Even if the model tries to invoke a core tool through tool_call,@@ -611,7 +497,6 @@ class TestRegression_OpenClawCron84141:"arguments": {"command": "echo hi"},})assert err is not None- assert "directly-listed tool" in err and "call it directly" in err.lower()class TestRegression_ToolsetScoping:@@ -691,13 +576,6 @@ class TestRegression_ToolsetScoping:class TestCatalogListing:- def test_config_defaults(self):- from tools.tool_search import ToolSearchConfig- cfg = ToolSearchConfig.from_raw(None)- assert cfg.listing == "auto"- assert cfg.listing_max_tokens == 4000- # legacy bool shapes keep defaults too- assert ToolSearchConfig.from_raw(True).listing == "auto"def test_default_listing_cap_bounds_fixed_catalog_overhead(self):@@ -732,14 +610,6 @@ class TestCatalogListing:assert description_tokens < 4500assert result.listing_form in {"names", "groups", "mixed"}- def test_short_desc_first_sentence_and_clip(self):- from tools.tool_search_catalog import _short_desc- assert _short_desc("Open an issue. Second sentence dropped.") == "Open an issue."- long = "word " * 40- s = _short_desc(long)- assert len(s) <= 61 # 60 + ellipsis char- assert s.endswith("…")- assert _short_desc("") == ""@staticmethod@@ -831,7 +701,6 @@ class TestDeferredCallSchemaProbe:assert err is not Noneparsed = json.loads(err)assert "document_id" in parsed["error"]- assert "NOT invoked" in parsed["error"]assert parsed["parameters"]["required"] == ["document_id"]assert "document_id" in parsed["parameters"]["properties"]@@ -879,7 +748,6 @@ class TestDeferredCallSchemaProbe:assert calls == []assert result["path"] == "arguments.priority"assert result["constraint"] == "enum"- assert "NOT invoked" in result["error"]@pytest.mark.parametrize(("suffix", "arguments", "expected_path", "expected_constraint"),diff --git a/tests/tools/test_tool_search_multiquery.py b/tests/tools/test_tool_search_multiquery.pyindex 137658c46b0..8800f3085cd 100644--- a/tests/tools/test_tool_search_multiquery.py+++ b/tests/tools/test_tool_search_multiquery.py@@ -97,18 +97,6 @@ class TestStemming:catalog = build_catalog(issue_defs)assert search_catalog(catalog, "post gmail message", limit=5) == []- def test_single_token_stems_are_cached(self):- from tools.tool_search_catalog import _stem, _tokenize-- _stem.cache_clear()- corpus = "issues creating issues creating"- _tokenize(corpus)- hits_before = _stem.cache_info().hits- _tokenize(corpus)-- assert _stem.cache_info().hits > hits_before- assert _stem.cache_info().hits > 0- assert _tokenize("issues creating") == ["issu", "creat"]def test_parallel_tokenize_search_and_dispatch_are_deterministic(self, issue_defs):from tools.tool_search import (@@ -348,7 +336,7 @@ class TestMultiQuerySearch:assert "available_sources" not in result["results"][0]assert "hint" not in result["results"][0]missed = result["results"][1]- assert "This query returned no lexical matches" in missed["hint"]+ assert missed["hint"]source_names = {s["name"] for s in missed["available_sources"]}assert {"mq-linear", "mq-slack"} <= source_namesassert "available_sources" not in result@@ -374,7 +362,7 @@ class TestMultiQuerySearch:assert "error" not in okover = json.loads(tool_search.dispatch_tool_search({"queries": ["a", "b", "c"]}, current_tool_defs=issue_defs, config=cfg))- assert "too many queries" in over["error"]+ assert "error" in over# ---------------------------------------------------------------------------@@ -404,7 +392,7 @@ class TestBatchedDescribe:# Deferrable-but-absent and unknown names collect in not_found; found# ones still resolve.assert result["not_found"] == ["mq_out_of_scope_op", "mcp__bogus__missing"]- assert "tool_search" in result["hint"]+ assert result["hint"]assert "errors" not in resultdef test_real_schemas_and_unknown_name_are_classified_independently(self):@@ -469,10 +457,7 @@ class TestBatchedDescribe:config=ToolSearchConfig.from_raw({}),))- assert result["errors"][name] == (- f"'{name}' is a directly-listed tool, not a deferred one. "- "Call it directly instead of via tool_call."- )+ assert result["errors"][name]assert name not in result.get("not_found", [])def test_registry_lookup_failure_is_not_found(self, monkeypatch):@@ -515,7 +500,7 @@ class TestBatchedDescribe:over = ["n%d" % i for i in range(3)]parsed = json.loads(tool_search.dispatch_tool_describe({"names": over}, current_tool_defs=issue_defs, config=cfg))- assert "too many names" in parsed["error"]+ assert "error" in parseddef test_bare_string_name_coerced(self, issue_defs):from tools.tool_search import ToolSearchConfig, dispatch_tool_describe@@ -539,8 +524,6 @@ class TestConfigAndSchema:from tools.tool_search import ToolSearchConfigcfg = ToolSearchConfig.from_raw(DEFAULT_CONFIG["tools"]["tool_search"])- assert cfg.max_search_limit == 25- assert cfg.search_default_limit == 5assert 1 <= cfg.search_default_limit <= cfg.max_search_limit <= 50def test_bridge_schema_declares_array_inputs(self):@@ -550,15 +533,6 @@ class TestConfigAndSchema:search_params = schemas["tool_search"]["parameters"]assert search_params["required"] == ["queries"]assert search_params["properties"]["queries"]["type"] == "array"- query_description = search_params["properties"]["queries"]["description"]- assert "single string is accepted" in query_description- assert "one query" in query_description- limit_description = search_params["properties"]["limit"]["description"]- assert "per query" in limit_description- assert "configured maximum (25 by default)" in limit_descriptiondescribe_params = schemas["tool_describe"]["parameters"]assert describe_params["required"] == ["names"]assert describe_params["properties"]["names"]["type"] == "array"- name_description = describe_params["properties"]["names"]["description"]- assert "single string is accepted" in name_description- assert "one name" in name_descriptiondiff --git a/tests/tools/test_toolset_distributions.py b/tests/tools/test_toolset_distributions.pyindex a90607ebcfa..7595e904062 100644--- a/tests/tools/test_toolset_distributions.py+++ b/tests/tools/test_toolset_distributions.py@@ -1,22 +1,13 @@"""Tests for toolset_distributions.py — distribution CRUD, sampling, validation."""-import pytestfrom toolset_distributions import (DISTRIBUTIONS,- get_distribution,list_distributions,sample_toolsets_from_distribution,- validate_distribution,)-class TestGetDistribution:- def test_known_distribution(self):- dist = get_distribution("default")- assert dist is not None- assert "description" in dist- assert "toolsets" in dist@@ -30,25 +21,9 @@ class TestListDistributions:-class TestValidateDistribution:- def test_valid(self):- assert validate_distribution("default") is True- assert validate_distribution("research") is True-class TestSampleToolsetsFromDistribution:--- def test_minimal_returns_web_only(self):- result = sample_toolsets_from_distribution("minimal")- assert "web" in result-- def test_returns_list_of_strings(self):- result = sample_toolsets_from_distribution("balanced")- assert isinstance(result, list)- for item in result:- assert isinstance(item, str)@@ -89,7 +64,7 @@ class TestGroupedCompoundEntries:result = sample_toolsets_from_distribution("_test_compound_fallback")assert set(result) == {"browser", "search"}- def test_invalid_member_skips_whole_entry(self, monkeypatch, capsys):+ def test_invalid_member_skips_whole_entry(self, monkeypatch):import toolset_distributions as tdmonkeypatch.setitem(@@ -101,4 +76,3 @@ class TestGroupedCompoundEntries:result = sample_toolsets_from_distribution("_test_compound_invalid")assert "browser" not in result # invalid member disqualifies the groupassert "web" in result- assert "not valid" in capsys.readouterr().outdiff --git a/tests/tools/test_toolsets.py b/tests/tools/test_toolsets.pyindex d716c696d6d..a9cb57e7771 100644--- a/tests/tools/test_toolsets.py+++ b/tests/tools/test_toolsets.py@@ -26,19 +26,7 @@ def _make_schema(name: str, description: str = "test tool"):class TestGetToolset:- def test_known_toolset(self):- ts = get_toolset("web")- assert ts is not None- assert "web_search" in ts["tools"]- def test_x_search_toolset_marks_read_only_and_points_to_xurl(self):- ts = get_toolset("x_search")- assert ts is not None- assert ts["tools"] == ["x_search"]- description = ts["description"].lower()- assert "read-only" in description- assert "xurl" in description- assert "authenticated" in descriptiondef test_merges_registry_tools_into_builtin_toolset(self, monkeypatch):reg = ToolRegistry()@@ -53,7 +41,7 @@ class TestGetToolset:ts = get_toolset("web")assert ts is not None- assert set(ts["tools"]) == {"web_search", "web_extract", "web_search_plus"}+ assert {"web_search", "web_search_plus"} <= set(ts["tools"])def test_static_and_mcp_alias_with_same_name_are_merged(self, monkeypatch):@@ -76,15 +64,7 @@ class TestGetToolset:class TestResolveToolset:- def test_leaf_toolset(self):- tools = resolve_toolset("web")- assert set(tools) == {"web_search", "web_extract"}- def test_composite_toolset(self):- tools = resolve_toolset("debugging")- assert "terminal" in tools- assert "web_search" in tools- assert "web_extract" in toolsdef test_cycle_detection(self):# Create a cycle: A includes B, B includes A@@ -123,20 +103,9 @@ class TestResolveToolset:-class TestResolveToolsetComposition:- def test_union_over_names_combines_and_deduplicates(self):- tools = sorted({t for name in ("web", "terminal") for t in resolve_toolset(name)})- assert "web_search" in tools- assert "web_extract" in tools- assert "terminal" in tools- # No duplicates- assert len(tools) == len(set(tools))class TestValidateToolset:- def test_valid(self):- assert validate_toolset("web") is True- assert validate_toolset("terminal") is Truedef test_invalid(self):@@ -160,11 +129,6 @@ class TestValidateToolset:class TestGetToolsetInfo:- def test_leaf(self):- info = get_toolset_info("web")- assert info["name"] == "web"- assert info["is_composite"] is False- assert info["tool_count"] == 2def test_composite(self):info = get_toolset_info("debugging")@@ -217,23 +181,6 @@ class TestToolsetConsistency:assert "includes" in ts, f"{name} missing includes"- def test_hermes_platforms_share_core_tools(self):- """All hermes-* platform toolsets share the same core tools.-- Platform-specific additions (e.g. ``discord`` / ``discord_admin``- on hermes-discord, gated on DISCORD_BOT_TOKEN) are allowed on top —- the invariant is that the core set is identical across platforms.- """- platforms = ["hermes-cli", "hermes-telegram", "hermes-discord", "hermes-whatsapp", "hermes-slack", "hermes-signal", "hermes-homeassistant"]- tool_sets = [set(TOOLSETS[p]["tools"]) for p in platforms]- # All platforms must contain the shared core; platform-specific- # extras are OK (subset check, not equality).- core = set.intersection(*tool_sets)- for name, ts in zip(platforms, tool_sets):- assert core.issubset(ts), f"{name} is missing core tools: {core - ts}"- # Sanity: the shared core must be non-trivial (i.e. we didn't- # silently let a platform diverge so far that nothing is shared).- assert len(core) > 20, f"Suspiciously small shared core: {len(core)} tools"class TestPluginToolsets:@@ -253,9 +200,6 @@ class TestPluginToolsets:assert all_toolsets["plugin_bundle"]["tools"] == ["plugin_tool"]-class TestDefaultPlatformWebSearchCoverage:- def test_hermes_whatsapp_toolset_includes_web_search(self):- assert "web_search" in resolve_toolset("hermes-whatsapp")@@ -282,7 +226,7 @@ class TestResolveToolsetIncludeRegistry:finally:registry.deregister("__probe_registry_only_tool__")- assert static == {"terminal", "process_manage"}, static+ assert "terminal" in static, static# Registered into 'terminal' but not part of the static definition — it# must only appear in the merged view.assert "__probe_registry_only_tool__" in merged@@ -304,41 +248,6 @@ class TestResolveToolsetIncludeRegistry:class TestResolveToolsetMemo:"""Measured-work pins for the generation-keyed resolution memo."""- def test_second_resolution_is_cached(self, monkeypatch):- """Repeated resolves of the same toolset must not re-walk the registry.-- resolve_toolset is called dozens of times per _get_platform_tools()- (every /tools completion keystroke). The memo keyed on the registry- generation makes repeat calls a dict lookup instead of a full- includes-walk + registry snapshot.- """- from tools.registry import registry-- toolsets_mod._resolve_toolset_memo.clear()- get_toolset_calls = {"n": 0}-- orig_get_toolset = toolsets_mod.get_toolset-- def counting_get_toolset(name, *, include_registry=True):- get_toolset_calls["n"] += 1- return orig_get_toolset(name, include_registry=include_registry)-- monkeypatch.setattr(toolsets_mod, "get_toolset", counting_get_toolset)-- registry_id = id(registry)- generation = registry._generation-- first = resolve_toolset("hermes-cli")- second = resolve_toolset("hermes-cli")-- assert first == second- assert get_toolset_calls["n"] == 1, (- "second resolution must be a memo hit (no get_toolset re-walk), "- f"got {get_toolset_calls['n']} calls"- )- assert (- "hermes-cli", True, registry_id, generation, registry.current_scope_key()- ) in toolsets_mod._resolve_toolset_memodef test_generation_bump_invalidates_memo(self, monkeypatch):"""A registry mutation (generation bump) must force a fresh resolve."""@@ -365,11 +274,4 @@ class TestResolveToolsetMemo:"generation bump must invalidate the memo and re-resolve")- def test_memo_result_matches_fresh_resolution(self):- """The memo must never change the resolved result."""- toolsets_mod._resolve_toolset_memo.clear()- first = resolve_toolset("hermes-cli", include_registry=False)- second = resolve_toolset("hermes-cli", include_registry=False)- assert first == second- assert first # non-empty sanitydiff --git a/tests/tools/test_tour_tool.py b/tests/tools/test_tour_tool.pyindex 1cd2196cc37..c0d946fcd02 100644--- a/tests/tools/test_tour_tool.py+++ b/tests/tools/test_tour_tool.py@@ -3,7 +3,6 @@import jsonfrom tools import tour_tool as tt-from tools.registry import registrydef _run(**kwargs):@@ -11,23 +10,9 @@ def _run(**kwargs):return json.loads(tt.tour_tool(**kwargs))-def test_lives_in_the_gui_surface_toolset(monkeypatch):- """Scoped by toolset, not by the backend's env — see AGENTS.md."""- monkeypatch.delenv("HERMES_DESKTOP", raising=False)- entry = registry.get_entry("gui_tour")- assert entry is not None- assert entry.toolset == "desktop_ui"-def test_answers_to_the_appearance_switch():- """Tours off has to mean the model never sees the tool. See- tests/tools/test_display_toggles.py for the config end of it."""- entry = registry.get_entry("gui_tour")-- assert entry is not None- assert entry.check_fn is tt.check_tours_enabled-def test_requires_callback():"""Outside the desktop GUI there is no bridge — a clear error, no crash."""diff --git a/tests/tools/test_transcription.py b/tests/tools/test_transcription.pyindex f1bd8fab71c..d7836dd2ca1 100644--- a/tests/tools/test_transcription.py+++ b/tests/tools/test_transcription.py@@ -103,7 +103,7 @@ class TestLoadSttConfig:local_config = _load_stt_config()["local"]assert local_config["model"] == "small"- assert local_config["initial_prompt"] == ""+ assert "initial_prompt" in local_config# ---------------------------------------------------------------------------@@ -187,18 +187,6 @@ class TestTranscribeOpenAI:class TestTranscribeAudio:- def test_dispatches_to_local(self, tmp_path):- audio_file = tmp_path / "test.ogg"- audio_file.write_bytes(b"fake audio")-- with patch("tools.transcription_tools._load_stt_config", return_value={"provider": "local"}), \- patch("tools.transcription_tools._get_provider", return_value="local"), \- patch("tools.transcription_tools._transcribe_local", return_value={"success": True, "transcript": "hi"}) as mock_local:- from tools.transcription_tools import transcribe_audio- result = transcribe_audio(str(audio_file))-- assert result["success"] is True- mock_local.assert_called_once()def test_invalid_file_returns_error(self):@@ -254,9 +242,6 @@ class TestLocalFallback:class TestNormalizeLocalModel:"""_normalize_local_model() maps cloud-only names to the local default."""- def test_openai_model_name_maps_to_default(self):- from tools.transcription_tools import _normalize_local_model, DEFAULT_LOCAL_MODEL- assert _normalize_local_model("whisper-1") == DEFAULT_LOCAL_MODELdef test_local_transcribe_normalises_model(self):diff --git a/tests/tools/test_transcription_command_providers.py b/tests/tools/test_transcription_command_providers.pyindex 99b4eca5aa2..831d350972e 100644--- a/tests/tools/test_transcription_command_providers.py+++ b/tests/tools/test_transcription_command_providers.py@@ -18,7 +18,6 @@ identically on Linux, macOS, and Windows (with minor quoting differences).from __future__ import annotations-import osimport sysimport wavefrom pathlib import Path@@ -27,7 +26,6 @@ from unittest.mock import patchfrom tools.transcription_common import BUILTIN_STT_PROVIDERSfrom tools.transcription_command import (- COMMAND_STT_OUTPUT_FORMATS,DEFAULT_COMMAND_STT_LANGUAGE,DEFAULT_COMMAND_STT_OUTPUT_FORMAT,DEFAULT_COMMAND_STT_TIMEOUT_SECONDS,@@ -142,7 +140,6 @@ class TestSTTCommandHelpers:def test_output_format_defaults_to_txt(self):assert _get_command_stt_output_format({}) == DEFAULT_COMMAND_STT_OUTPUT_FORMAT- assert DEFAULT_COMMAND_STT_OUTPUT_FORMAT == "txt"# ---------------------------------------------------------------------------diff --git a/tests/tools/test_transcription_plugin_dispatch.py b/tests/tools/test_transcription_plugin_dispatch.pyindex 979da40b6d8..0f780250730 100644--- a/tests/tools/test_transcription_plugin_dispatch.py+++ b/tests/tools/test_transcription_plugin_dispatch.py@@ -79,34 +79,6 @@ def sample_audio_file(tmp_path):# ----------------------------------------------------------------------------class TestBuiltinAlwaysWins:- """Built-in STT provider names short-circuit the dispatcher.-- Even with a plugin registered (which the registry would reject —- but the dispatcher is defensive), built-in names return None so- the caller's elif chain handles them natively.- """-- @pytest.mark.parametrize(- "builtin",- ["local", "local_command", "groq", "openai", "mistral", "xai"],- )- def test_dispatcher_short_circuits_builtin(self, builtin):- result = transcription_tools._dispatch_to_plugin_provider(- "/tmp/audio.mp3", builtin,- )- assert result is None, (- f"Built-in {builtin!r} must short-circuit plugin dispatch."- )--- def test_dispatcher_short_circuits_builtin_case_insensitive(self):- for variant in ("OPENAI", "OpenAI", " openai ", "oPeNaI"):- assert (- transcription_tools._dispatch_to_plugin_provider(- "/tmp/audio.mp3", variant,- ) is None- )# ---------------------------------------------------------------------------diff --git a/tests/tools/test_transcription_tools.py b/tests/tools/test_transcription_tools.pyindex 0fd891cc7e6..d0e087d9cde 100644--- a/tests/tools/test_transcription_tools.py+++ b/tests/tools/test_transcription_tools.py@@ -54,14 +54,6 @@ def sample_ogg(tmp_path):ogg_path.write_bytes(b"fake audio data")return str(ogg_path)-def sample_silk(tmp_path):- """Create a fake WeChat .silk file for preprocessing tests."""- silk_path = tmp_path / "voice.silk"- silk_path.write_bytes(b"\x02#!SILK_V3fake")- return str(silk_path)--@pytest.fixturedef oversized_wav(tmp_path):"""Create a sparse WAV-shaped file just above the remote upload cap."""@@ -156,18 +148,6 @@ class TestExplicitProviderRespected:"""When stt.provider is explicitly set, that choice is authoritative.No silent fallback to a different cloud provider."""- def test_explicit_local_no_fallback_to_openai(self, monkeypatch):- """GH-1774: provider=local must not silently fall back to openai- even when an OpenAI API key is set."""- monkeypatch.setenv("OPENAI_API_KEY", "***")- monkeypatch.delenv("GROQ_API_KEY", raising=False)- with patch("tools.transcription_tools._HAS_FASTER_WHISPER", False), \- patch("tools.transcription_tools._has_local_command", return_value=False), \- patch("tools.tool_backend_helpers.read_selection", return_value="local"), \- patch("tools.transcription_tools._HAS_OPENAI", True):- from tools.transcription_tools import _get_provider- result = _get_provider({"provider": "local"})- assert result == "none", f"Expected 'none' but got {result!r}"def test_seeded_local_without_stored_selection_autodetects(self, monkeypatch):"""The DEFAULT_CONFIG-seeded stt.provider: local (no raw-config@@ -229,7 +209,7 @@ class TestTranscribeGroq:class TestOpenAIClientConfig:@pytest.mark.parametrize(("openai_config", "expected_timeout", "expected_retries"),- [({}, 60, 1), ({"timeout": 95, "max_retries": 3}, 95, 3)],+ [({"timeout": 95, "max_retries": 3}, 95, 3)],)def test_stt_openai_config_controls_sdk_client(self, monkeypatch, tmp_path, sample_wav, openai_config, expected_timeout, expected_retries@@ -683,13 +663,6 @@ class TestValidateAudioFileEdgeCases:assert "symbolic link" in result["error"]- def test_all_supported_formats_accepted(self, tmp_path):- from tools.transcription_tools import _validate_audio_file- from tools.transcription_common import SUPPORTED_FORMATS- for fmt in SUPPORTED_FORMATS:- f = tmp_path / f"test{fmt}"- f.write_bytes(b"data")- assert _validate_audio_file(str(f)) is None, f"Format {fmt} should be accepted"# ============================================================================# transcribe_audio — end-to-end dispatch@@ -716,8 +689,6 @@ class TestTranscribeAudioDispatch:assert result["success"] is Falseassert "No STT provider" in result["error"]- assert "faster-whisper" in result["error"]- assert "GROQ_API_KEY" in result["error"]def test_silk_symlink_is_rejected_before_preprocessing(self, tmp_path):@@ -1012,16 +983,6 @@ class TestGetProviderXAI:# transcribe_audio — xAI dispatch# ============================================================================-class TestTranscribeAudioXAIDispatch:- def test_model_default_is_grok_stt(self, sample_ogg):- with patch("tools.transcription_tools._load_stt_config", return_value={"provider": "xai"}), \- patch("tools.transcription_tools._get_provider", return_value="xai"), \- patch("tools.transcription_tools._transcribe_xai",- return_value={"success": True, "transcript": "hi"}) as mock_xai:- from tools.transcription_tools import transcribe_audio- transcribe_audio(sample_ogg, model=None)-- assert mock_xai.call_args[0][1] == "grok-stt"# ============================================================================# _transcribe_elevenlabs@@ -1146,7 +1107,6 @@ class TestShellSafety:def test_env_var_template_metacharacters_are_literal_argv(self, monkeypatch, sample_wav, tmp_path):- from hermes_cli._subprocess_compat import windows_hide_flagsfrom tools.transcription_tools import (LOCAL_STT_COMMAND_ENV,_transcribe_local_command,@@ -1204,17 +1164,8 @@ class TestShellSafety:"--output_dir",str(output_dir),]- assert invocation["kwargs"].pop("env") is not None- assert invocation["kwargs"] == {- "check": True,- "capture_output": True,- "text": True,- "encoding": "utf-8",- "errors": "replace",- "timeout": 300,- "stdin": subprocess.DEVNULL,- "creationflags": windows_hide_flags(),- }+ assert invocation["kwargs"].get("env") is not None+ assert not invocation["kwargs"].get("shell")class TestLocalModelLock:@@ -1273,7 +1224,7 @@ class TestLocalBaseUrlNoApiKey:return_value={"openai": {"base_url": "http://localhost:8504/v1"}},):api_key, base_url = _resolve_openai_audio_client_config()- assert api_key == "not-needed"+ assert api_key # non-empty placeholder so the SDK client does not raiseassert base_url == "http://localhost:8504/v1"@@ -1452,33 +1403,6 @@ class TestRunCommandSttIdleTimeout:assert "tick 8" in result.stderrassert "done" in result.stdout- def test_silent_stall_still_times_out(self, tmp_path):- """A silently stalled command is killed once the idle window elapses,- and pre-stall output is preserved on the TimeoutExpired."""- from tools.transcription_command import _run_command_stt-- script = tmp_path / "progress_then_hang.py"- script.write_text(- "\n".join([- "import sys, time",- "print('starting pass 1', file=sys.stderr, flush=True)",- "time.sleep(30)",- ]),- encoding="utf-8",- )-- # Same budget rule as the progress test above: the idle window must- # comfortably exceed process spawn latency on a loaded runner, or the- # child is killed before its first stderr line is ever read and the- # pre-stall-output assertion fails spuriously. 30s of silence still- # trips a 0.25s window by a wide margin.- with pytest.raises(subprocess.TimeoutExpired) as excinfo:- _run_command_stt(- self._shell_command(sys.executable, "-u", str(script)),- timeout=0.25,- )-- assert "starting pass 1" in (excinfo.value.stderr or "")# ============================================================================@@ -1508,29 +1432,6 @@ class TestExplicitOpenaiSelectionError:lambda vendor: None,)- def test_get_provider_openai_none_not_generic_when_managed_route_down(- self, monkeypatch, caplog- ):- self._no_openai_credentials(monkeypatch)- monkeypatch.setattr(- "tools.tool_backend_helpers.managed_nous_tools_enabled", lambda: True- )- monkeypatch.setattr(- "tools.transcription_tools._load_stt_config", lambda: {}- )- with patch("tools.transcription_tools._HAS_OPENAI", True), \- patch("tools.transcription_tools._HAS_FASTER_WHISPER", False):- from tools.transcription_tools import _get_provider-- with caplog.at_level("WARNING"):- result = _get_provider({"provider": "openai"})-- assert result == "none"- warning = caplog.records[-1].getMessage()- assert "unavailable" in warning- # The selection-specific blocker is named, not a bare API-key hint.- assert "managed" in warning or "gateway" in warning- assert "no API key available" not in warningdef test_dispatch_returns_selection_specific_error(self, monkeypatch):"""The final transcription result carries the managed-route error anddiff --git a/tests/tools/test_tts_command_providers.py b/tests/tools/test_tts_command_providers.pyindex 9e1e24c229b..b5df1ad0cd3 100644--- a/tests/tools/test_tts_command_providers.py+++ b/tests/tools/test_tts_command_providers.py@@ -23,7 +23,6 @@ from unittest.mock import patchimport pytestfrom tools.tts_command_provider import (- COMMAND_TTS_OUTPUT_FORMATS,DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH,DEFAULT_COMMAND_TTS_OUTPUT_FORMAT,DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS,@@ -39,7 +38,6 @@ from tools.tts_tool import (BUILTIN_TTS_PROVIDERS,_generate_command_tts,_get_command_tts_output_format,- _is_command_tts_voice_compatible,_resolve_command_provider_config,_resolve_max_text_length,check_tts_requirements,@@ -160,8 +158,6 @@ class TestGetNamedProviderConfig:class TestIsCommandProviderConfig:- def test_empty_dict_is_false(self):- assert _is_command_provider_config({}) is Falsedef test_type_mismatch_is_false(self):@@ -199,13 +195,8 @@ class TestConfigGetters:assert _get_command_tts_output_format({}) == DEFAULT_COMMAND_TTS_OUTPUT_FORMAT- def test_voice_compatible_boolean(self):- assert _is_command_tts_voice_compatible({"voice_compatible": True}) is True- assert _is_command_tts_voice_compatible({"voice_compatible": False}) is False- def test_voice_compatible_default_off(self):- assert _is_command_tts_voice_compatible({}) is False# ---------------------------------------------------------------------------@@ -319,38 +310,6 @@ class TestRenderCommandTtsTemplate:# ---------------------------------------------------------------------------class TestRunCommandTts:- def test_reads_process_output_in_large_chunks(self):- read_sizes: dict[str, list[int]] = {"stdout": [], "stderr": []}-- class FakeStream:- def __init__(self, name: str, chunks: list[str]):- self.name = name- self.chunks = chunks-- def read(self, size: int) -> str:- read_sizes[self.name].append(size)- if self.chunks:- return self.chunks.pop(0)- return ""-- class FakeProcess:- def __init__(self):- self.pid = 12345- self.returncode = 0- self.stdout = FakeStream("stdout", ["done"])- self.stderr = FakeStream("stderr", ["tick"])-- def wait(self, timeout=None):- return self.returncode-- with patch("tools.tts_command_provider.subprocess.Popen", return_value=FakeProcess()):- result = _run_command_tts("fake tts", timeout=0.25)-- assert result.returncode == 0- assert result.stdout == "done"- assert result.stderr == "tick"- assert read_sizes["stdout"][0] == 65536- assert read_sizes["stderr"][0] == 65536def test_silent_after_progress_still_times_out_with_stderr(self, tmp_path):diff --git a/tests/tools/test_tts_container_repair.py b/tests/tools/test_tts_container_repair.pyindex 35c266efc42..d5a100fcf14 100644--- a/tests/tools/test_tts_container_repair.py+++ b/tests/tools/test_tts_container_repair.py@@ -12,7 +12,6 @@ bytes once after synthesis and repairs the container centrally."""import struct-from unittest.mock import patchimport pytest@@ -90,6 +89,3 @@ class TestOpusPlatformSet:for platform in ("telegram", "matrix", "feishu", "whatsapp", "signal"):assert platform in OPUS_VOICE_PLATFORMS- def test_cli_not_included(self):- assert "" not in OPUS_VOICE_PLATFORMS- assert "cli" not in OPUS_VOICE_PLATFORMSdiff --git a/tests/tools/test_tts_gemini.py b/tests/tools/test_tts_gemini.pyindex dc096983e09..6a1df6f3810 100644--- a/tests/tools/test_tts_gemini.py+++ b/tests/tools/test_tts_gemini.py@@ -2,7 +2,6 @@import base64import struct-from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest@@ -70,12 +69,6 @@ class TestWrapPcmAsWav:assert wav[36:40] == b"data"assert wav[44:] == pcm- def test_header_size_is_44(self):- from tools.tts_tool_delivery import _wrap_pcm_as_wav-- pcm = b"\xff" * 100- wav = _wrap_pcm_as_wav(pcm)- assert len(wav) == 44 + len(pcm)class TestGenerateGeminiTts:diff --git a/tests/tools/test_tts_instructions.py b/tests/tools/test_tts_instructions.pyindex de4333cc88a..ae24961b872 100644--- a/tests/tools/test_tts_instructions.py+++ b/tests/tools/test_tts_instructions.py@@ -40,10 +40,6 @@ class TestOpenaiBackendInstructions:)return mock_client.audio.speech.create- def test_instructions_forwarded_when_provided(self, tmp_path, monkeypatch):- """Tool arg `instructions` is passed to audio.speech.create as-is."""- create = self._run(tmp_path, monkeypatch, instructions="Speak cheerfully.")- assert create.call_args[1]["instructions"] == "Speak cheerfully."def test_empty_string_instructions_omitted(self, tmp_path, monkeypatch):@@ -106,11 +102,3 @@ class TestToolLevelInstructions:# Schema# ----------------------------------------------------------------------------class TestSchema:- def test_schema_exposes_instructions_parameter(self):- from tools.tts_tool import TTS_SCHEMA- props = TTS_SCHEMA["parameters"]["properties"]- assert "instructions" in props- assert props["instructions"]["type"] == "string"- # Must stay optional — current behavior must be preserved.- assert "instructions" not in TTS_SCHEMA["parameters"].get("required", [])diff --git a/tests/tools/test_tts_kittentts.py b/tests/tools/test_tts_kittentts.pyindex 44fd7cc41cb..bd7e4902dfe 100644--- a/tests/tools/test_tts_kittentts.py+++ b/tests/tools/test_tts_kittentts.py@@ -80,34 +80,8 @@ class TestGenerateKittenTts:assert call_kwargs["clean_text"] is False- def test_missing_kittentts_raises_import_error(self, tmp_path, monkeypatch):- """When kittentts package is not installed, _import_kittentts raises."""- import sys- monkeypatch.setitem(sys.modules, "kittentts", None)- from tools.tts_tool import _generate_kittentts-- with pytest.raises((ImportError, TypeError)):- _generate_kittentts("Hi", str(tmp_path / "out.wav"), {})---class TestCheckKittenttsAvailable:- def test_reports_available_when_package_present(self, monkeypatch):- import importlib.util- from tools.tts_tool import _check_kittentts_available-- fake_spec = MagicMock()- monkeypatch.setattr(- importlib.util, "find_spec",- lambda name: fake_spec if name == "kittentts" else None,- )- assert _check_kittentts_available() is True- def test_reports_unavailable_when_package_missing(self, monkeypatch):- import importlib.util- from tools.tts_tool import _check_kittentts_available- monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)- assert _check_kittentts_available() is Falseclass TestDispatcherBranch:@@ -128,4 +102,3 @@ class TestDispatcherBranch:result = json.loads(text_to_speech_tool(text="Hello"))assert result["success"] is Falseassert "kittentts" in result["error"].lower()- assert "hermes setup tts" in result["error"].lower()diff --git a/tests/tools/test_tts_long_form_chunking.py b/tests/tools/test_tts_long_form_chunking.pyindex 81d9c4c3d8a..1c0714bc9ba 100644--- a/tests/tools/test_tts_long_form_chunking.py+++ b/tests/tools/test_tts_long_form_chunking.py@@ -5,17 +5,12 @@ content loss, that chunks are synthesized in order, and that the deliverypacking respects platform upload limits."""-import json-import os-from pathlib import Path-from unittest.mock import patchimport pytestfrom tools.tts_tool import _build_audio_delivery_files, _split_text_for_ttsfrom tools.tts_tool_delivery import (AudioDeliveryProfile,- _concat_audio_files,_pack_audio_files_for_delivery,_split_oversized_sentence,)@@ -56,11 +51,6 @@ class TestSplitOversizedSentence:def test_short_sentence_returns_as_is(self):assert _split_oversized_sentence("Hello world.", 100) == ["Hello world."]- def test_long_word_is_hard_split(self):- word = "A" * 100- chunks = _split_oversized_sentence(word, 30)- assert all(len(c) <= 30 for c in chunks)- assert "".join(chunks) == worddef test_word_boundary_split(self):words = " ".join(["word"] * 50)@@ -68,17 +58,6 @@ class TestSplitOversizedSentence:assert all(len(c) <= 30 for c in chunks)-class TestAudioDeliveryProfile:- def test_default_profile(self):- profile = AudioDeliveryProfile(platform="default", max_file_bytes=10 * 1024 * 1024)- assert profile.target_file_bytes > 0- assert profile.target_file_bytes < profile.max_file_bytes-- def test_custom_safety_ratio(self):- profile = AudioDeliveryProfile(- platform="custom", max_file_bytes=1000, safety_ratio=0.5- )- assert profile.target_file_bytes == 500class TestPackAudioFilesForDelivery:@@ -131,19 +110,3 @@ class TestBuildAudioDeliveryFiles:with pytest.raises(ValueError, match="exceeds"):_build_audio_delivery_files([str(f)], out, profile)- def test_combines_multiple_files(self, tmp_path):- files = []- for i in range(3):- f = tmp_path / f"chunk{i:02d}.mp3"- f.write_bytes(b"\x00" * 100)- files.append(str(f))- out = str(tmp_path / "output.mp3")- profile = AudioDeliveryProfile(platform="default", max_file_bytes=10000)-- with patch("tools.tts_tool_delivery._concat_audio_files") as mock_concat:- mock_concat.return_value = out- # Copy the first file to output so the size check passes- Path(out).write_bytes(b"\x00" * 300)- paths, combined = _build_audio_delivery_files(files, out, profile)- assert len(paths) == 1- assert combined is Truediff --git a/tests/tools/test_tts_max_text_length.py b/tests/tools/test_tts_max_text_length.pyindex 46b8394295d..ec4af886558 100644--- a/tests/tools/test_tts_max_text_length.py+++ b/tests/tools/test_tts_max_text_length.py@@ -9,27 +9,15 @@ import jsonfrom tools.tts_tool import _resolve_max_text_length-from tools.tts_tool_delivery import FALLBACK_MAX_TEXT_LENGTH, PROVIDER_MAX_TEXT_LENGTH+from tools.tts_tool_delivery import FALLBACK_MAX_TEXT_LENGTHclass TestResolveMaxTextLength:- def test_edge_default(self):- assert _resolve_max_text_length("edge", {}) == PROVIDER_MAX_TEXT_LENGTH["edge"]- def test_openai_default_is_4096(self):- assert _resolve_max_text_length("openai", {}) == 4096- def test_xai_default_is_15000(self):- assert _resolve_max_text_length("xai", {}) == 15000- def test_minimax_default_is_10000(self):- assert _resolve_max_text_length("minimax", {}) == 10000- def test_mistral_default(self):- assert _resolve_max_text_length("mistral", {}) == PROVIDER_MAX_TEXT_LENGTH["mistral"]- def test_gemini_default(self):- assert _resolve_max_text_length("gemini", {}) == PROVIDER_MAX_TEXT_LENGTH["gemini"]def test_unknown_provider_falls_back(self):assert _resolve_max_text_length("does-not-exist", {}) == FALLBACK_MAX_TEXT_LENGTH@@ -47,10 +35,6 @@ class TestResolveMaxTextLength:# --- Sanity: the table covers every provider listed in the schema ---- def test_all_documented_providers_have_defaults(self):- expected = {"edge", "openai", "xai", "minimax", "mistral",- "gemini", "elevenlabs", "neutts", "kittentts"}- assert expected.issubset(PROVIDER_MAX_TEXT_LENGTH.keys())class TestTextToSpeechToolChunking:diff --git a/tests/tools/test_tts_openai_config.py b/tests/tools/test_tts_openai_config.pyindex 7ab2861de68..989dfb91a80 100644--- a/tests/tools/test_tts_openai_config.py+++ b/tests/tools/test_tts_openai_config.py@@ -76,7 +76,6 @@ class TestResolveOpenaiAudioClientConfig:with pytest.raises(ValueError) as exc:tts_tool_openai._resolve_openai_audio_client_config()assert "nous" in str(exc.value)- assert "hermes tools" in str(exc.value)def test_vendor_selection_missing_key_raises_selection_error(self):"""A stored vendor selection with no credentials errors by name —@@ -89,7 +88,6 @@ class TestResolveOpenaiAudioClientConfig:tts_tool_openai._resolve_openai_audio_client_config()gateway_mock.assert_not_called()assert "openai" in str(exc.value)- assert "hermes tools" in str(exc.value)def test_missing_config_and_env_raises_updated_error(self):with patch.object(tts_tool, "_load_tts_config", return_value={}), \@@ -100,10 +98,7 @@ class TestResolveOpenaiAudioClientConfig:with pytest.raises(ValueError) as exc:tts_tool_openai._resolve_openai_audio_client_config()- assert (- str(exc.value)- == "Neither tts.openai.api_key in config nor VOICE_TOOLS_OPENAI_KEY/OPENAI_API_KEY is set"- )+ assert "OPENAI_API_KEY" in str(exc.value)def test_config_api_key_counts_as_available_backend(self):config = {"openai": {"api_key": "cfg-key"}}diff --git a/tests/tools/test_tts_output_dir_profile_scope.py b/tests/tools/test_tts_output_dir_profile_scope.pyindex 264718e20d3..5e4bbc9f22d 100644--- a/tests/tools/test_tts_output_dir_profile_scope.py+++ b/tests/tools/test_tts_output_dir_profile_scope.py@@ -47,14 +47,3 @@ def test_default_output_dir_follows_contextvar_profile_override(tmp_path, monkeyassert tts_tool._default_output_dir() == str(default_home / "cache" / "audio")-def test_explicit_default_output_dir_monkeypatch_still_wins(tmp_path, monkeypatch):- """Existing tests and external patchers can still override- tools.tts_tool.DEFAULT_OUTPUT_DIR directly."""- default_home = tmp_path / "default-home"- default_home.mkdir(parents=True)-- tts_tool = _reload_tts_tool(default_home, monkeypatch)-- monkeypatch.setattr(tts_tool, "DEFAULT_OUTPUT_DIR", "/custom/audio")-- assert tts_tool._default_output_dir() == "/custom/audio"diff --git a/tests/tools/test_tts_output_timestamp.py b/tests/tools/test_tts_output_timestamp.pydeleted file mode 100644index 33e391b1259..00000000000--- a/tests/tools/test_tts_output_timestamp.py+++ /dev/null@@ -1,29 +0,0 @@-"""Regression test for salvaged PR #43911 — microsecond TTS output timestamps.--Default output paths used second-resolution ``%Y%m%d_%H%M%S`` timestamps, so-two text_to_speech_tool calls landing in the same wall-clock second produced-the same filename and the second synthesis overwrote the first. The format-now appends ``%f`` (microseconds).-"""--import datetime-import re---class TestDefaultOutputTimestampResolution:- def test_default_output_path_uses_microsecond_timestamp(self):- """The source must build default filenames with a %f component."""- import inspect-- from tools import tts_tool-- src = inspect.getsource(tts_tool._resolve_output_base)- assert "%Y%m%d_%H%M%S_%f" in src, (- "default TTS output timestamp lost its microsecond component — "- "concurrent calls in the same second would collide again (#43911)"- )--- def test_timestamp_component_is_filename_safe(self):- stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")- assert re.fullmatch(r"\d{8}_\d{6}_\d{6}", stamp)diff --git a/tests/tools/test_tts_piper.py b/tests/tools/test_tts_piper.pyindex d4dfea03a65..4fea5cbb406 100644--- a/tests/tools/test_tts_piper.py+++ b/tests/tools/test_tts_piper.py@@ -10,18 +10,15 @@ import jsonimport sysimport typesfrom pathlib import Path-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockimport pytestfrom tools import tts_tool, tts_tool_localfrom tools.tts_tool import (- BUILTIN_TTS_PROVIDERS,- _check_piper_available,check_tts_requirements,text_to_speech_tool,)-from tools.tts_tool_delivery import PROVIDER_MAX_TEXT_LENGTHfrom tools.tts_tool_local import DEFAULT_PIPER_VOICE, _resolve_piper_voice_path@@ -29,23 +26,12 @@ from tools.tts_tool_local import DEFAULT_PIPER_VOICE, _resolve_piper_voice_path# Registry / constants# ----------------------------------------------------------------------------class TestPiperRegistration:- def test_piper_is_a_builtin_provider(self):- assert "piper" in BUILTIN_TTS_PROVIDERS-- def test_piper_has_a_text_length_cap(self):- assert PROVIDER_MAX_TEXT_LENGTH.get("piper", 0) > 0# ---------------------------------------------------------------------------# _check_piper_available# ----------------------------------------------------------------------------class TestCheckPiperAvailable:- def test_returns_bool_without_raising(self):- # We don't care about the current environment's answer — just that- # the probe never raises on a machine without piper installed.- assert isinstance(_check_piper_available(), bool)# ---------------------------------------------------------------------------diff --git a/tests/tools/test_tts_plugin_dispatch.py b/tests/tools/test_tts_plugin_dispatch.pyindex 3798995d5d9..cdd8a316fed 100644--- a/tests/tools/test_tts_plugin_dispatch.py+++ b/tests/tools/test_tts_plugin_dispatch.py@@ -91,12 +91,12 @@ class TestBuiltinAlwaysWins:the caller's elif chain handles them natively."""- @pytest.mark.parametrize(- "builtin",- ["edge", "openai", "elevenlabs", "minimax", "gemini",- "mistral", "xai", "piper", "kittentts", "neutts"],- )- def test_dispatcher_short_circuits_builtin(self, builtin):+ def test_dispatcher_short_circuits_builtin(self):+ assert tts_tool.BUILTIN_TTS_PROVIDERS+ for builtin in tts_tool.BUILTIN_TTS_PROVIDERS:+ self._assert_short_circuits(builtin)++ def _assert_short_circuits(self, builtin):result = tts_tool._dispatch_to_plugin_provider(text="hello",output_path="/tmp/out.mp3",diff --git a/tests/tools/test_tts_provider_base_urls.py b/tests/tools/test_tts_provider_base_urls.pydeleted file mode 100644index 16764854e5a..00000000000--- a/tests/tools/test_tts_provider_base_urls.py+++ /dev/null@@ -1,68 +0,0 @@-"""Class-level base_url parity: every cloud TTS provider honors config base_url.--xAI, MiniMax, Gemini, OpenAI and DeepInfra already read-``tts.<provider>.base_url`` from config.yaml. This locks in the same-contract for the ElevenLabs and Mistral sections (the two that used to-hardcode the SDK default endpoint).-"""-from __future__ import annotations--import sys-import types-from unittest.mock import patch--import tools.tts_tool as tts---# ── ElevenLabs: base_url/wss_url → ElevenLabsEnvironment ──────────────────---def _fake_elevenlabs_environment_module(captured: dict):- mod = types.ModuleType("elevenlabs.environment")-- class ElevenLabsEnvironment:- def __init__(self, base, wss):- captured["base"] = base- captured["wss"] = wss-- mod.ElevenLabsEnvironment = ElevenLabsEnvironment- pkg = types.ModuleType("elevenlabs")- pkg.environment = mod- return pkg, mod---def test_elevenlabs_no_base_url_uses_sdk_default_environment():- from tools.tts_tool_providers import _elevenlabs_environment_kwargs-- assert _elevenlabs_environment_kwargs({}) == {}- assert _elevenlabs_environment_kwargs({"base_url": ""}) == {}---# ── Mistral: tts.mistral.base_url → SDK server_url ────────────────────────---def test_mistral_no_base_url_omits_server_url(tmp_path):- captured: dict = {}-- class _FakeMistral:- def __init__(self, **kwargs):- captured.update(kwargs)-- def __enter__(self):- return self-- def __exit__(self, *args):- return False-- class audio: # noqa: N801- class speech: # noqa: N801- @staticmethod- def complete(**kwargs):- return types.SimpleNamespace(audio_data="aGVsbG8=")-- out = tmp_path / "out.mp3"- with patch.object(tts, "_import_mistral_client", return_value=_FakeMistral), \- patch("hermes_cli.config.get_env_value", lambda k, *a: "key" if k == "MISTRAL_API_KEY" else None):- tts._generate_mistral_tts("hi", str(out), {"mistral": {}})-- assert "server_url" not in captureddiff --git a/tests/tools/test_tts_speed.py b/tests/tools/test_tts_speed.pyindex 97ab7f0f7f8..026b2c7cf5b 100644--- a/tests/tools/test_tts_speed.py+++ b/tests/tools/test_tts_speed.py@@ -157,10 +157,9 @@ class TestMinimaxTtsT2aV2:"""Default endpoint uses nested voice_setting / audio_setting."""mock_post, _ = self._run({}, tmp_path, monkeypatch)payload = mock_post.call_args[1]["json"]- assert payload["model"] == "speech-02-hd"assert payload["text"] == "Hello"assert "voice_setting" in payload- assert payload["voice_setting"]["voice_id"] == "English_expressive_narrator"+ assert payload["voice_setting"]["voice_id"]assert "audio_setting" in payloadassert payload["audio_setting"]["format"] == "mp3"# Don't send flat top-level voice_id alongside nested voice_setting.diff --git a/tests/tools/test_tts_streaming.py b/tests/tools/test_tts_streaming.pyindex 4eff79d2b10..8bb9aefe027 100644--- a/tests/tools/test_tts_streaming.py+++ b/tests/tools/test_tts_streaming.py@@ -81,10 +81,6 @@ def _register_fake(monkeypatch, name, available=True, chunks=(b"\x00\x00",)):return _Fake-def test_resolve_returns_configured_streamer(monkeypatch):- _register_fake(monkeypatch, "faketts")- prov = ts.resolve_streaming_provider({"provider": "faketts"})- assert isinstance(prov, ts.StreamingTTSProvider)def test_never_swaps_provider_for_streaming(monkeypatch):@@ -221,16 +217,6 @@ def _sd_mock():# ── Credential routing: resolve_provider_secret, never bare env ──────────-def test_elevenlabs_available_routes_through_secret_resolver(monkeypatch):- calls = []-- def _fake_resolve(env_var, provider_id):- calls.append((env_var, provider_id))- return "pool-key"-- monkeypatch.setattr(ts, "_resolve_key", _fake_resolve)- assert ts.ElevenLabsStreamer.available() is True- assert ("ELEVENLABS_API_KEY", "elevenlabs") in callsdef test_xai_available_uses_oauth_credential_resolver(monkeypatch):@@ -531,41 +517,6 @@ def test_streamer_tempfile_fallback_after_reinit_exhausted(monkeypatch):# ── Dispatch: hybrid batch-prefetch path ──────────────────────────────────- sys.platform == "darwin",- reason="macOS deliberately skips the sounddevice OutputStream path (PR #62601)",-)-def test_hybrid_first_sentence_streamed_individually(monkeypatch):- """The first sentence must get its own stream() call for low TTFA."""- from tools import tts_tool- from tools.tts_tool_speaker import stream_tts_to_speaker-- stream_calls: list[str] = []-- class _Tracking(ts.StreamingTTSProvider):- sample_rate = 24000-- @staticmethod- def available():- return True-- def stream(self, text):- stream_calls.append(text)- yield b"\x00\x00" * 10-- sd, out = _sd_mock()- q = _drain_queue(["This is the first complete sentence."])- stop, done = threading.Event(), threading.Event()-- with patch("tools.tts_streaming.resolve_streaming_provider",- return_value=_Tracking({}, {})), \- patch.object(tts_tool, "_import_sounddevice", return_value=sd):- stream_tts_to_speaker(q, stop, done)-- assert len(stream_calls) == 1, (- f"single sentence should trigger 1 stream() call, got {stream_calls}"- )- assert done.is_set()@pytest.mark.skipif(@@ -658,49 +609,6 @@ def test_hybrid_subsequent_sentences_prefetched_individually(monkeypatch):assert done.is_set()- sys.platform == "darwin",- reason="macOS deliberately skips the sounddevice OutputStream path (PR #62601)",-)-def test_hybrid_short_sentences_each_get_own_call(monkeypatch):- """Short sentences should each get their own stream() call — no batching,- no waiting for a threshold or end-of-text."""- from tools import tts_tool- from tools.tts_tool_speaker import stream_tts_to_speaker-- stream_calls: list[str] = []-- class _Tracking(ts.StreamingTTSProvider):- sample_rate = 24000-- @staticmethod- def available():- return True-- def stream(self, text):- stream_calls.append(text)- yield b"\x00\x00" * 10-- sd, out = _sd_mock()- # Two short sentences — each gets its own stream() call.- q = _drain_queue([- "This is the first sentence. ",- "Short second one. ",- ])- stop, done = threading.Event(), threading.Event()-- with patch("tools.tts_streaming.resolve_streaming_provider",- return_value=_Tracking({}, {})), \- patch.object(tts_tool, "_import_sounddevice", return_value=sd):- stream_tts_to_speaker(q, stop, done)-- assert len(stream_calls) == 2, (- f"expected 2 stream() calls (1 per sentence), "- f"got {len(stream_calls)}: {stream_calls}"- )- assert "first" in stream_calls[0].lower()- assert "second" in stream_calls[1].lower()- assert done.is_set()@pytest.mark.skipif(@@ -852,114 +760,8 @@ def test_hybrid_playback_serialized_no_overlap(monkeypatch):)- sys.platform == "darwin",- reason="macOS deliberately skips the sounddevice OutputStream path (PR #62601)",-)-def test_hybrid_prefetch_fires_http_immediately(monkeypatch):- """The prefetch thread must start consuming the generator (firing the- HTTP request) the moment _enqueue_audio is called, NOT when the- playback worker gets to it.-- We verify by recording the wall-clock time when stream() first yields- and asserting that the second call's first yield happens before the- first call's playback completes.- """- import time- from tools import tts_tool- from tools.tts_tool_speaker import stream_tts_to_speaker-- stream_start_times: list[float] = []- playback_done_times: list[float] = []- block_first_playback = threading.Event()-- class _BlockingFirst(ts.StreamingTTSProvider):- sample_rate = 24000-- @staticmethod- def available():- return True-- def stream(self, text):- stream_start_times.append(time.monotonic())- # First sentence: block until the test signals playback to proceed.- # This simulates a long audio segment still playing.- if len(stream_start_times) == 1:- block_first_playback.wait(timeout=5.0)- yield b"\x00\x00" * 10-- sd, out = _sd_mock()- write_count = [0]-- def _mock_write(_data):- write_count[0] += 1- if write_count[0] == 1:- # First write of first sentence — unblock so playback can finish.- block_first_playback.set()-- out.write.side_effect = _mock_write-- # Two sentences: first blocks, second should prefetch while first plays.- q = _drain_queue(["First sentence here. ", "Second sentence here. "])- stop, done = threading.Event(), threading.Event()-- with patch("tools.tts_streaming.resolve_streaming_provider",- return_value=_BlockingFirst({}, {})), \- patch.object(tts_tool, "_import_sounddevice", return_value=sd):- stream_tts_to_speaker(q, stop, done)-- assert done.is_set()- assert len(stream_start_times) == 2, (- f"expected 2 stream() calls, got {len(stream_start_times)}"- )- # The second stream() call must have started (HTTP fired) while the- # first was still blocked/playing. Since the first blocks until- # playback starts, and the second is enqueued immediately after,- # the second's start time should be very close to the first's.- # We just assert both fired (the timing is inherently tested by the- # fact that block_first_playback was needed to unblock the first).- assert stream_start_times[1] > stream_start_times[0], (- "second stream() should start after the first"- )--- sys.platform == "darwin",- reason="macOS deliberately skips the sounddevice OutputStream path (PR #62601)",-)-def test_display_callback_not_called_when_streaming_enabled(monkeypatch):- """When streaming is enabled, display_callback must NOT be passed to- the TTS consumer — the token stream already renders text. This- prevents duplicate rendering (fix #1).-- This is a CLI-level test simulated at the tts_tool level: the key- invariant is that stream_tts_to_speaker with display_callback=None- still works correctly (no crash, no display).- """- from tools import tts_tool- from tools.tts_tool_speaker import stream_tts_to_speaker-- class _Fake(ts.StreamingTTSProvider):- sample_rate = 24000-- @staticmethod- def available():- return True-- def stream(self, text):- yield b"\x00\x00" * 10-- sd, out = _sd_mock()- q = _drain_queue(["A sentence for the no-callback path. "])- stop, done = threading.Event(), threading.Event()- # display_callback=None simulates the streaming_enabled=True case.- with patch("tools.tts_streaming.resolve_streaming_provider",- return_value=_Fake({}, {})), \- patch.object(tts_tool, "_import_sounddevice", return_value=sd):- stream_tts_to_speaker(q, stop, done, display_callback=None)- assert done.is_set()# No assertion on display — the point is no crash and done is set.diff --git a/tests/tools/test_tts_streaming_e2e.py b/tests/tools/test_tts_streaming_e2e.pydeleted file mode 100644index 3686b0f60de..00000000000--- a/tests/tools/test_tts_streaming_e2e.py+++ /dev/null@@ -1,67 +0,0 @@-"""End-to-end tests for streaming TTS providers. Gated on real API keys.--Salvaged from PR #47588 (@Cdddo) and adapted to the current provider ABC-(``StreamingTTSProvider(tts_config, section)``). These tests are SKIPPED by-default — they only run when the relevant credential is present. They're-useful for catching provider-API drift and verifying the integration-end-to-end, but they shouldn't run in CI without secrets configured.-"""-from __future__ import annotations--import os--import pytest---def _has_xai_creds() -> bool:- # Plain os.environ, matching the other gates here: the repo's test- # conftest scrubs dotenv/pooled secrets, so gating on the richer- # resolver would collect a test whose runtime credentials are gone.- return bool(os.environ.get("XAI_API_KEY"))---# --- ElevenLabs ------ not os.environ.get("ELEVENLABS_API_KEY"),- reason="ELEVENLABS_API_KEY not set",-)-def test_elevenlabs_streaming_real():- """Generate audio from the real ElevenLabs API and verify non-empty chunks."""- from tools.tts_streaming import ElevenLabsStreamer-- provider = ElevenLabsStreamer({}, {})- chunks = list(provider.stream("Hello world, this is a test."))- assert len(chunks) > 0- total_bytes = sum(len(c) for c in chunks)- # 1s of PCM at 24kHz mono int16 = 48000 bytes; expect at least 1k for real audio- assert total_bytes > 1000---# --- Gemini ------# --- OpenAI ------# --- xAI ------# --- Resolver integration (no network; requires at least one key) ------ not (- os.environ.get("ELEVENLABS_API_KEY")- or os.environ.get("GEMINI_API_KEY")- or os.environ.get("GOOGLE_API_KEY")- or os.environ.get("OPENAI_API_KEY")- ),- reason="no streaming-capable TTS key set",-)-def test_auto_resolver_finds_a_real_provider():- from tools.tts_streaming import StreamingTTSProvider, resolve_streaming_provider-- provider = resolve_streaming_provider({"streaming": {"provider": "auto"}})- assert isinstance(provider, StreamingTTSProvider)diff --git a/tests/tools/test_tts_xai_speech_tags.py b/tests/tools/test_tts_xai_speech_tags.pyindex 473d11785ff..6a55a3133fb 100644--- a/tests/tools/test_tts_xai_speech_tags.py+++ b/tests/tools/test_tts_xai_speech_tags.py@@ -1,9 +1,8 @@"""Tests for xAI TTS speech-tag handling."""from types import SimpleNamespace-from unittest.mock import Mock, patch+from unittest.mock import patch-import pytestfrom tools.tts_tool import _generate_xai_ttsfrom tools.tts_tool_providers import (@@ -235,7 +234,6 @@ def test_auto_speech_tags_calls_auxiliary_rewriter_with_tts_audio_tags_task():mock_call.assert_called_once()call_kwargs = mock_call.call_args.kwargsassert call_kwargs["task"] == "tts_audio_tags"- assert call_kwargs["temperature"] == 0.7messages = call_kwargs["messages"]assert messages[0]["role"] == "system"@@ -254,13 +252,9 @@ def test_auto_speech_tags_calls_auxiliary_rewriter_with_tts_audio_tags_task():assert tag in system_prompt, (f"wrapping tag {tag!r} missing from system prompt")- # The prompt must explicitly show the BBCode-style closing syntax so- # the rewriter uses [/tag] and not <tag>...</tag>.- assert "[/tag]" in system_prompt# The user message carries the locally pause-tagged transcript (the# conservative fallback the rewriter is asked to enrich).- assert "TRANSCRIPT TO TAG" in messages[1]["content"]assert "[pause]" in messages[1]["content"]@@ -281,27 +275,3 @@ def test_auto_speech_tags_strips_markdown_fences_from_rewriter_output():assert result == "[warmly] Bonjour. [soft laugh]"-def test_generate_xai_tts_omits_text_normalization_when_explicit_false(- tmp_path, monkeypatch-):- """text_normalization: false is the API default; field is not sent."""- captured = {}-- fake_response = Mock()- fake_response.content = b"mp3"- fake_response.raise_for_status.return_value = None-- def fake_post(url, headers, json, timeout, stream=False):- captured["json"] = json- return fake_response-- monkeypatch.setenv("XAI_API_KEY", "test-xai-key")- monkeypatch.setattr("requests.post", fake_post)-- _generate_xai_tts(- "Hello world.",- str(tmp_path / "out.mp3"),- {"xai": {"voice_id": "ara", "language": "en", "text_normalization": False}},- )-- assert "text_normalization" not in captured["json"]diff --git a/tests/tools/test_video_analyze.py b/tests/tools/test_video_analyze.pyindex 00351116302..62719bd9d50 100644--- a/tests/tools/test_video_analyze.py+++ b/tests/tools/test_video_analyze.py@@ -11,9 +11,7 @@ from tools.vision_tools import (_detect_video_mime_type,_video_to_base64_data_url,_handle_video_analyze,- _MAX_VIDEO_BASE64_BYTES,video_analyze_tool,- VIDEO_ANALYZE_SCHEMA,)@@ -70,15 +68,6 @@ class TestVideoToBase64DataUrl:# ----------------------------------------------------------------------------class TestVideoAnalyzeSchema:- """Schema structure is correct."""-- def test_schema_name(self):- assert VIDEO_ANALYZE_SCHEMA["name"] == "video_analyze"--- def test_schema_description_mentions_video(self):- assert "video" in VIDEO_ANALYZE_SCHEMA["description"].lower()# ---------------------------------------------------------------------------@@ -89,19 +78,6 @@ class TestVideoAnalyzeSchema:class TestHandleVideoAnalyze:"""Tests for the registry handler wrapper."""- def test_returns_awaitable(self, tmp_path, monkeypatch):- video_file = tmp_path / "test.mp4"- video_file.write_bytes(b"\x00" * 100)- monkeypatch.setenv("AUXILIARY_VIDEO_MODEL", "")- monkeypatch.setenv("AUXILIARY_VISION_MODEL", "")-- with patch("tools.vision_tools.video_analyze_tool", new_callable=AsyncMock) as mock_tool:- mock_tool.return_value = json.dumps({"success": True, "analysis": "test"})- result = _handle_video_analyze({"video_url": str(video_file), "question": "what is this?"})- # Should return an awaitable (coroutine)- assert asyncio.iscoroutine(result)- # Clean up the unawaited coroutine- result.close()def test_falls_back_to_vision_model_env(self, tmp_path, monkeypatch):@@ -279,11 +255,5 @@ class TestVideoToolsetRegistration:assert entry is not Noneassert entry.toolset == "video"assert entry.is_async is True- assert entry.emoji == "🎬"- def test_in_video_toolset_definition(self):- """Toolset 'video' should contain video_analyze."""- from toolsets import TOOLSETS- assert "video" in TOOLSETS- assert "video_analyze" in TOOLSETS["video"]["tools"]diff --git a/tests/tools/test_video_generate_schema.py b/tests/tools/test_video_generate_schema.pyindex a340975ae4a..70d3c39bbd7 100644--- a/tests/tools/test_video_generate_schema.py+++ b/tests/tools/test_video_generate_schema.py@@ -1,14 +1,12 @@"""video_generate dynamic schema — capability-gated params (#95681 diet).Mirrors tests/tools/test_image_generate_schema.py (#97057). Coverage is-guaranteed three ways:+guaranteed two ways:1. every in-tree video_gen plugin's capabilities() must declare EVERY axisthe schema builder reads (a new axis added to the builder without fleetdeclarations fails here);2. every FAL video family must carry the per-family keys the fal provider'sactive-model capabilities() resolution reads;-3. declaration⇄implementation: a provider that declares seed/upscale must- implement it, and vice versa (source-level sweep, both directions)."""import osimport sys@@ -19,7 +17,6 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))import tools.video_generation_tool as vtfrom tools.video_generation_tool import (- VIDEO_GENERATE_SCHEMA,_build_dynamic_video_schema,)@@ -42,20 +39,6 @@ FAL_FAMILY_KEYS = ("durations", "aspect_ratios", "resolutions", "audio","negative", "seed")-def _plugin_sources():- import pathlib-- plugins_dir = (pathlib.Path(__file__).resolve().parents[2]- / "plugins" / "video_gen")- assert plugins_dir.is_dir(), plugins_dir- out = {}- for plugin in sorted(plugins_dir.iterdir()):- src_file = plugin / "__init__.py"- if src_file.is_file():- out[plugin.name] = src_file.read_text(encoding="utf-8")- return out--class TestFleetCapabilityCoverage(unittest.TestCase):def test_every_provider_declares_every_axis(self):"""Instantiate each in-tree provider class and check the RETURNED@@ -144,39 +127,6 @@ class TestFleetCapabilityCoverage(unittest.TestCase):self.assertNotIn("audio", schema["parameters"]["properties"])self.assertIn("always on", schema["description"])- def test_declaration_matches_implementation(self):- """supports_seed / supports_upscale: declaration ⇄ implementation,- source-level, both directions, every in-tree plugin.-- deepinfra inherits generate() from OpenAICompatibleVideoGenProvider- (agent/video_gen_provider.py), so its implementation source is the- base class file."""- import pathlib-- base_src = (pathlib.Path(__file__).resolve().parents[2]- / "agent" / "video_gen_provider.py").read_text(encoding="utf-8")- for name, src in _plugin_sources().items():- with self.subTest(provider=name):- impl_src = src if "def generate" in src else src + base_src- declares_upscale = '"supports_upscale": True' in src- implements_upscale = ("_upscale_video" in impl_src- or "UPSCALER_ENDPOINT" in impl_src)- self.assertEqual(- declares_upscale, implements_upscale,- f"{name}: supports_upscale declaration "- f"({declares_upscale}) != implementation "- f"({implements_upscale})",- )- declares_seed = '"supports_seed": True' in src- implements_seed = ("seed" in impl_src- and ("payload[\"seed\"]" in impl_src- or "seed: Optional[int]" in impl_src- or "\"seed\": seed" in impl_src))- self.assertEqual(- declares_seed, implements_seed,- f"{name}: supports_seed declaration ({declares_seed}) "- f"!= implementation ({implements_seed})",- )class TestDynamicParamGating(unittest.TestCase):@@ -243,12 +193,6 @@ class TestDynamicParamGating(unittest.TestCase):schema = _build_dynamic_video_schema()self.assertEqual(sorted(schema["parameters"]["properties"]), ["prompt"])- def test_static_schema_carries_no_capability_args(self):- props = VIDEO_GENERATE_SCHEMA["parameters"]["properties"]- self.assertEqual(- sorted(props),- ["aspect_ratio", "duration", "prompt", "resolution"],- )if __name__ == "__main__":diff --git a/tests/tools/test_video_generation_dispatch.py b/tests/tools/test_video_generation_dispatch.pyindex 3cf1e823b70..b96f8a02fc5 100644--- a/tests/tools/test_video_generation_dispatch.py+++ b/tests/tools/test_video_generation_dispatch.py@@ -89,25 +89,12 @@ class TestUnifiedDispatch:assert result["error_type"] == "provider_not_registered"- def test_edit_extend_fields_not_in_schema(self):- from tools.video_generation_tool import VIDEO_GENERATE_SCHEMA- props = VIDEO_GENERATE_SCHEMA["parameters"]["properties"]- assert "operation" not in props- assert "video_url" not in propsdef test_upscale_in_schema_and_forwarded(self):"""`upscale` is advertised per-capability by the dynamic builder(#95681 diet — static schema no longer carries it) and forwardedto providers when set, omitted (not None) when unset."""- from tools.video_generation_tool import (- VIDEO_GENERATE_SCHEMA,- _build_dynamic_video_schema,- )- # Static placeholder: capability args live in the dynamic override.- props = VIDEO_GENERATE_SCHEMA["parameters"]["properties"]- assert "upscale" not in props-provider = _RecordingProvider()video_gen_registry.register_provider(provider)result = self._run({"prompt": "a dog", "upscale": True}, configured="fake")diff --git a/tests/tools/test_video_generation_dynamic_schema.py b/tests/tools/test_video_generation_dynamic_schema.pyindex 55de50afb5e..16a3d1ee4ac 100644--- a/tests/tools/test_video_generation_dynamic_schema.py+++ b/tests/tools/test_video_generation_dynamic_schema.py@@ -84,15 +84,6 @@ class _ImageOnlyProvider(VideoGenProvider):class TestDynamicSchemaBuilder:- def test_no_config_says_so(self, cfg_home):- from tools.video_generation_tool import _build_dynamic_video_schema-- desc = _build_dynamic_video_schema()["description"]- # No provider configured AND none available → description says so. The- # wording reflects the *resolved* active provider (mirrors execution),- # so it reads "available" rather than "configured".- assert "No video backend is available" in desc- assert "hermes tools" in descdef test_builder_wired_into_registry(self):diff --git a/tests/tools/test_video_generation_tool_surface_matrix.py b/tests/tools/test_video_generation_tool_surface_matrix.pyindex 4c58607ae67..2ffdf757f15 100644--- a/tests/tools/test_video_generation_tool_surface_matrix.py+++ b/tests/tools/test_video_generation_tool_surface_matrix.py@@ -225,7 +225,6 @@ def test_xai_text_only_via_tool_surface(matrix_env):assert len(xai_calls) == 1assert xai_calls[0]["url"].endswith("/videos/generations")payload = xai_calls[0]["json"] or {}- assert payload["model"] == "grok-imagine-video"assert "image" not in payloadassert "reference_images" not in payloadassert payload["storage_options"]["public_url"] is Truediff --git a/tests/tools/test_vision_native_fast_path.py b/tests/tools/test_vision_native_fast_path.pyindex bd6e6e6890d..467ce243294 100644--- a/tests/tools/test_vision_native_fast_path.py+++ b/tests/tools/test_vision_native_fast_path.py@@ -150,18 +150,7 @@ class TestBuildNativeVisionToolResult:assert env["content"][1]["type"] == "image_url"assert env["content"][1]["image_url"]["url"] == "data:image/png;base64,XYZ"assert "what does it say?" in env["content"][0]["text"]- assert "Image attached natively" in env["text_summary"]- def test_no_question_omits_question_section(self):- env = _build_native_vision_tool_result(- image_url="/tmp/foo.png",- question="",- image_data_url="data:image/png;base64,XYZ",- image_size_bytes=512,- )- text = env["content"][0]["text"]- assert "Question:" not in text- assert "Image loaded" in text# ─── _vision_analyze_native ──────────────────────────────────────────────────diff --git a/tests/tools/test_vision_region.py b/tests/tools/test_vision_region.pyindex dcc7c5f2552..33a2ba7859e 100644--- a/tests/tools/test_vision_region.py+++ b/tests/tools/test_vision_region.py@@ -164,15 +164,6 @@ class TestNativePathRegion:class TestSchemaAndHandler:- def test_schema_declares_optional_region(self):- from tools.vision_tools import VISION_ANALYZE_SCHEMA-- props = VISION_ANALYZE_SCHEMA["parameters"]["properties"]- assert "region" in props- assert props["region"]["type"] == "array"- assert "region" not in VISION_ANALYZE_SCHEMA["parameters"]["required"]- # Description must document original-image pixel space.- assert "original" in props["region"]["description"].lower()def test_handler_passes_region_to_native_path(self, tmp_path, monkeypatch):from tools import vision_toolsdiff --git a/tests/tools/test_vision_tools.py b/tests/tools/test_vision_tools.pyindex 5cf4bcd0260..9037fee009f 100644--- a/tests/tools/test_vision_tools.py+++ b/tests/tools/test_vision_tools.py@@ -7,7 +7,6 @@ import loggingimport osfrom contextlib import ExitStackfrom pathlib import Path-from typing import Awaitablefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -22,7 +21,6 @@ from tools.vision_tools import (_EMBED_MAX_DIMENSION,_is_image_size_error,_MAX_BASE64_BYTES,- _RESIZE_TARGET_BYTES,vision_analyze_tool,check_vision_requirements,)@@ -127,18 +125,6 @@ class TestImageToBase64DataUrl:class TestHandleVisionAnalyze:"""Verify _handle_vision_analyze returns an Awaitable and builds correct prompt."""- def test_returns_awaitable_even_for_empty_args(self):- """The handler is registered as async, and missing keys must not raise."""- with patch(- "tools.vision_tools.vision_analyze_tool", new_callable=AsyncMock- ) as mock_tool:- mock_tool.return_value = json.dumps({"result": "ok"})- for args in ({"image_url": "https://example.com/img.png",- "question": "What is this?"}, {}):- result = _handle_vision_analyze(args)- assert isinstance(result, Awaitable)- # Clean up the coroutine to avoid RuntimeWarning- result.close()@pytest.mark.asyncio@@ -720,19 +706,6 @@ class TestErrorClassification:assert "smaller" in result["analysis"].lower()-class TestVisionRegistration:- def test_vision_analyze_registered_with_schema(self):- from tools.registry import registry-- entry = registry._tools.get("vision_analyze")- assert entry is not None- assert entry.toolset == "vision"- assert entry.is_async is True- assert callable(entry.handler)-- props = entry.schema.get("parameters", {}).get("properties", {})- assert "image_url" in props- assert "question" in props# ---------------------------------------------------------------------------diff --git a/tests/tools/test_voice_cli_integration.py b/tests/tools/test_voice_cli_integration.pyindex d0ed71d1ed6..76dfd1b44ab 100644--- a/tests/tools/test_voice_cli_integration.py+++ b/tests/tools/test_voice_cli_integration.py@@ -227,7 +227,9 @@ class TestMaxRecordingSecondsConfigReal:# become a 1-second cap; it falls back to the documented 120 default,# mirroring the silence-param corruption handling.recorder = self._start_with_voice_cfg({"max_recording_seconds": True})- assert recorder._max_recording_seconds == 120.0+ from hermes_cli.config import DEFAULT_CONFIG++ assert recorder._max_recording_seconds == DEFAULT_CONFIG["voice"]["max_recording_seconds"]class TestDisableVoiceModeReal:"""Tests _disable_voice_mode with real CLI instance."""@@ -472,7 +474,6 @@ class TestVoiceBargeCaptureSubmit:cli._voice_submit_barge_utterance(str(wav))queued = cli._pending_input.get_nowait()- from cli import _VoiceInputMessageassert str(queued) == "actually can you check my calendar for tomorrow"def test_generation_phase_transcript_not_echo_checked(self, tmp_path, monkeypatch):@@ -493,7 +494,6 @@ class TestVoiceBargeCaptureSubmit:cli._voice_submit_barge_utterance(str(wav))queued = cli._pending_input.get_nowait()- from cli import _VoiceInputMessageassert str(queued) == "stop, do it differently"diff --git a/tests/tools/test_voice_max_recording_seconds.py b/tests/tools/test_voice_max_recording_seconds.pyindex 394c9bfcd56..bfa41691320 100644--- a/tests/tools/test_voice_max_recording_seconds.py+++ b/tests/tools/test_voice_max_recording_seconds.py@@ -11,11 +11,6 @@ test pins the enforcement contract on the recorder:from tools.voice_mode import AudioRecorder-def test_cap_disabled_by_default():- r = AudioRecorder()- assert r._max_recording_seconds == 0.0- # No cap → duration trigger never fires, even at absurd elapsed times.- assert r._max_duration_reached(10_000.0) is Falsedef test_cap_enforced_when_set():@@ -26,7 +21,3 @@ def test_cap_enforced_when_set():assert r._max_duration_reached(300.0) is True-def test_zero_means_unlimited():- r = AudioRecorder()- r._max_recording_seconds = 0- assert r._max_duration_reached(99_999.0) is Falsediff --git a/tests/tools/test_voice_mode.py b/tests/tools/test_voice_mode.pyindex 50c9e589183..740f7c1e992 100644--- a/tests/tools/test_voice_mode.py+++ b/tests/tools/test_voice_mode.py@@ -289,7 +289,6 @@ class TestCheckVoiceRequirements:result = check_voice_requirements()assert result["available"] is Trueassert result["stt_available"] is True- assert "STT provider: OK (plugin: my-plugin-stt)" in result["details"]# ============================================================================# AudioRecorderdiff --git a/tests/tools/test_voice_stop_phrase.py b/tests/tools/test_voice_stop_phrase.pyindex ebd40e60cae..c7a1c00d28b 100644--- a/tests/tools/test_voice_stop_phrase.py+++ b/tests/tools/test_voice_stop_phrase.py@@ -24,9 +24,6 @@ from tools.voice_mode_transcript import (class TestVoiceStopHint:"""The 'Say "stop" to end the voice chat.' hint shown on voice-mode start."""- def test_default_phrase(self):- with patch("tools.voice_mode_transcript._load_voice_stop_phrases", return_value=("stop",)):- assert voice_stop_hint() == 'Say "stop" to end the voice chat.'def test_disabled_phrases_show_no_hint(self):@@ -159,12 +156,6 @@ class TestContinuousLoopStopPhraseSignal:assert still_active is False- def test_start_continuous_accepts_on_stop_phrase_kwarg(self):- import inspect-- import hermes_cli.voice as v-- assert "on_stop_phrase" in inspect.signature(v.start_continuous).parametersclass _ImmediateThread:diff --git a/tests/tools/test_voice_thinking_sound.py b/tests/tools/test_voice_thinking_sound.pyindex c0c87f01f0c..f068d7f52be 100644--- a/tests/tools/test_voice_thinking_sound.py+++ b/tests/tools/test_voice_thinking_sound.py@@ -44,9 +44,6 @@ def _reset():class TestConfigGate:- def test_default_enabled(self):- with patch("hermes_cli.config.load_config", return_value={"voice": {}}):- assert vm.thinking_sound_enabled() is Truedef test_start_refuses_when_disabled(self):diff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.pyindex 2f005d38b10..59b51604b58 100644--- a/tests/tools/test_wake_word.py+++ b/tests/tools/test_wake_word.py@@ -61,12 +61,6 @@ def test_looks_like_path():assert not _looks_like_path("hey_jarvis")-def test_load_wake_word_config_is_a_dict_with_defaults():- # Wired into DEFAULT_CONFIG, so a real load returns the section shape.- cfg = ww.load_wake_word_config()- assert isinstance(cfg, dict)- assert cfg.get("enabled") is False- assert cfg.get("provider") == "openwakeword"def test_load_wake_word_config_guards_non_dict(monkeypatch):@@ -240,16 +234,6 @@ def test_bundled_hey_hermes_model_ships_on_disk():# ── platform-aware backend selection (openWakeWord onnx is broken on macOS ARM64,# upstream dscripka/openWakeWord#336) ────────────────────────────────────────-def test_default_framework_tracks_the_macos_arm64_probe():- """``default_inference_framework()`` is exactly the ``_is_macos_arm64()``- branch — tflite there, onnx everywhere else.-- Stated as an invariant between the probe and its consumer so it holds on- every host, including the macOS runner (where both sides are real) and an- Intel Mac (where ONNX is fine and both sides say so).- """- expected = "tflite" if ww._is_macos_arm64() else "onnx"- assert ww.default_inference_framework() == expected@pytest.mark.macos_only@@ -788,7 +772,6 @@ def test_requirements_client_capture_without_local_mic(monkeypatch):return ""monkeypatch.setattr(ww, "lazy_deps", _LD, raising=False)- import tools.lazy_deps as real_ldmonkeypatch.setattr("tools.lazy_deps.is_available", lambda f: True)monkeypatch.setattr("tools.lazy_deps._allow_lazy_installs", lambda: False)diff --git a/tests/tools/test_watch_patterns.py b/tests/tools/test_watch_patterns.pyindex 78849630690..d997dec4099 100644--- a/tests/tools/test_watch_patterns.py+++ b/tests/tools/test_watch_patterns.py@@ -18,7 +18,6 @@ from unittest.mock import patchfrom tools.process_registry import (ProcessRegistry,ProcessSession,- WATCH_STRIKE_LIMIT,WATCH_GLOBAL_MAX_PER_WINDOW,)@@ -49,17 +48,6 @@ def _make_session(# ProcessSession field defaults# =========================================================================-class TestProcessSessionField:- def test_default_empty(self):- s = ProcessSession(id="proc_1", command="echo hi")- assert s.watch_patterns == []- assert s._watch_disabled is False- assert s._watch_hits == 0- assert s._watch_suppressed == 0-- def test_can_set_patterns(self):- s = _make_session(watch_patterns=["ERROR", "WARN"])- assert s.watch_patterns == ["ERROR", "WARN"]# =========================================================================@@ -282,18 +270,6 @@ class TestTerminalToolSchema:array_alts = [alt for alt in props["notify"]["anyOf"] if alt["type"] == "array"]assert array_alts and array_alts[0]["items"] == {"type": "string"}- def test_handler_passes_watch_patterns(self):- """_handle_terminal passes legacy watch_patterns through to- terminal_tool (background call — foreground+watch now errors)."""- from tools.terminal_tool import _handle_terminal- with patch("tools.terminal_tool.terminal_tool") as mock_tt:- mock_tt.return_value = json.dumps({"output": "ok", "exit_code": 0})- _handle_terminal(- {"command": "echo hi", "background": True, "watch_patterns": ["ERR"]},- task_id="t1",- )- _, kwargs = mock_tt.call_args- assert kwargs.get("watch_patterns") == ["ERR"]def test_foreground_watch_patterns_rejected_with_teaching_error(self):"""Background-only modifiers on a foreground call fail loud with thediff --git a/tests/tools/test_web_providers.py b/tests/tools/test_web_providers.pyindex c8af85aba7f..d1198200e3b 100644--- a/tests/tools/test_web_providers.py+++ b/tests/tools/test_web_providers.py@@ -9,7 +9,7 @@ Covers:from __future__ import annotationsimport json-from typing import Any, Dict, List+from typing import Any, Dictimport pytest@@ -32,11 +32,6 @@ class TestWebProviderABCs:``supports_search() / supports_extract()`` flags."""- def test_cannot_instantiate_abc_directly(self):- from agent.web_search_provider import WebSearchProvider-- with pytest.raises(TypeError):- WebSearchProvider() # type: ignore[abstract]def test_search_only_provider_skips_extract(self):@@ -105,21 +100,6 @@ class TestPerCapabilityBackendSelection:# ----------------------------------------------------------------------------class TestDefaultConfig:- """The web section exists in DEFAULT_CONFIG with per-capability keys."""-- def test_web_section_in_default_config(self):- from hermes_cli.config import DEFAULT_CONFIG-- assert "web" in DEFAULT_CONFIG- web = DEFAULT_CONFIG["web"]- assert "backend" in web- assert "search_backend" in web- assert "extract_backend" in web- # All empty string by default (no override)- assert web["backend"] == ""- assert web["search_backend"] == ""- assert web["extract_backend"] == ""# ---------------------------------------------------------------------------diff --git a/tests/tools/test_web_providers_brave_free.py b/tests/tools/test_web_providers_brave_free.pyindex 9a9de6daa5e..b2586f7ba37 100644--- a/tests/tools/test_web_providers_brave_free.py+++ b/tests/tools/test_web_providers_brave_free.py@@ -32,10 +32,6 @@ class TestBraveFreeProviderIsConfigured:assert BraveFreeWebSearchProvider().is_available() is True- def test_implements_web_search_provider(self):- from agent.web_search_provider import WebSearchProvider- from plugins.web.brave_free.provider import BraveFreeWebSearchProvider- assert issubclass(BraveFreeWebSearchProvider, WebSearchProvider)class TestBraveFreeProviderSearch:diff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.pyindex b5dd4d62700..938c6d25ce4 100644--- a/tests/tools/test_web_providers_ddgs.py+++ b/tests/tools/test_web_providers_ddgs.py@@ -83,10 +83,6 @@ class TestDDGSProviderIsConfigured:assert DDGSWebSearchProvider().is_available() is True- def test_implements_web_search_provider(self):- from agent.web_search_provider import WebSearchProvider- from plugins.web.ddgs.provider import DDGSWebSearchProvider- assert issubclass(DDGSWebSearchProvider, WebSearchProvider)class TestDDGSProviderSearch:diff --git a/tests/tools/test_web_providers_searxng.py b/tests/tools/test_web_providers_searxng.pyindex 415de09f774..d301b56a812 100644--- a/tests/tools/test_web_providers_searxng.py+++ b/tests/tools/test_web_providers_searxng.py@@ -31,10 +31,6 @@ class TestSearXNGSearchProviderIsConfigured:assert SearXNGWebSearchProvider().is_available() is True- def test_implements_web_search_provider(self):- from agent.web_search_provider import WebSearchProvider- from plugins.web.searxng.provider import SearXNGWebSearchProvider- assert issubclass(SearXNGWebSearchProvider, WebSearchProvider)class TestSearXNGSearchProviderSearch:diff --git a/tests/tools/test_web_providers_xai.py b/tests/tools/test_web_providers_xai.pyindex 6f42456136b..baa72c0d0f6 100644--- a/tests/tools/test_web_providers_xai.py+++ b/tests/tools/test_web_providers_xai.py@@ -51,15 +51,6 @@ def _responses_payload(text: str, annotations=None, citations=None) -> dict:# ----------------------------------------------------------------------------class TestXAIProviderIdentity:- def test_provider_name(self):- from plugins.web.xai.provider import XAIWebSearchProvider- assert XAIWebSearchProvider().name == "xai"--- def test_display_name(self):- from plugins.web.xai.provider import XAIWebSearchProvider- assert "Grok" in XAIWebSearchProvider().display_nameclass TestXAIProviderIsAvailable:@@ -69,10 +60,6 @@ class TestXAIProviderIsAvailable:visible CLI latency."""- def test_available_via_env_var(self, monkeypatch):- monkeypatch.setenv("XAI_API_KEY", "sk-xai-test")- from plugins.web.xai.provider import XAIWebSearchProvider- assert XAIWebSearchProvider().is_available() is Truedef test_unavailable_when_auth_store_corrupted(self, monkeypatch, tmp_path):@@ -399,11 +386,6 @@ class TestXAIProviderSearchErrors:class TestXAIBackendWiring:- def test_is_backend_available_true_via_env_var(self, monkeypatch):- from tools import web_tools-- monkeypatch.setenv("XAI_API_KEY", "sk-xai-test")- assert web_tools._is_backend_available("xai") is Truedef test_is_backend_available_does_not_call_resolver(self, monkeypatch):@@ -419,10 +401,6 @@ class TestXAIBackendWiring:):assert web_tools._is_backend_available("xai") is True- def test_configured_backend_xai_accepted(self, monkeypatch):- from tools import web_tools- monkeypatch.setattr(web_tools, "_load_web_config", lambda: {"backend": "xai"})- assert web_tools._get_backend() == "xai"def test_xai_not_in_legacy_backend_candidate_chain(self, monkeypatch):"""The hardcoded ``backend_candidates`` tuple in ``_get_backend()``diff --git a/tests/tools/test_web_tools_config.py b/tests/tools/test_web_tools_config.pyindex f765d2ba60f..cd7921922ec 100644--- a/tests/tools/test_web_tools_config.py+++ b/tests/tools/test_web_tools_config.py@@ -14,7 +14,7 @@ import osimport sysimport typesimport pytest-from unittest.mock import patch, MagicMock, AsyncMock+from unittest.mock import patch, MagicMockclass TestFirecrawlClientConfig:@@ -444,16 +444,6 @@ class TestParallelClientConfig:class TestWebSearchSchema:"""Test suite for web_search tool schema and handler wiring."""- def test_schema_exposes_optional_limit(self):- import tools.web_tools-- limit_schema = tools.web_tools.WEB_SEARCH_SCHEMA["parameters"]["properties"]["limit"]-- assert limit_schema["type"] == "integer"- assert limit_schema["minimum"] == 1- assert limit_schema["maximum"] == 100- assert limit_schema["default"] == 5- assert "limit" not in tools.web_tools.WEB_SEARCH_SCHEMA["parameters"]["required"]def test_web_search_clamps_limit_before_backend_call(self):@@ -666,12 +656,6 @@ class TestCheckWebApiKey:assert check_web_api_key() is True-def test_web_requires_env_includes_exa_key():- from tools.web_tools import _web_requires_env-- env = _web_requires_env()- assert "EXA_API_KEY" in env- assert "TAVILY_API_KEY" in envclass TestNonBuiltinProviderAvailability:@@ -773,18 +757,6 @@ class TestNonBuiltinProviderAvailability:from tools.web_tools import _get_extract_backendassert _get_extract_backend() == "fake-plugin-prov"- def test_tool_registry_entries_not_filtered_out(self):- """web_search and web_extract tool entries must remain in the- registry when only a custom provider is available."""- with patch("tools.web_tools._ddgs_package_importable", return_value=False), \- patch("tools.managed_tool_gateway.peek_nous_access_token", return_value=None):- import tools.web_tools- web_search_entry = tools.web_tools.registry.get_entry("web_search")- web_extract_entry = tools.web_tools.registry.get_entry("web_extract")- assert web_search_entry is not None, \- "web_search tool was filtered out despite custom provider being available"- assert web_extract_entry is not None, \- "web_extract tool was filtered out despite custom provider being available"class TestFirecrawlEnvResolution:@@ -851,7 +823,6 @@ class TestSiblingProvidersEnvResolution:"""is_available() must see a key that lives only in the .env layer."""monkeypatch.delenv(env_key, raising=False)- import importlibmodule = importlib.import_module(module_path)provider = getattr(module, cls_name)()diff --git a/tests/tools/test_web_tools_tavily.py b/tests/tools/test_web_tools_tavily.pyindex ae6c8ff52c0..4de6c94b8fc 100644--- a/tests/tools/test_web_tools_tavily.py+++ b/tests/tools/test_web_tools_tavily.py@@ -320,11 +320,6 @@ class TestWebSearchTavily:assert "Authorization" not in headersassert "api.tavily.com/search" in mock_post.call_args.args[0]- def test_tavily_is_not_in_keyless_ring(self):- from plugins.web.keyless_mcp import _KEYLESS_RING, _KEYLESS_SEARCHERS, _KEYLESS_EXTRACTORS- assert "tavily" not in _KEYLESS_RING- assert "tavily" not in _KEYLESS_SEARCHERS- assert "tavily" not in _KEYLESS_EXTRACTORS# ─── web_extract_tool (Tavily dispatch) ───────────────────────────────────────diff --git a/tests/tools/test_windows_agent_loop_papercuts.py b/tests/tools/test_windows_agent_loop_papercuts.pyindex 820590355a2..d6023384ebd 100644--- a/tests/tools/test_windows_agent_loop_papercuts.py+++ b/tests/tools/test_windows_agent_loop_papercuts.py@@ -5,8 +5,6 @@ mangling, crashes, and divergent hashing that made day-to-day agent use onWindows unpleasant. Each test names the issue it pins."""-import os-import reimport sysfrom pathlib import Path@@ -76,30 +74,8 @@ class TestWindowsMarketingVersion:expected = "11" if build >= 22000 else "10"assert _windows_marketing_version() == expected- def test_fallback_on_lookup_failure(self, monkeypatch):- import agent.prompt_builder as pb-- if sys.platform == "win32":- monkeypatch.delattr(sys, "getwindowsversion")- assert isinstance(pb._windows_marketing_version(), str)---class TestAutocompleteDevicePaths:- """#42016 — relpath ValueError on device paths must not escape."""-- def test_relpath_valueerror_pattern(self):- # The guarded pattern in _get_project_files: a ValueError from- # os.path.relpath (different mount) is skipped, not raised.- bad = "\\\\.\\nul" if sys.platform == "win32" else "/dev/null"- cwd = os.getcwd()- files = []- for p in [bad, os.path.join(cwd, "real.txt")]:- try:- rel = os.path.relpath(p, cwd) if os.path.isabs(p) else p- except ValueError:- continue- files.append(rel)- assert "real.txt" in files++class TestBrowserScreenshotPathRegex:diff --git a/tests/tools/test_windows_compat.py b/tests/tools/test_windows_compat.pydeleted file mode 100644index 109d5bd297d..00000000000--- a/tests/tools/test_windows_compat.py+++ /dev/null@@ -1,105 +0,0 @@-"""Tests for Windows compatibility of process management code.--Verifies that os.setsid and os.killpg are never called unconditionally,-and that each module uses a platform guard before invoking POSIX-only functions.-"""--import ast-import pytest-from pathlib import Path--# Files that must have Windows-safe process management-GUARDED_FILES = [- "tools/environments/local.py",- "tools/process_registry.py",- "tools/code_kernel.py", # execute_code's child Popen lives in the session kernel- "gateway/platforms/whatsapp.py",-]--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent---def _get_preexec_fn_values(filepath: Path) -> list:- """Find all preexec_fn= keyword arguments in Popen calls."""- source = filepath.read_text(encoding="utf-8")- tree = ast.parse(source, filename=str(filepath))- values = []- for node in ast.walk(tree):- if isinstance(node, ast.keyword) and node.arg == "preexec_fn":- values.append(ast.dump(node.value))- return values---class TestNoUnconditionalSetsid:- """preexec_fn must never be a bare os.setsid reference."""-- @pytest.mark.parametrize("relpath", GUARDED_FILES)- def test_preexec_fn_is_guarded(self, relpath):- filepath = PROJECT_ROOT / relpath- if not filepath.exists():- pytest.skip(f"{relpath} not found")- values = _get_preexec_fn_values(filepath)- for val in values:- # A bare os.setsid would be: Attribute(value=Name(id='os'), attr='setsid')- assert "attr='setsid'" not in val or "IfExp" in val or "None" in val, (- f"{relpath} has unconditional preexec_fn=os.setsid"- )---class TestStartNewSession:- """All guarded files must use start_new_session=True instead of preexec_fn."""-- @pytest.mark.parametrize("relpath", GUARDED_FILES)- def test_uses_start_new_session(self, relpath):- """Each guarded file must use start_new_session instead of preexec_fn.-- The value may be a variable (e.g. ``popen_start_new_session``) when- the spawn conditionally uses ``systemd-run --scope`` which creates its- own session/cgroup — in that case ``start_new_session=False`` is- correct and a literal ``True`` would mask scope-creation failures.- """- filepath = PROJECT_ROOT / relpath- if not filepath.exists():- pytest.skip(f"{relpath} not found")- source = filepath.read_text(encoding="utf-8")- # Files should use start_new_session, not preexec_fn- assert "preexec_fn" not in source, (- f"{relpath} still uses preexec_fn; use start_new_session=True instead"- )- assert "start_new_session=" in source, (- f"{relpath} missing start_new_session= in Popen call"- )---class TestIsWindowsConstant:- """Each guarded file must define _IS_WINDOWS."""-- @pytest.mark.parametrize("relpath", GUARDED_FILES)- def test_has_is_windows(self, relpath):- filepath = PROJECT_ROOT / relpath- if not filepath.exists():- pytest.skip(f"{relpath} not found")- source = filepath.read_text(encoding="utf-8")- assert "_IS_WINDOWS" in source, (- f"{relpath} missing _IS_WINDOWS platform guard"- )---class TestKillpgGuarded:- """os.killpg must always be behind a platform check."""-- @pytest.mark.parametrize("relpath", GUARDED_FILES)- def test_no_unguarded_killpg(self, relpath):- filepath = PROJECT_ROOT / relpath- if not filepath.exists():- pytest.skip(f"{relpath} not found")- source = filepath.read_text(encoding="utf-8")- lines = source.splitlines()- for i, line in enumerate(lines):- stripped = line.strip()- if "os.killpg" in stripped or "os.getpgid" in stripped:- # Check that there's an _IS_WINDOWS guard in the surrounding context- context = "\n".join(lines[max(0, i - 15):i + 1])- assert "_IS_WINDOWS" in context or "else:" in context, (- f"{relpath}:{i + 1} has unguarded os.killpg/os.getpgid call"- )diff --git a/tests/tools/test_windows_native_support.py b/tests/tools/test_windows_native_support.pyindex c813211d08e..c002bf826f0 100644--- a/tests/tools/test_windows_native_support.py+++ b/tests/tools/test_windows_native_support.py@@ -1,12 +1,8 @@"""Behavioral tests for Windows-specific compatibility fixes.-Complements ``tests/tools/test_windows_compat.py`` (which does source-level-pattern linting) with cross-platform-mocked tests that exercise the actual-code paths Hermes takes on native Windows.--Runs on Linux CI — every test mocks ``sys.platform``, ``subprocess.run``,-and ``os.kill`` as needed to simulate Windows behavior without requiring a-Windows runner.+Host-independent tests run everywhere; tests that need a real Windows host+are marked ``windows_only`` (they mock only dependencies such as+``subprocess.run`` / ``os.kill``, never ``sys.platform``)."""from __future__ import annotations@@ -59,12 +55,6 @@ class TestConfigureWindowsStdio:result = stdio.configure_windows_stdio()assert result is False- def test_idempotent(self):- from hermes_cli import stdio-- stdio.configure_windows_stdio()- # Second call returns False because _CONFIGURED is set- assert stdio.configure_windows_stdio() is Falsedef test_reconfigure_stream_handles_missing_method(self, monkeypatch):@@ -174,41 +164,6 @@ class TestTerminatePidRoutingOnWindows:assert captured["sig"] == signal.SIGTERM-# ----------------------------------------------------------------------------# SIGKILL fallback pattern-# ------------------------------------------------------------------------------class TestSigkillFallback:- """Modules that want SIGKILL must fall back to SIGTERM when absent."""-- def test_getattr_fallback_works_when_sigkill_missing(self, monkeypatch):- """The `getattr(signal, "SIGKILL", signal.SIGTERM)` pattern."""- # Build a stand-in signal module with no SIGKILL attribute- fake_signal = MagicMock()- del fake_signal.SIGKILL # ensure it's absent- fake_signal.SIGTERM = 15-- result = getattr(fake_signal, "SIGKILL", fake_signal.SIGTERM)- assert result == 15--- @pytest.mark.parametrize(- "module_path, line_pattern",- [- ("hermes_cli.kanban_db_dispatch", 'getattr(signal, "SIGKILL", signal.SIGTERM)'),- ],- )- def test_module_uses_getattr_fallback(self, module_path, line_pattern):- """Source-level check that our modules use the safe fallback."""- rel = module_path.replace(".", "/") + ".py"- root = Path(__file__).resolve().parents[2]- source = (root / rel).read_text(encoding="utf-8")- assert line_pattern in source, (- f"{rel} must use the getattr fallback pattern on its SIGKILL site"- )--# ---------------------------------------------------------------------------# OSError widening on liveness probes#@@ -221,38 +176,6 @@ class TestSigkillFallback:# ----------------------------------------------------------------------------class TestProcessRegistryOSErrorWidening:- """_is_host_pid_alive delegates to gateway.status._pid_exists."""-- def test_oserror_treated_as_not_alive(self, monkeypatch):- """_pid_exists → False propagates as _is_host_pid_alive → False."""- from tools.process_registry import ProcessRegistry-- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)- assert ProcessRegistry._is_host_pid_alive(12345) is False-- def test_permission_error_treated_as_alive(self, monkeypatch):- """PermissionError is encoded by _pid_exists as alive=True; propagates as-is.-- This is a meaningful semantic change from the pre-#21561 version of- this test (which asserted PermissionError → not-alive). The old- ``os.kill(pid, 0)``-based probe couldn't distinguish "gone" from- "owned by another user" on some platforms, so it conservatively- returned False. The new psutil-based probe CAN distinguish them via- ``OpenProcess + ERROR_ACCESS_DENIED`` on Windows / ``except- PermissionError`` on POSIX, so alive=True is correct.- """- from tools.process_registry import ProcessRegistry-- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: True)- assert ProcessRegistry._is_host_pid_alive(12345) is True--- def test_alive_pid_returns_true(self, monkeypatch):- from tools.process_registry import ProcessRegistry-- monkeypatch.setattr("gateway.status._pid_exists", lambda pid: True)- assert ProcessRegistry._is_host_pid_alive(os.getpid()) is True@pytest.mark.linux_only@@ -331,77 +254,6 @@ class TestTzdataDependencyDeclared:)-# ----------------------------------------------------------------------------# README / docs consistency-# ------------------------------------------------------------------------------class TestReadmeNoLongerSaysWindowsUnsupported:- """The README shouldn't claim native Windows isn't supported."""-- def test_readme_does_not_say_not_supported(self):- root = Path(__file__).resolve().parents[2]- source = (root / "README.md").read_text(encoding="utf-8")- # Previous string (removed in this PR): "Native Windows is not supported"- assert "Native Windows is not supported" not in source, (- "README.md still says native Windows is not supported — update the "- "install copy to reflect the PowerShell installer."- )-- def test_readme_mentions_powershell_installer(self):- root = Path(__file__).resolve().parents[2]- source = (root / "README.md").read_text(encoding="utf-8")- assert "install.ps1" in source, (- "README.md must point at scripts/install.ps1 for Windows users"- )---# ----------------------------------------------------------------------------# pty_bridge graceful import on Windows-# ------------------------------------------------------------------------------class TestWebServerPtyBridgeGuard:- """The web server must not crash if pty_bridge can't import (Windows)."""-- def test_import_guard_present_in_source(self):- root = Path(__file__).resolve().parents[2]- source = (root / "hermes_cli" / "web_server_chat.py").read_text(encoding="utf-8")- assert "_PTY_BRIDGE_AVAILABLE" in source- assert "except ImportError" in source, (- "web_server_chat.py must wrap the pty_bridge import in try/except ImportError"- )-- def test_pty_handler_checks_availability_flag(self):- """The /api/pty handler must short-circuit when the bridge is unavailable."""- root = Path(__file__).resolve().parents[2]- source = (root / "hermes_cli" / "web_routers" / "chat_ws.py").read_text(encoding="utf-8")- assert "if not _PTY_BRIDGE_AVAILABLE" in source, (- "/api/pty handler must return a friendly error when PTY is unavailable"- )---# ----------------------------------------------------------------------------# Entry points wire configure_windows_stdio-# ------------------------------------------------------------------------------class TestEntryPointsConfigureStdio:- """cli.py, hermes_cli/main.py, gateway/run.py must call configure_windows_stdio."""-- @pytest.mark.parametrize(- "relpath",- ["cli.py", "hermes_cli/main.py", "gateway/run.py"],- )- def test_entry_point_calls_configure_stdio(self, relpath):- root = Path(__file__).resolve().parents[2]- source = (root / relpath).read_text(encoding="utf-8")- assert "configure_windows_stdio" in source, (- f"{relpath} must call hermes_cli.stdio.configure_windows_stdio() "- "early in startup so Windows consoles render Unicode without crashing"- )--# ---------------------------------------------------------------------------# _subprocess_compat shared helpers# ---------------------------------------------------------------------------@@ -410,9 +262,6 @@ class TestEntryPointsConfigureStdio:class TestSubprocessCompatHelpers:"""hermes_cli/_subprocess_compat.py POSIX + Windows behaviour."""- def test_is_windows_matches_sys_platform(self):- from hermes_cli import _subprocess_compat as sc- assert sc.IS_WINDOWS == (sys.platform == "win32")def test_resolve_node_command_returns_absolute_on_posix(self):"""On Linux, resolve_node_command('sh', ['-c','echo hi']) picks up /bin/sh."""@@ -499,205 +348,6 @@ class TestSubprocessCompatHelpers:assert fallback & 0x08000000, "fallback missing CREATE_NO_WINDOW"-# ----------------------------------------------------------------------------# tui_gateway/entry.py signal installation survives absent POSIX signals-# ------------------------------------------------------------------------------class TestTuiGatewayEntrySignalGuards:- """Importing tui_gateway.entry must not crash when SIGPIPE/SIGHUP absent.-- Linux has both signals, so this is mostly a source-level invariant check- (no bare ``signal.SIGPIPE`` at module level without a ``hasattr`` guard).- On Windows the import would have raised AttributeError before this fix.- """-- def test_source_guards_each_signal_installation(self):- root = Path(__file__).resolve().parents[2]- source = (root / "tui_gateway" / "entry.py").read_text(encoding="utf-8")- # Every signal installation at module scope must be guarded against- # missing signals (Windows: SIGPIPE/SIGHUP absent). Originally this- # was ``hasattr(signal, "SIGPIPE")`` inline; PR #72677 refactored to- # ``_install_signal("SIGPIPE", ...)`` which does the same guard via- # ``getattr(signal, signame, None)`` internally. Either form is- # acceptable — what matters is no bare ``signal.signal(SIGPIPE)``- # at module scope without a guard.- for sig_name in ("SIGPIPE", "SIGHUP", "SIGTERM", "SIGINT"):- assert (- f'hasattr(signal, "{sig_name}")' in source- or f'_install_signal("{sig_name}"' in source- ), (- f"signal {sig_name} must be installed via a guarded path "- f"(hasattr or _install_signal), not bare signal.signal()"- )-- def test_module_imports_cleanly(self):- """Importing the module must not raise — verifies the guards work."""- # Drop any cached import so the module re-initialises- for mod in list(sys.modules):- if mod.startswith("tui_gateway"):- del sys.modules[mod]- import tui_gateway.entry # noqa: F401 # must not raise---# ----------------------------------------------------------------------------# hermes_cli/kanban_db_dispatch.py waitpid guard-# ------------------------------------------------------------------------------class TestKanbanWaitpidWindowsGuard:- """os.WNOHANG doesn't exist on Windows — the dispatcher tick reap loop- must be gated behind a Windows check (``os.name != "nt"`` or the- monkeypatchable ``_kb._IS_WINDOWS`` flag from ``kanban_db``)."""-- def test_source_gates_waitpid_loop(self):- root = Path(__file__).resolve().parents[2]- source = (root / "hermes_cli" / "kanban_db_dispatch.py").read_text(encoding="utf-8")- # Find the waitpid call and confirm it's inside a POSIX gate.- idx = source.find("os.waitpid(-1, os.WNOHANG)")- assert idx > 0, "waitpid call must exist"- # Look backwards up to 600 chars for the gate (the Windows branch- # that polls Popen handles sits between the guard and the waitpid- # loop). Accept any of:- # `if os.name != "nt":` (run iff POSIX),- # `if os.name == "nt": return []` (early-return guard), or- # `if _kb._IS_WINDOWS: ... return reaped` (early-return via the- # kanban_db flag, which tests flip instead of faking sys.platform).- # All keep the waitpid loop off Windows; the early-return forms are- # stronger because the rest of the function never runs.- preamble = source[max(0, idx - 600):idx]- guard_patterns = (- 'os.name != "nt"',- "os.name != 'nt'",- 'os.name == "nt"', # early-return guard- "os.name == 'nt'",- "_kb._IS_WINDOWS", # early-return guard via kanban_db flag- )- assert any(p in preamble for p in guard_patterns), (- "os.waitpid(-1, os.WNOHANG) must sit behind a Windows guard "- f"(checked patterns: {guard_patterns})"- )---# ----------------------------------------------------------------------------# code_execution_tool TCP loopback on Windows-# ------------------------------------------------------------------------------class TestCodeExecutionTransportTcpFallback:- """The RPC transport must fall back to TCP on Windows.-- We can't easily execute the sandbox on Linux CI in Windows mode, but we- CAN assert that the generated client module supports both AF_UNIX and- AF_INET endpoints based on the HERMES_RPC_SOCKET format.- """-- def test_generated_client_handles_tcp_endpoint(self):- root = Path(__file__).resolve().parents[2]- source = (root / "tools" / "code_execution_tool.py").read_text(encoding="utf-8")- # _UDS_TRANSPORT_HEADER body must parse both transports.- assert 'endpoint.startswith("tcp://")' in source, (- "generated sandbox client must accept tcp:// endpoints for Windows"- )- assert "socket.AF_INET" in source, (- "generated sandbox client must be able to open AF_INET sockets"- )-- def test_server_side_branches_on_use_tcp_rpc(self):- # The local RPC listener lives in the session kernel (tools/code_kernel.py).- root = Path(__file__).resolve().parents[2]- source = (root / "tools" / "code_kernel.py").read_text(encoding="utf-8")- assert "if _IS_WINDOWS:" in source- assert 'rpc_endpoint = f"tcp://{host}:{port}"' in source---# ----------------------------------------------------------------------------# cron/scheduler.py /bin/bash dynamic resolution-# ------------------------------------------------------------------------------class TestCronSchedulerBashResolution:- """cron.scheduler_script (the pre-run script runner) must NOT hardcode /bin/bash — .sh scripts need a- dynamically-resolved bash so Windows (Git Bash) works."""-- def test_source_uses_shutil_which_for_bash(self):- root = Path(__file__).resolve().parents[2]- source = (root / "cron" / "scheduler_script.py").read_text(encoding="utf-8")- # The old hardcoded path should be gone as the sole bash source.- # It may still appear as a POSIX fallback after shutil.which(), so- # we check for the shutil.which call near the .sh/.bash branch.- assert 'shutil.which("bash")' in source, (- "cron.scheduler must resolve bash dynamically via shutil.which"- )-- def test_error_message_when_bash_missing(self):- root = Path(__file__).resolve().parents[2]- source = (root / "cron" / "scheduler_script.py").read_text(encoding="utf-8")- # The graceful-failure message must mention "bash not found" so- # Windows users without Git Bash see an actionable error instead- # of a WinError 2 traceback.- assert "bash not found" in source.lower()---# ----------------------------------------------------------------------------# Node-ecosystem launcher resolution (npm / npx / node)-# ------------------------------------------------------------------------------class TestNpmBareSpawnsResolved:- """Every spawn site that launches ``npm``/``npx`` must resolve via- shutil.which / hermes_cli._subprocess_compat.resolve_node_command- so Windows can execute the .cmd batch shims."""-- @pytest.mark.parametrize(- "relpath",- [- "hermes_cli/tools_config.py",- "hermes_cli/doctor.py",- "plugins/platforms/whatsapp/adapter.py",- "tools/browser_tool.py",- ],- )- def test_no_bare_npm_or_npx_in_popen_argv(self, relpath):- """Reject ``subprocess.run(["npm", ...])`` / ``["npx", ...]`` patterns.-- Those fail on Windows with WinError 193. Callers must resolve- via shutil.which(...) and pass the absolute path (or fall back- to the bare name only as a last resort behind a variable).- """- root = Path(__file__).resolve().parents[2]- source = (root / relpath).read_text(encoding="utf-8")- # The forbidden literal: a subprocess invocation that names npm- # or npx as a bare string inside an argv list.- forbidden_patterns = [- '["npm",',- '["npx",',- "['npm',",- "['npx',",- ]- for pat in forbidden_patterns:- # Exception: strings inside error-message text or comments are fine.- # We only fail if the literal appears in an argv position, which- # we approximate by checking it isn't inside a print/log/comment.- # Find all occurrences and verify they're behind shutil.which.- idx = 0- while True:- idx = source.find(pat, idx)- if idx < 0:- break- # Look at the preceding 120 chars — if "shutil.which" appears- # there, or the pattern is inside a comment/string, it's fine.- context = source[max(0, idx - 120):idx]- if "#" in context.split("\n")[-1]:- idx += len(pat)- continue- # Argv forms that START with a bare npm/npx are the bug.- raise AssertionError(- f"{relpath}: bare {pat!r} still present at offset {idx} — "- f"resolve via shutil.which(...) so Windows can execute .cmd shims"- )--# ---------------------------------------------------------------------------# tools/environments/local.py Windows temp dir & PATH injection# ---------------------------------------------------------------------------@@ -720,13 +370,6 @@ class TestLocalEnvironmentWindowsTempDir:f"POSIX temp dir must start with '/'; got {tmp_dir!r}")- def test_source_has_windows_branch_using_hermes_home(self):- root = Path(__file__).resolve().parents[2]- source = (root / "tools" / "environments" / "local.py").read_text(encoding="utf-8")- assert "if _IS_WINDOWS:" in source- assert "get_hermes_home" in source- assert 'get_hermes_home() / "cache" / "terminal"' in source- assert "_default_terminal_temp_dir()" in sourceclass TestLocalEnvironmentPathInjectionGated:@@ -783,19 +426,6 @@ class TestGitBashPathNormalization:assert cli_mod._normalize_git_bash_path("C:/Users/foo") == "C:/Users/foo"-class TestWorktreeSymlinkFallback:- """.worktreeinclude directory symlinks must fall back to copytree on- Windows (where symlink creation requires admin / Dev Mode)."""-- def test_source_has_symlink_fallback(self):- root = Path(__file__).resolve().parents[2]- source = (root / "hermes_cli" / "worktree_ops.py").read_text(encoding="utf-8")- # Look for the try/except that handles OSError around os.symlink- # with a shutil.copytree fallback.- assert "os.symlink(str(src_resolved), str(dst))" in source- assert "except (OSError, NotImplementedError)" in source- assert "shutil.copytree" in source- assert 'sys.platform != "win32"' in source# ---------------------------------------------------------------------------@@ -803,135 +433,6 @@ class TestWorktreeSymlinkFallback:# ----------------------------------------------------------------------------class TestGatewayDetachedWatcherWindowsFlags:- """launch_detached_profile_gateway_restart and the in-gateway update- launcher must use CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS on- Windows, not silent start_new_session=True."""-- def test_hermes_cli_gateway_uses_compat_kwargs(self):- root = Path(__file__).resolve().parents[2]- source = (root / "hermes_cli" / "gateway.py").read_text(encoding="utf-8")- assert "windows_detach_popen_kwargs" in source, (- "hermes_cli/gateway.py must use the platform-aware detach helper"- )- # The legacy start_new_session=True on the outer Popen should be- # replaced by **windows_detach_popen_kwargs(). Inside the watcher- # STRING the old pattern is replaced by explicit creationflags.- assert "**windows_detach_popen_kwargs()" in source--- def test_launch_detached_profile_gateway_restart_inlined_watcher_uses_breakaway(self):- """The inlined respawn script (stringified Python passed to ``python -c``)- must include CREATE_BREAKAWAY_FROM_JOB so the *respawned gateway* also- breaks away from any job-object the watcher itself inherits.-- Static check — the watcher source is built at import time and embedded- verbatim in the module text. The literal Win32 bits live in- hermes_cli._subprocess_compat; the watcher must call that helper from- inside the inlined payload so runtime behavior keeps the breakaway bit.-- The bit was added to the inlined payload by PR #40909. This test- ensures a future refactor of the dedent block doesn't silently drop it.- """- root = Path(__file__).resolve().parents[2]- text = (root / "hermes_cli" / "gateway.py").read_text(encoding="utf-8")- marker = "watcher = textwrap.dedent("- idx = text.find(marker)- assert idx != -1, "watcher block not found in gateway.py"- end = text.find(").strip()", idx)- assert end != -1, "watcher block end not found"- block = text[idx:end]- assert "from hermes_cli._subprocess_compat import" in block- assert "windows_detach_flags" in block- assert "windows_detach_flags()" in block, (- "Inlined respawn watcher must call windows_detach_flags() for the "- "respawned gateway; that helper carries CREATE_BREAKAWAY_FROM_JOB "- "so the new gateway is not reaped when the parent job tears down."- )- assert "See _subprocess_compat.windows_detach_flags()" in block, (- "Inlined respawn watcher should keep the breakaway intent greppable "- "near the helper call."- )-- def test_launch_detached_profile_gateway_restart_outer_popen_has_access_denied_fallback(- self,- ):- """When the outer watcher Popen raises OSError (breakaway denied by- the parent job object), the watcher launch must retry without the- breakaway bit instead of giving up.-- This mirrors the canonical pattern in- ``gateway_windows._spawn_detached`` and brings the post-update- watcher path into parity with the gateway-start path: a- breakaway-denied job object on the parent process (rare but- possible on Windows Terminal with restrictive job settings,- containers, kiosk-mode shells) shouldn't take out the entire- gateway-respawn chain.-- Static check — without standing up a real Windows job object- with breakaway forbidden, we can't trigger the OSError in a unit- test. The textual presence of the fallback helper import +- ``windows_detach_flags_without_breakaway`` in the fallback path- is the regression guard.- """- root = Path(__file__).resolve().parents[2]- text = (root / "hermes_cli" / "gateway.py").read_text(encoding="utf-8")- assert "windows_detach_flags_without_breakaway" in text, (- "launch_detached_profile_gateway_restart must import "- "windows_detach_flags_without_breakaway so it can retry a "- "breakaway-denied Popen without giving up on the watcher."- )- # And the inlined watcher's respawn must also handle the denial —- # check the symbol is referenced INSIDE the watcher block (not- # just at module scope).- marker = "watcher = textwrap.dedent("- idx = text.find(marker)- end = text.find(").strip()", idx)- block = text[idx:end]- assert "except OSError" in block- assert "windows_detach_flags_without_breakaway()" in block, (- "Inlined respawn must catch OSError on the breakaway-denied "- "CreateProcess and retry with windows_detach_flags_without_breakaway(), "- "matching gateway_windows._spawn_detached's fallback pattern."- )-- def test_watcher_threads_hidden_console_spec_into_respawn(self):- """The post-update respawn must route through- ``gateway_windows.windowless_gateway_restart_spec``.-- The spec supplies the stable cwd + env overlay (HERMES_HOME,- VIRTUAL_ENV, PYTHONPATH) so the respawned gateway doesn't depend on- the watcher's transient working directory. (The interpreter itself- stays the venv's console ``python.exe``, launched hidden via- CREATE_NO_WINDOW — see the hidden-console rationale in- ``_subprocess_compat``.)-- Static check: the watcher build (in ``_spawn_gateway_restart_watcher``)- must invoke the spec helper and thread the cwd / env overlay into- the inlined respawn ``Popen``.- """- root = Path(__file__).resolve().parents[2]- text = (root / "hermes_cli" / "gateway.py").read_text(encoding="utf-8")- assert "windowless_gateway_restart_spec" in text, (- "_spawn_gateway_restart_watcher must build the respawn via "- "gateway_windows.windowless_gateway_restart_spec so the gateway "- "comes back with the stable cwd + env overlay."- )- marker = "watcher = textwrap.dedent("- idx = text.find(marker)- end = text.find(".strip()", idx)- block = text[idx:end]- # The inlined respawn must apply the cwd + env overlay so the- # respawned gateway starts in the stable gateway working dir with- # the right venv context.- assert '_popen_kwargs["cwd"]' in block, (- "Inlined respawn must set cwd from the restart spec so the "- "gateway starts in the stable gateway working dir."- )- assert '_popen_kwargs["env"]' in block, (- "Inlined respawn must overlay env (VIRTUAL_ENV / PYTHONPATH / "- "HERMES_HOME) from the restart spec."- )class TestWindowlessGatewayRestartSpec:diff --git a/tests/tools/test_working_diff.py b/tests/tools/test_working_diff.pyindex 6fec09030be..29e40621275 100644--- a/tests/tools/test_working_diff.py+++ b/tests/tools/test_working_diff.py@@ -10,7 +10,6 @@ import subprocessimport pytest-import tools.working_diff as working_difffrom tools.working_diff import collect_working_diffpytestmark = pytest.mark.skipif(@@ -60,29 +59,6 @@ def test_unknown_mode_rejected(repo):assert "bogus" in result["error"]-def test_run_decodes_git_output_as_utf8(monkeypatch, repo):- """``_run`` must force UTF-8 decoding of git's output.-- Without ``encoding="utf-8"`` (and a lossy ``errors=``), ``subprocess.run``- falls back to the platform locale encoding. On Windows that's typically- cp932: UTF-8 multibyte output (e.g. a Japanese filename or diff content)- then either raises ``UnicodeDecodeError`` or silently decodes as mojibake,- depending on the byte sequence. The raise violates the "Never raises on- git failure" contract in ``_run``'s docstring.- """- captured = {}- real_run = subprocess.run-- def fake_run(*args, **kwargs):- captured.update(kwargs)- return real_run(*args, **kwargs)-- monkeypatch.setattr(working_diff.subprocess, "run", fake_run)-- working_diff._run(["status"], str(repo))-- assert captured.get("encoding") == "utf-8"- assert captured.get("errors") == "replace"def test_non_ascii_untracked_file_does_not_raise(repo):@@ -120,4 +96,3 @@ def test_cp932_content_is_lossy_but_never_raises(repo):assert result["success"] is Trueassert "legacy.txt" in result["diff"]- assert "\ufffd" in result["diff"] # lossy by design, matching _run_gitdiff --git a/tests/tools/test_write_approval.py b/tests/tools/test_write_approval.pyindex 37fd4ea3532..3a5cb6adf0a 100644--- a/tests/tools/test_write_approval.py+++ b/tests/tools/test_write_approval.py@@ -36,16 +36,8 @@ def _set_approval(subsystem, enabled):# Config resolution# ----------------------------------------------------------------------------def test_default_gate_is_off(hermes_home):- from tools import write_approval as wa- # Default: gate off → writes flow freely.- assert wa.write_approval_enabled("memory") is False- assert wa.write_approval_enabled("skills") is False-def test_invalid_subsystem_is_off(hermes_home):- from tools import write_approval as wa- assert wa.write_approval_enabled("bogus") is Falsedef test_list_pending_skips_non_dict_record(hermes_home):@@ -122,7 +114,7 @@ def test_cli_memory_approve_without_live_agent_uses_fresh_store(hermes_home, capdef test_load_on_disk_store_honors_configured_limits_and_permissions(hermes_home, monkeypatch):"""Fresh approval stores must match the live agent's limits and target gates."""- from tools.memory_tool import load_on_disk_store+ from tools.memory_tool import MemoryStore, load_on_disk_store# Config override path: helper picks up configured limits and store flags.monkeypatch.setattr(@@ -148,27 +140,13 @@ def test_load_on_disk_store_honors_configured_limits_and_permissions(hermes_homemonkeypatch.setattr("hermes_cli.config.load_config", _boom)fallback = load_on_disk_store()- assert fallback.memory_char_limit == 2200- assert fallback.user_char_limit == 1375+ defaults = MemoryStore()+ assert fallback.memory_char_limit == defaults.memory_char_limit+ assert fallback.user_char_limit == defaults.user_char_limitassert fallback.memory_enabled is Trueassert fallback.user_profile_enabled is True-# ----------------------------------------------------------------------------# Skill gate-# -----------------------------------------------------------------------------_SKILL = (- "---\nname: test-skill\ndescription: A test skill\nversion: 1.0.0\n---\n"- "# Test\nbody\n"-)---# ----------------------------------------------------------------------------# Pending store CRUD-# -----------------------------------------------------------------------------# ---------------------------------------------------------------------------# Shared command handler# ---------------------------------------------------------------------------@@ -294,32 +272,3 @@ def test_memory_invalid_params_rejected_before_staging(hermes_home):assert wa.pending_count("memory") == 0-class TestSkillGist:- """skill_gist builds a heuristic one-line summary for a pending skill write.-- Pure, no model call — every branch is verifiable from the function source.- """-- def test_create_with_frontmatter_description(self):- from tools import write_approval as wa- content = "---\ndescription: My cool skill\n---\nprint('hi')\n"- assert (- wa.skill_gist("create", "demo", content=content)- == f"create 'demo' — My cool skill ({len(content)} chars)"- )-- def test_edit_without_description_uses_size_only(self):- from tools import write_approval as wa- content = "no frontmatter here"- assert (- wa.skill_gist("edit", "demo", content=content)- == f"rewrite 'demo' ({len(content)} chars)"- )--- def test_file_actions_and_unknown_fallback(self):- from tools import write_approval as wa- assert wa.skill_gist("write_file", "demo", file_path="a.py") == "write a.py in 'demo'"- assert wa.skill_gist("remove_file", "demo", file_path="a.py") == "remove a.py from 'demo'"- assert wa.skill_gist("delete", "demo") == "delete skill 'demo'"- assert wa.skill_gist("unknown", "demo") == "unknown 'demo'"diff --git a/tests/tools/test_write_file_rewrite_hint.py b/tests/tools/test_write_file_rewrite_hint.pyindex 16e39ff40c8..e9876f75aee 100644--- a/tests/tools/test_write_file_rewrite_hint.py+++ b/tests/tools/test_write_file_rewrite_hint.py@@ -20,7 +20,7 @@ def test_rewrite_of_a_large_file_with_few_changes_gets_a_patch_hint(tmp_path):assert "error" not in json.loads(read_file_tool(str(f), task_id="t")) # the read→rewrite pattern the hint targetsr = json.loads(write_file_tool(str(f), new, task_id="t"))assert r.get("error") is None and f.read_text(encoding="utf-8") == new # the write still happens- assert "use patch" in r["hint"] and "798 of 800 lines were already on disk" in r["hint"]+ assert r.get("hint") # wording is free to change; presence is the contractdef test_new_files_small_files_and_real_rewrites_get_no_hint(tmp_path):diff --git a/tests/tools/test_write_verification.py b/tests/tools/test_write_verification.pyindex d784ded7609..6aa99c2066a 100644--- a/tests/tools/test_write_verification.py+++ b/tests/tools/test_write_verification.py@@ -56,8 +56,7 @@ class TestWriteVerification:with mock_patch.object(fo.hashlib, "sha256", _WrongHash):r = json.loads(write_file_tool(str(f), "actual content\n", task_id="t-wv"))assert "error" in r- assert "did not persist" in r["error"]-+def test_verification_failure_never_breaks_write(self, workdir):# sha256sum unavailable/failing -> verified omitted, write still ok.f = workdir / "ok.txt"diff --git a/tests/tools/test_x_search_tool.py b/tests/tools/test_x_search_tool.pyindex 146f03f3a6b..ce3dd5df88f 100644--- a/tests/tools/test_x_search_tool.py+++ b/tests/tools/test_x_search_tool.py@@ -70,7 +70,7 @@ def test_x_search_posts_responses_request(monkeypatch):tool_def = captured["json"]["tools"][0]assert captured["url"] == "https://api.x.ai/v1/responses"assert captured["headers"]["User-Agent"] == f"Hermes-Agent/{__version__}"- assert captured["json"]["model"] == "grok-4.5"+ assert captured["json"]["model"]assert captured["json"]["store"] is Falseassert "reasoning" not in captured["json"]assert tool_def["type"] == "x_search"@@ -95,29 +95,10 @@ def test_x_search_rejects_conflicting_handle_filters(monkeypatch):))- assert result["error"] == "allowed_x_handles and excluded_x_handles cannot be used together"+ assert result["error"]+ assert not result.get("success")-def test_x_search_schema_is_read_only_without_cross_tool_names():- """Static schema must state read-only scope without naming other surfaces.-- AGENTS.md forbids hardcoding cross-tool/skill names in tool schemas because- those surfaces may be unavailable. Keep out-of-scope guidance generic here;- xurl routing lives in the skill and feature docs.- """- from tools.x_search_tool import X_SEARCH_SCHEMA-- description = X_SEARCH_SCHEMA["description"]- lowered = description.lower()-- assert "read-only" in lowered- assert "public x" in lowered- for action in ("post", "reply", "like", "dm", "upload media", "delete"):- assert action in lowered- assert "authenticated" in lowered- # No static cross-surface names in the model-facing schema.- assert "xurl" not in lowered- assert "web_search" not in lowereddef test_x_search_extracts_inline_url_citations(monkeypatch):@@ -265,24 +246,8 @@ def test_x_search_returns_tool_error_when_no_credentials(monkeypatch):# If a model somehow invokes the tool despite a False check_fn, the call# surfaces a friendly error rather than an HTTP exception.- result = x_search_tool(query="anything")- assert "No xAI credentials available" in result- assert "hermes auth add xai-oauth" in result---# ----------------------------------------------------------------------------# Date validation — fail fast before burning an API call on a window that-# cannot possibly return X posts. xAI itself happily 200s with a fluff-# answer when the range is malformed or pure-future, which is hard for-# callers to distinguish from a real result.-# -----------------------------------------------------------------------------def _no_post_allowed(monkeypatch):- """Guard: any test that should fail before HTTP can hit this fence."""- def _fail(*_, **__):- raise AssertionError("requests.post must not be called — validation should reject first")-- monkeypatch.setattr("requests.post", _fail)+ result = json.loads(x_search_tool(query="anything"))+ assert result["error"]# ---------------------------------------------------------------------------@@ -409,26 +374,4 @@ def test_x_search_bearer_helper_falls_back_to_oauth_without_api_key(monkeypatch))-def test_x_search_bearer_requests_prefer_api_key_from_shared_resolver(monkeypatch):- """The x_search call site must opt into the shared resolver's- ``prefer_api_key`` precedence rather than re-implementing it inline."""- from tools.x_search_tool import _resolve_xai_bearer-- captured = {}-- def _fake_resolve(**kwargs):- captured.update(kwargs)- return {- "provider": "xai",- "api_key": _xcred("paid"),- "base_url": "https://api.x.ai/v1",- }-- monkeypatch.setattr(- "tools.x_search_tool.resolve_xai_http_credentials", _fake_resolve- )-- _api_key, _base_url, source = _resolve_xai_bearer()- assert captured.get("prefer_api_key") is True- assert source == "xai"diff --git a/tests/tools/test_xai_http_storage.py b/tests/tools/test_xai_http_storage.pyindex dca24e0b111..88fa8706c0c 100644--- a/tests/tools/test_xai_http_storage.py+++ b/tests/tools/test_xai_http_storage.py@@ -47,7 +47,7 @@ def test_invalid_storage_retention_falls_back_to_bounded_ttl(tmp_path, monkeypat}))_invalidate_config_cache()- from tools.xai_http import build_xai_storage_options+ from tools.xai_http import SAFE_XAI_STORAGE_EXPIRES_AFTER_SECONDS, build_xai_storage_optionsstorage = build_xai_storage_options("video_gen",@@ -56,4 +56,4 @@ def test_invalid_storage_retention_falls_back_to_bounded_ttl(tmp_path, monkeypat)assert storage is not None- assert storage["expires_after"] == 172800+ assert storage["expires_after"] == SAFE_XAI_STORAGE_EXPIRES_AFTER_SECONDSdiff --git a/tests/tools/test_yolo_mode.py b/tests/tools/test_yolo_mode.pyindex 5266d9c45d5..64896f6557f 100644--- a/tests/tools/test_yolo_mode.py+++ b/tests/tools/test_yolo_mode.py@@ -1,6 +1,5 @@"""Tests for --yolo (HERMES_YOLO_MODE) approval bypass."""-import osimport pytestimport tools.approval as approval_module@@ -100,11 +99,6 @@ class TestYoloMode:assert result["message"] is Noneassert called["value"] is False- def test_yolo_mode_not_set_by_default(self):- """HERMES_YOLO_MODE should not be set by default."""- # Clean env check — if it happens to be set in test env, that's fine,- # we just verify the mechanism exists- assert os.getenv("HERMES_YOLO_MODE") is None or True # no-op, documents intent@pytest.mark.parametrize("value", ["false", "False", "0", "off", "no"])diff --git a/tests/tools/test_zombie_process_cleanup.py b/tests/tools/test_zombie_process_cleanup.pyindex 312ce26c4bf..77fec52c023 100644--- a/tests/tools/test_zombie_process_cleanup.py+++ b/tests/tools/test_zombie_process_cleanup.py@@ -6,7 +6,6 @@ gateway deployments."""import os-import signalimport subprocessimport sysimport threading@@ -29,67 +28,6 @@ def _pid_alive(pid: int) -> bool:return False-class TestZombieReproduction:- """Demonstrate that subprocesses survive when cleanup is not called."""-- def test_orphaned_processes_survive_without_cleanup(self):- """REPRODUCTION: processes spawned directly survive if no one kills- them — this models the gap that causes zombie accumulation when- the gateway drops agent references without calling close()."""- pids = []-- try:- for _ in range(3):- proc = _spawn_sleep(60)- pids.append(proc.pid)-- for pid in pids:- assert _pid_alive(pid), f"PID {pid} should be alive after spawn"-- # Simulate "session end" by just dropping the reference- del proc # noqa: F821-- # BUG: processes are still alive after reference is dropped- for pid in pids:- assert _pid_alive(pid), (- f"PID {pid} died after ref drop — "- f"expected it to survive (demonstrating the bug)"- )- finally:- for pid in pids:- try:- os.kill(pid, signal.SIGKILL)- except (ProcessLookupError, PermissionError):- pass-- def test_explicit_terminate_reaps_processes(self):- """Explicitly terminating+waiting on Popen handles works.- This models what ProcessRegistry.kill_process does internally."""- procs = []-- try:- for _ in range(3):- proc = _spawn_sleep(60)- procs.append(proc)-- for proc in procs:- assert _pid_alive(proc.pid)-- for proc in procs:- proc.terminate()- proc.wait(timeout=5)-- for proc in procs:- assert proc.returncode is not None, (- f"PID {proc.pid} should have exited after terminate+wait"- )- finally:- for proc in procs:- try:- proc.kill()- proc.wait(timeout=1)- except Exception:- passclass TestAgentCloseMethod:@@ -245,46 +183,7 @@ class TestAgentCloseMethod:agent._session_db.end_session.assert_not_called()- def test_close_session_end_noops_without_session_db(self):- """close() is a no-op for session finalization when no DB is wired in."""- from unittest.mock import patch-- with patch("run_agent.AIAgent.__init__", return_value=None):- from run_agent import AIAgent- agent = AIAgent.__new__(AIAgent)- agent.session_id = "test-close-no-db"- agent._active_children = []- agent._active_children_lock = threading.Lock()- agent.client = None- # No _session_db / _end_session_on_close attributes at all —- # getattr defaults must keep close() from raising.- agent.close() # must not raise-- def test_close_survives_partial_failures(self):- """close() continues cleanup even if one step fails."""- from unittest.mock import patch-- with patch("run_agent.AIAgent.__init__", return_value=None):- from run_agent import AIAgent- agent = AIAgent.__new__(AIAgent)- agent.session_id = "test-close-partial"- agent._active_children = []- agent._active_children_lock = threading.Lock()- agent.client = None-- with patch(- "tools.process_registry.process_registry"- ) as mock_reg, patch(- "run_agent.cleanup_vm"- ) as mock_vm, patch(- "run_agent.cleanup_browser"- ) as mock_browser:- mock_reg.list_sessions.side_effect = RuntimeError("boom")-- agent.close()- mock_vm.assert_called_once()- mock_browser.assert_called_once()class TestGatewayCleanupWiring:diff --git a/tests/tui_gateway/test_backend_dir_entries_preconfirmed.py b/tests/tui_gateway/test_backend_dir_entries_preconfirmed.pyindex d04122a5c3d..6eecba903d3 100644--- a/tests/tui_gateway/test_backend_dir_entries_preconfirmed.py+++ b/tests/tui_gateway/test_backend_dir_entries_preconfirmed.py@@ -13,7 +13,6 @@ import jsonimport pytestfrom tui_gateway.methods_complete import _backend_dir_entries-from tools.approval_detection import detect_dangerous_commanddef _fake_terminal_tool(seen, output="src/\nREADME.md\n", exit_code=0):@@ -25,15 +24,6 @@ def _fake_terminal_tool(seen, output="src/\nREADME.md\n", exit_code=0):return _capture-def test_backend_dir_listing_is_guard_flagged_without_preconfirmation(monkeypatch):- """Premise of the regression: the internal listing shape reads as a shell -c invocation."""- seen = {}- monkeypatch.setattr("tools.terminal_tool.terminal_tool", _fake_terminal_tool(seen))- _backend_dir_entries("/workspace", session_key="sess")-- is_dangerous, pattern_key, _ = detect_dangerous_command(seen["command"])- assert is_dangerous- assert pattern_key # "shell command via -c/-lc flag"def test_backend_dir_entries_preconfirms_internal_listing(monkeypatch):@@ -46,14 +36,12 @@ def test_backend_dir_entries_preconfirms_internal_listing(monkeypatch):assert entries == [("README.md", False), ("src", True)]-def test_backend_dir_entries_keeps_session_routing_and_parses_output(monkeypatch):+def test_backend_dir_entries_keeps_session_routing(monkeypatch):seen = {}monkeypatch.setattr("tools.terminal_tool.terminal_tool", _fake_terminal_tool(seen))_backend_dir_entries("~/proj", session_key="sess-42")assert seen["kwargs"]["task_id"] == "sess-42"- assert seen["kwargs"]["timeout"] == 3- assert seen["command"].startswith("sh -c ")@pytest.mark.parametrize("payload", [diff --git a/tests/tui_gateway/test_backend_heartbeat.py b/tests/tui_gateway/test_backend_heartbeat.pyindex b7d42f4df2f..cd2113e325a 100644--- a/tests/tui_gateway/test_backend_heartbeat.py+++ b/tests/tui_gateway/test_backend_heartbeat.py@@ -16,7 +16,6 @@ refreshes it periodically. This file verifies:from __future__ import annotationsimport io-import osimport pytest@@ -71,18 +70,6 @@ class TestBackendHeartbeatRefresher:rows = db.list_backend_heartbeats()assert len(rows) == 1- def test_zero_refresh_disables_refresher(self, db, monkeypatch):- from tui_gateway import server-- monkeypatch.setattr(server, "_get_db", lambda: db)- monkeypatch.setattr(server, "_HEARTBEAT_REFRESH_S", 0.0)- monkeypatch.setattr(server, "_heartbeat_refresher_started", False)- monkeypatch.setattr(- server, "_backend_id_for_this_process",- lambda: "test-backend-A",- )-- server._start_backend_heartbeat_refresher()# Should have written the initial row exactly once, no thread started.# (The default flow with _HEARTBEAT_REFRESH_S > 0 would spawn a# thread; we asserted the helper is a no-op for repeat calls above.)@@ -101,15 +88,6 @@ class TestBackendHeartbeatRefresher:# Must not raise.server._start_backend_heartbeat_refresher()- def test_backend_id_is_stable_for_this_process(self):- """backend_id is per-process and includes a nonce for PID-reuse safety."""- from tui_gateway import server-- a = server._backend_id_for_this_process()- b = server._backend_id_for_this_process()- assert a == b # idempotent within a process- assert ":nonce" not in a # we use a hex suffix- assert str(os.getpid()) in aclass TestEntryAndWsWiring:@@ -134,7 +112,6 @@ class TestEntryAndWsWiring:monkeypatch.setattr(entry, "write_json", lambda _payload: True)monkeypatch.setattr(entry.sys, "stdin", io.StringIO(""))- import hermes_cli.model_switch as msmonkeypatch.setattr(model_switch_providers, "prewarm_picker_cache_async", lambda: None)entry.main()diff --git a/tests/tui_gateway/test_billing_rpc.py b/tests/tui_gateway/test_billing_rpc.pyindex ee0bec5a82c..2719529c752 100644--- a/tests/tui_gateway/test_billing_rpc.py+++ b/tests/tui_gateway/test_billing_rpc.py@@ -11,10 +11,8 @@ from __future__ import annotationsfrom decimal import Decimal-import pytestimport tui_gateway.server as srv-import hermes_cli.nous_billing as nbimport agent.billing_view as bvfrom agent.billing_view import BillingState, CardInfo, MonthlyCap, PaymentMethodInfo@@ -72,25 +70,3 @@ def test_billing_state_serializes_decimals_as_strings(monkeypatch):}assert res["monthly_cap"]["is_default_ceiling"] is Trueassert res["is_admin"] is True and res["can_charge"] is True---# ----------------------------------------------------------------------------# billing.charge — typed error envelopes-# ------------------------------------------------------------------------------# ----------------------------------------------------------------------------# billing.charge_status — the poll-# ------------------------------------------------------------------------------# ----------------------------------------------------------------------------# billing.auto_reload-# ------------------------------------------------------------------------------# ----------------------------------------------------------------------------# billing.step_up-# -----------------------------------------------------------------------------diff --git a/tests/tui_gateway/test_bot_delivery_poll_throttle.py b/tests/tui_gateway/test_bot_delivery_poll_throttle.pydeleted file mode 100644index c88128de5c4..00000000000--- a/tests/tui_gateway/test_bot_delivery_poll_throttle.py+++ /dev/null@@ -1,51 +0,0 @@-"""Idle notification poller must not probe bot-delivery on every 0.5s queue tick (#108005)."""--from __future__ import annotations--import threading-import time-import queue--import tui_gateway.server as server-from tools.process_registry import process_registry---def test_idle_poller_throttles_bot_live_delivery_probe(monkeypatch):- """Drive the bound poller: ~1.2s of 0.5s idle ticks must not call the probe every iteration.-- Pre-fix every loop iteration hits ``_poll_bot_live_delivery_once`` (~2/s → 3 calls).- Post-fix the first iteration fires promptly, then the 5.0s cadence holds (exactly 1).- """- calls: list[float] = []-- def _probe(_sid, _session):- calls.append(time.monotonic())- return False-- monkeypatch.setattr(server, "_poll_bot_live_delivery_once", _probe)- monkeypatch.setattr(server, "_notif_poll_kanban", lambda *_a, **_k: None)- monkeypatch.setattr(server, "_maybe_fire_tui_loop_tick", lambda *_a, **_k: None)- monkeypatch.setattr(server, "_maybe_fire_tui_heartbeat_tick", lambda *_a, **_k: None)- monkeypatch.setattr(process_registry, "completion_queue", queue.Queue())-- session = {- "session_key": "sid-bot-delivery-throttle",- "history_lock": threading.Lock(),- "_finalized": False,- }- stop = threading.Event()- thread = threading.Thread(- target=server._notification_poller_loop,- args=(stop, "sid-bot-delivery-throttle", session),- daemon=True,- name="tui-notif-poller-bot-delivery-throttle",- )- thread.start()- try:- time.sleep(1.2)- finally:- stop.set()- thread.join(timeout=5)-- assert thread.is_alive() is False- assert len(calls) == 1, f"idle bot-delivery probe ran {len(calls)} times in ~1.2s; expected 1, not every 0.5s tick"diff --git a/tests/tui_gateway/test_bot_live_owner_delivery.py b/tests/tui_gateway/test_bot_live_owner_delivery.pyindex e15a72ecb2e..c069f3bae18 100644--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@ -144,9 +144,7 @@ def test_failing_mailbox_poll_warns_once_per_window():for now in (0.0, 6.0, 12.0, 61.0): # the poller calls at _BOT_DELIVERY_POLL_SECONDS cadenceguarded("live", session, now)warnings = [r for r in records if r.levelno == logging.WARNING]- assert [r.getMessage() for r in warnings] == [- "Bot live-owner delivery poll failed (0 repeat(s) suppressed since the last report)",- "Bot live-owner delivery poll failed (2 repeat(s) suppressed since the last report)"]+ assert len(warnings) == 2 # t=0 and t=61; the two in-window repeats are suppressedassert all(r.exc_info for r in warnings)diff --git a/tests/tui_gateway/test_cold_start_gil_stall.py b/tests/tui_gateway/test_cold_start_gil_stall.pyindex 9fc7585efb8..0533c380830 100644--- a/tests/tui_gateway/test_cold_start_gil_stall.py+++ b/tests/tui_gateway/test_cold_start_gil_stall.py@@ -13,13 +13,8 @@ between ``HERMES_BACKEND_READY`` and the first prompt. Three fixes:import on the loop thread."""-import asyncio-import inspect-import sys-from unittest.mock import patch, MagicMock+from unittest.mock import patch-import pytest-import hermes_cli.web_server_lifecycle as _web_server_lifecycle# ─── Fix 1: copilot_auth skips gh CLI when env var is set ──────────────@@ -78,121 +73,10 @@ class TestCopilotAuthSkipsGhCli:# ─── Fix 2: resolve_skin runs via to_thread in handle_ws ───────────────-def test_handle_ws_resolves_skin_off_the_loop_thread():- """resolve_skin must run on a worker thread, not the event loop (#60800).- Behavioral check (not source inspection): run the ready-payload path- with a resolve_skin stub that records its thread ident and assert it- differs from the loop thread's. Pattern from the #72720 salvage.- """- import asyncio as _asyncio- import threading-- import tui_gateway.server as server_mod-- idents = {}-- def _fake_resolve_skin():- idents["skin_thread"] = threading.get_ident()- return {"palette": "test"}-- async def _scenario():- idents["loop_thread"] = threading.get_ident()- with patch.object(server_mod, "resolve_skin", _fake_resolve_skin):- payload = await _asyncio.to_thread(server_mod.resolve_skin)- return payload-- payload = _asyncio.run(_scenario())- assert payload == {"palette": "test"}- assert idents["skin_thread"] != idents["loop_thread"], (- "resolve_skin ran on the event loop thread — the #60800 cold-start "- "stall would be back."- )---def test_handle_ws_ready_payload_wires_skin_through_to_thread():- """The gateway.ready payload construction must route resolve_skin- through asyncio.to_thread with change_events preserved.-- Exercises handle_ws's actual payload site by faking the transport- and asserting on the written frame.- """- import asyncio as _asyncio- import threading-- import tui_gateway.server as server_mod- import tui_gateway.ws as ws_mod-- idents = {}- frames = []-- def _fake_resolve_skin():- idents["skin_thread"] = threading.get_ident()- return {"palette": "wired"}-- async def _scenario():- idents["loop_thread"] = threading.get_ident()- with patch.object(server_mod, "resolve_skin", _fake_resolve_skin):- # Reproduce handle_ws's ready-frame construction verbatim.- skin_payload = await _asyncio.to_thread(server_mod.resolve_skin)- frames.append(- {- "jsonrpc": "2.0",- "method": "event",- "params": {- "type": "gateway.ready",- "payload": {"skin": skin_payload, "change_events": True},- },- }- )-- _asyncio.run(_scenario())-- assert frames[0]["params"]["payload"]["skin"] == {"palette": "wired"}- assert frames[0]["params"]["payload"]["change_events"] is True- assert idents["skin_thread"] != idents["loop_thread"]- # Belt and braces: the production site must still route through- # to_thread — assert against the live source so a revert to inline- # resolve_skin() cannot slip past the behavioral stub above.- source = inspect.getsource(ws_mod.handle_ws)- assert "to_thread(server.resolve_skin)" in source# ─── Fix 3: _warm_gateway_module pre-imports heavy chains ──────────────-def test_warm_gateway_module_imports_cold_start_chains():- """_warm_gateway_module must pre-import the module chains that the- first WS connection + RPC burst would otherwise import on the loop- thread (#60800).-- Real-import test: run the actual function (no stubs), then assert- every cold-start-critical module is present in sys.modules. This- catches a typo in the warm tuple — _warm_gateway_module swallows- ImportError by design (except-pass), so a tracking-stub test that- raises ImportError for every name would pass even if a module name- were misspelled.- """- import sys-- import hermes_cli.web_server as web_server_mod-- required = {- "hermes_cli.gateway",- "hermes_cli.auth",- "hermes_cli.copilot_auth",- "hermes_cli.runtime_provider",- "hermes_cli.skin_engine",- "hermes_cli.inventory",- "hermes_cli.model_switch",- }-- _web_server_lifecycle._warm_gateway_module()-- missing = required - set(sys.modules)- assert not missing, (- f"_warm_gateway_module did not import cold-start-critical modules: "- f"{missing}. A typo in the warm tuple is silently swallowed by its "- f"except-pass — this real-import test is the only guard (#60800)."- )diff --git a/tests/tui_gateway/test_compress_lock_skip.py b/tests/tui_gateway/test_compress_lock_skip.pyindex a47f8aec925..4654fc5f213 100644--- a/tests/tui_gateway/test_compress_lock_skip.py+++ b/tests/tui_gateway/test_compress_lock_skip.py@@ -101,7 +101,6 @@ def test_session_compress_rpc_returns_lock_held_payload():result = r["result"]assert result["lock_held"] is Trueassert result["compressed"] is False- assert "Compression already in progress" in result["message"]assert "pid=4242" in result["message"]assert "No changes from compression" not in result["message"]@@ -135,7 +134,6 @@ def test_command_dispatch_compress_reports_lock_skip_as_output_not_error():assert "error" not in r, f"lock-skip surfaced as error: {r.get('error')}"output = r["result"]["output"]assert r["result"]["type"] == "exec"- assert "Compression already in progress" in outputassert "pid=5150" in outputassert "compress failed" not in outputassert "No changes from compression" not in output@@ -164,7 +162,6 @@ def test_mirror_slash_side_effects_reports_lock_skip():finally:server._sessions.pop(sid, None)- assert "Compression already in progress" in outputassert "pid=6161" in outputassert "No changes from compression" not in outputassert "live session sync failed" not in outputdiff --git a/tests/tui_gateway/test_compression_config_hot_reload.py b/tests/tui_gateway/test_compression_config_hot_reload.pyindex b285e91fc9d..81287784066 100644--- a/tests/tui_gateway/test_compression_config_hot_reload.py+++ b/tests/tui_gateway/test_compression_config_hot_reload.py@@ -171,14 +171,6 @@ def test_absent_threshold_tokens_keeps_default_cap_on_1m_window(monkeypatch):-def test_prompt_submit_calls_compression_sync_after_model_sync():- # Read the module that actually defines the turn (it moved out of server.py).- source = open(server._run_prompt_submit.__code__.co_filename, encoding="utf-8").read()- model_idx = source.find("_sync_agent_model_with_config(sid, session)")- compression_idx = source.find("_sync_agent_compression_with_config(sid, session)")- assert model_idx != -1- assert compression_idx != -1- assert model_idx < compression_idx# ── Unset semantics (#94724 review finding on #95980) ────────────────────@@ -217,53 +209,34 @@ def _sync_with_cfg(monkeypatch, session, cfg):server._sync_agent_compression_with_config("sid-unset", session)-def test_removing_tail_mode_restores_lean_default(monkeypatch):- session, compressor = _neutral_session(tail_mode="legacy")- assert compressor.tail_mode == "legacy"- _sync_with_cfg(monkeypatch, session, {"compression": {}})- assert compressor.tail_mode == "lean"---def test_removing_target_ratio_restores_default(monkeypatch):- session, compressor = _neutral_session(summary_target_ratio=0.60)- assert compressor.summary_target_ratio == 0.60- _sync_with_cfg(monkeypatch, session, {"compression": {}})- assert compressor.summary_target_ratio == 0.20---def test_removing_protect_last_n_restores_default(monkeypatch):- session, compressor = _neutral_session(protect_last_n=5)- _sync_with_cfg(monkeypatch, session, {"compression": {}})- assert compressor.protect_last_n == 20---def test_removing_proactive_prune_keys_restores_defaults(monkeypatch):+def test_removing_compressor_keys_restores_fresh_build_values(monkeypatch):+ """Absent keys must land on exactly what a fresh ContextCompressor installs, not stale values."""session, compressor = _neutral_session(+ tail_mode="legacy",+ summary_target_ratio=0.60,+ protect_last_n=5,proactive_prune_tokens=48_000,proactive_prune_min_result_chars=30_000,proactive_prune_min_reclaim_tokens=1,- )- _sync_with_cfg(monkeypatch, session, {"compression": {}})- assert compressor.proactive_prune_tokens == 0- assert compressor.proactive_prune_min_result_chars == 8000- assert compressor.proactive_prune_min_reclaim_tokens == 4096---def test_removing_min_tail_user_messages_restores_default(monkeypatch):- session, compressor = _neutral_session(min_tail_user_messages=4)- _sync_with_cfg(monkeypatch, session, {"compression": {}})- assert compressor.min_tail_user_messages == 1---def test_removing_model_thresholds_restores_empty_map(monkeypatch):- session, compressor = _neutral_session(- model_thresholds={"unset-test-model": 0.95}+ min_tail_user_messages=4,+ model_thresholds={"unset-test-model": 0.95},)assert compressor.threshold_percent == 0.95_sync_with_cfg(monkeypatch, session, {"compression": {}})- assert compressor.model_thresholds == {}- # The stale per-model override must stop steering the live threshold too.- assert compressor.threshold_percent == 0.50++ _, fresh = _neutral_session()+ for attr in (+ "tail_mode",+ "summary_target_ratio",+ "protect_last_n",+ "proactive_prune_tokens",+ "proactive_prune_min_result_chars",+ "proactive_prune_min_reclaim_tokens",+ "min_tail_user_messages",+ "model_thresholds",+ "threshold_percent", # the stale per-model override must stop steering the live threshold+ ):+ assert getattr(compressor, attr) == getattr(fresh, attr), attrdef test_removing_threshold_restores_derived_default(monkeypatch):diff --git a/tests/tui_gateway/test_compute_host_borrowed_lease.py b/tests/tui_gateway/test_compute_host_borrowed_lease.pyindex 7b643fa6c0e..bb09670d352 100644--- a/tests/tui_gateway/test_compute_host_borrowed_lease.py+++ b/tests/tui_gateway/test_compute_host_borrowed_lease.py@@ -31,7 +31,7 @@ def _frames(out: io.StringIO) -> list[dict]:return [json.loads(line) for line in out.getvalue().splitlines() if line.strip()]-def _wait(out: io.StringIO, predicate, timeout: float = 5.0) -> dict:+def _wait(out: io.StringIO, predicate, timeout: float = 30.0) -> dict:deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:for frame in _frames(out):@@ -123,7 +123,7 @@ def isolated_env(monkeypatch, tmp_path):server._sessions.pop(sid, None)-def _run_turn(frame: dict, timeout: float = 5.0) -> tuple[list[dict], dict | None]:+def _run_turn(frame: dict, timeout: float = 30.0) -> tuple[list[dict], dict | None]:"""Run one turn.start through the real child path; return (all frames, turn.end frame)."""out = io.StringIO()host = ComputeHost(stdout=out, heartbeat_secs=0)diff --git a/tests/tui_gateway/test_compute_host_phase1.py b/tests/tui_gateway/test_compute_host_phase1.pyindex a9eda851ef0..f86d5d38b08 100644--- a/tests/tui_gateway/test_compute_host_phase1.py+++ b/tests/tui_gateway/test_compute_host_phase1.py@@ -4,14 +4,11 @@ import osimport sysimport threadingimport time-from pathlib import Path-import pytestfrom tui_gateway import compute_host, serverfrom tui_gateway.compute_host import ComputeHost, _default_workersfrom tui_gateway.host_supervisor import (- MUTATOR_ROUTE_TABLE,HostSupervisor,append_log_record,)@@ -35,17 +32,17 @@ def _wait_for_frame(out: io.StringIO, predicate, timeout: float = 2.0) -> dict:raise AssertionError(f"timed out waiting for frame; saw={_json_lines(out)}")-def test_compute_host_workers_inherit_tui_pool_env_or_8(monkeypatch):+def test_compute_host_workers_inherit_tui_pool_env(monkeypatch):monkeypatch.delenv("HERMES_TUI_RPC_POOL_WORKERS", raising=False)monkeypatch.delenv("HERMES_COMPUTE_HOST_WORKERS", raising=False)- assert _default_workers() == 8+ default = _default_workers()monkeypatch.setenv("HERMES_TUI_RPC_POOL_WORKERS", "11")assert _default_workers() == 11- # Dead-RC tombstone: malformed env falls back to 8, not the old except-branch 4.+ # Malformed env falls back to the same default as unset.monkeypatch.setenv("HERMES_TUI_RPC_POOL_WORKERS", "not-an-int")- assert _default_workers() == 8+ assert _default_workers() == defaultdef test_compute_host_routes_relayed_response_and_lock_to_its_open_request(monkeypatch):@@ -80,22 +77,6 @@ def test_compute_host_routes_relayed_response_and_lock_to_its_open_request(monkehost.close()-def test_mutator_route_table_matches_prd_inventory():- assert MUTATOR_ROUTE_TABLE == {- "prompt.submit": "turn-path",- "session.interrupt": "turn-path",- "reload.mcp": "run-concurrent",- "session.save": "run-concurrent",- "session.compress": "idle-gated",- "prompt.submit.truncate": "idle-gated",- "slash.model": "idle-gated",- "slash.personality": "idle-gated",- "slash.prompt": "idle-gated",- "slash.compress": "idle-gated",- "session.reset": "idle-gated",- "session.history.reload": "idle-gated",- "slash.retry": "idle-gated",- }def test_append_log_record_single_write_lines(tmp_path):diff --git a/tests/tui_gateway/test_compute_host_turn_protocol.py b/tests/tui_gateway/test_compute_host_turn_protocol.pyindex 92e85bbd5bf..bb92e7a21bf 100644--- a/tests/tui_gateway/test_compute_host_turn_protocol.py+++ b/tests/tui_gateway/test_compute_host_turn_protocol.py@@ -25,7 +25,7 @@ def _frames(out: io.StringIO) -> list[dict]:return [json.loads(line) for line in out.getvalue().splitlines() if line.strip()]-def _wait(out: io.StringIO, predicate, timeout: float = 5.0) -> dict:+def _wait(out: io.StringIO, predicate, timeout: float = 30.0) -> dict:deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:for frame in _frames(out):diff --git a/tests/tui_gateway/test_config_set_display_toggles.py b/tests/tui_gateway/test_config_set_display_toggles.pyindex ef1578e55d2..a845da134d6 100644--- a/tests/tui_gateway/test_config_set_display_toggles.py+++ b/tests/tui_gateway/test_config_set_display_toggles.py@@ -44,13 +44,3 @@ def test_a_non_boolean_is_refused_rather_than_written(config_home):assert not config_home.exists()-def test_every_key_the_renderer_mirrors_is_listed():- """The list is the contract: a switch missing from it silently does nothing.-- Kept as a relationship rather than a snapshot — it asserts that the tools- which gate on `display.<x>` all have `<x>` reachable through config.set,- not that the set has some particular size.- """- gated = {"display.message_reactions", "display.in_app_tips", "display.in_app_tours"}-- assert gated <= server._DISPLAY_TOGGLE_KEYS