Skip to content

The agent that grows with you

test: purge low-value tests, lane py16 (624 removed)

teknium1524c38a98add
diff --git a/tests/plugins/test_kanban_worker_runs.py b/tests/plugins/test_kanban_worker_runs.py
deleted file mode 100644
index 6ac1c35dccf..00000000000
--- a/tests/plugins/test_kanban_worker_runs.py
+++ /dev/null
@@ -1,154 +0,0 @@
-"""Tests for kanban worker/runs read endpoints.
-
-Covers:
- GET /workers/active
- GET /runs/{run_id}
- GET /runs/{run_id}/inspect
- POST /runs/{run_id}/terminate
-"""
-
-from __future__ import annotations
-
-import importlib.util
-import secrets
-import sys
-import time
-from pathlib import Path
-from unittest.mock import MagicMock
-
-import pytest
-from fastapi import FastAPI
-from fastapi.testclient import TestClient
-
-from hermes_cli import kanban_db as kb
-
-
-# ---------------------------------------------------------------------------
-# Fixtures
-# ---------------------------------------------------------------------------
-
-def _load_plugin_router():
- """Dynamically load plugins/kanban/dashboard/plugin_api.py and return its router."""
- repo_root = Path(__file__).resolve().parents[2]
- plugin_file = repo_root / "plugins" / "kanban" / "dashboard" / "plugin_api.py"
- assert plugin_file.exists(), f"plugin file missing: {plugin_file}"
-
- mod_name = "hermes_dashboard_plugin_kanban_worker_runs_test"
- # Re-use a cached module if already loaded to avoid duplicate-router issues.
- if mod_name in sys.modules:
- return sys.modules[mod_name].router
-
- spec = importlib.util.spec_from_file_location(mod_name, plugin_file)
- assert spec is not None and spec.loader is not None
- mod = importlib.util.module_from_spec(spec)
- sys.modules[mod_name] = mod
- spec.loader.exec_module(mod)
- return mod.router
-
-
-def kanban_home(tmp_path, monkeypatch):
- """Isolated HERMES_HOME with an empty kanban DB."""
- home = tmp_path / ".hermes"
- home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- kb.init_db()
- return home
-
-
-def client(kanban_home):
- app = FastAPI()
- app.include_router(_load_plugin_router(), prefix="/api/plugins/kanban")
- return TestClient(app)
-
-
-def _insert_run(conn, task_id, *, worker_pid=None, ended_at=None):
- """Insert a task_runs row directly (bypassing claim machinery) and return run_id."""
- lock = secrets.token_hex(8)
- future = int(time.time()) + 3600
- cur = conn.execute(
- "INSERT INTO task_runs "
- "(task_id, status, claim_lock, claim_expires, worker_pid, started_at, ended_at) "
- "VALUES (?, 'running', ?, ?, ?, ?, ?)",
- (task_id, lock, future, worker_pid, int(time.time()), ended_at),
- )
- conn.commit()
- return cur.lastrowid
-
-
-# ---------------------------------------------------------------------------
-# GET /workers/active
-# ---------------------------------------------------------------------------
-
-def test_workers_active_empty_board(client):
- """Board with no running tasks returns an empty workers list."""
- r = client.get("/api/plugins/kanban/workers/active")
- assert r.status_code == 200
- body = r.json()
- assert body["workers"] == []
- assert body["count"] == 0
- assert "checked_at" in body
-
-
-# ---------------------------------------------------------------------------
-# GET /runs/{run_id}
-# ---------------------------------------------------------------------------
-
-def test_get_run_404_unknown_id(client):
- """Non-existent run_id returns 404."""
- r = client.get("/api/plugins/kanban/runs/999999")
- assert r.status_code == 404
- assert "999999" in r.json()["detail"]
-
-
-# ---------------------------------------------------------------------------
-# GET /runs/{run_id}/inspect
-# ---------------------------------------------------------------------------
-
-def test_inspect_run_404(client):
- """Non-existent run_id returns 404."""
- r = client.get("/api/plugins/kanban/runs/888888/inspect")
- assert r.status_code == 404
-
-
-# ---------------------------------------------------------------------------
-# POST /runs/{run_id}/terminate
-# ---------------------------------------------------------------------------
-
-def _setup_running_task_with_run(conn, *, title, assignee, worker_pid):
- """Create a task in 'running' state with a matching open task_runs row.
-
- Mirrors what dispatcher_claim does: stamps tasks.status='running',
- tasks.claim_lock, tasks.worker_pid; inserts task_runs row with the
- same claim_lock so reclaim_task's preconditions are satisfied.
- """
- task_id = kb.create_task(conn, title=title, assignee=assignee)
- lock = secrets.token_hex(8)
- future = int(time.time()) + 3600
- conn.execute(
- "UPDATE tasks SET status='running', claim_lock=?, "
- "claim_expires=?, worker_pid=? WHERE id=?",
- (lock, future, worker_pid, task_id),
- )
- cur = conn.execute(
- "INSERT INTO task_runs "
- "(task_id, status, claim_lock, claim_expires, worker_pid, started_at) "
- "VALUES (?, 'running', ?, ?, ?, ?)",
- (task_id, lock, future, worker_pid, int(time.time())),
- )
- conn.commit()
- return task_id, cur.lastrowid
-
-
-def test_terminate_run_404_unknown_id(client):
- """POST to unknown run_id returns 404."""
- r = client.post(
- "/api/plugins/kanban/runs/777777/terminate",
- json={"reason": "test"},
- )
- assert r.status_code == 404
- assert "777777" in r.json()["detail"]
-
-
diff --git a/tests/plugins/test_langfuse_plugin.py b/tests/plugins/test_langfuse_plugin.py
index 4e5d58cf837..69b0eca9dab 100644
--- a/tests/plugins/test_langfuse_plugin.py
+++ b/tests/plugins/test_langfuse_plugin.py
@@ -10,35 +10,6 @@ from types import SimpleNamespace
import pytest
-import yaml
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-PLUGIN_DIR = REPO_ROOT / "plugins" / "observability" / "langfuse"
-
-
-# ---------------------------------------------------------------------------
-# Manifest + layout
-# ---------------------------------------------------------------------------
-
-class TestManifest:
-
- def test_manifest_fields(self):
- data = yaml.safe_load((PLUGIN_DIR / "plugin.yaml").read_text())
- assert data["name"] == "langfuse"
- assert data["version"]
- # All eleven hooks the plugin implements, declared under the field discovery/validate read (#108371).
- assert set(data["provides_hooks"]) == {
- "pre_api_request", "post_api_request", "api_request_error",
- "pre_llm_call", "post_llm_call",
- "pre_tool_call", "post_tool_call",
- "on_session_finalize", "on_session_end",
- "subagent_start", "subagent_stop",
- }
- # Required env vars are the user-facing HERMES_ prefixed keys.
- assert "HERMES_LANGFUSE_PUBLIC_KEY" in data["requires_env"]
- assert "HERMES_LANGFUSE_SECRET_KEY" in data["requires_env"]
-
# ---------------------------------------------------------------------------
# Plugin discovery: langfuse is opt-in (not loaded unless explicitly enabled).
@@ -102,42 +73,6 @@ class TestRuntimeGate:
messages = [record.getMessage() for record in caplog.records]
assert len(messages) == 1
- assert "SDK is unavailable" in messages[0]
- assert "tracing is disabled" in messages[0]
-
- def test_get_langfuse_caches_failure_no_config_load(self, monkeypatch):
- """A miss must be cached — no per-hook config.yaml reads, no env re-reads."""
- for k in (
- "HERMES_LANGFUSE_PUBLIC_KEY", "HERMES_LANGFUSE_SECRET_KEY",
- "LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY",
- ):
- monkeypatch.delenv(k, raising=False)
-
- langfuse_plugin = self._fresh_plugin()
-
- # Prime the cache with one call.
- assert langfuse_plugin._get_langfuse() is None
-
- # Now block os.environ.get — a correctly-cached plugin must not
- # touch env again.
- import os
- called = {"n": 0}
- real_get = os.environ.get
-
- def tracking_get(key, default=None):
- if key.startswith(("HERMES_LANGFUSE_", "LANGFUSE_")):
- called["n"] += 1
- return real_get(key, default)
-
- monkeypatch.setattr(os.environ, "get", tracking_get)
-
- for _ in range(20):
- assert langfuse_plugin._get_langfuse() is None
-
- assert called["n"] == 0, (
- f"_get_langfuse() re-read env {called['n']} times after cache miss — "
- "it should short-circuit via _INIT_FAILED"
- )
# ---------------------------------------------------------------------------
@@ -199,23 +134,6 @@ class TestPayloadSanitization:
}
-class TestTraceScopeKey:
- def _fresh_plugin(self):
- mod_name = "plugins.observability.langfuse"
- sys.modules.pop(mod_name, None)
- return importlib.import_module(mod_name)
-
- def test_trace_key_scopes_by_turn_id_when_available(self):
- plugin = self._fresh_plugin()
-
- key_a = plugin._trace_key("task-1", "session-1", turn_id="turn-a")
- key_b = plugin._trace_key("task-1", "session-1", turn_id="turn-b")
-
- assert key_a != key_b
- assert "turn:turn-a" in key_a
- assert "turn:turn-b" in key_b
-
-
# ---------------------------------------------------------------------------
# End-to-end collision regression: two turns of ONE gateway session must not
# share trace state. The helper-level tests above prove _trace_key returns
@@ -601,33 +519,6 @@ class TestRequestMessageCoercion:
) == [{"role": "user", "content": "h"}]
assert mod._coerce_request_messages(user_message="u") == [{"role": "user", "content": "u"}]
- def test_messages_for_langfuse_includes_anthropic_system_param(self):
- sys.modules.pop("plugins.observability.langfuse", None)
- mod = importlib.import_module("plugins.observability.langfuse")
-
- out = mod._messages_for_langfuse_input(
- request_messages=[{"role": "user", "content": "hi"}],
- system_prompt="You are Hermes.",
- )
- assert out[0]["role"] == "system"
- assert out[0]["content"] == "You are Hermes."
- assert out[1]["role"] == "user"
-
- def test_messages_for_langfuse_skips_duplicate_system(self):
- sys.modules.pop("plugins.observability.langfuse", None)
- mod = importlib.import_module("plugins.observability.langfuse")
-
- out = mod._messages_for_langfuse_input(
- request_messages=[
- {"role": "system", "content": "already here"},
- {"role": "user", "content": "hi"},
- ],
- system_prompt="ignored when messages include system",
- )
- assert out[0]["role"] == "system"
- assert out[0]["content"] == "already here"
- assert out[1]["role"] == "user"
-
class TestAssistantMessageSerialization:
def test_serialize_assistant_message_prefers_reasoning(self):
@@ -1075,7 +966,6 @@ class TestCostTotal:
base_url="",
)
- assert cost_details["total"] == pytest.approx(0.0111)
components = {k: v for k, v in cost_details.items() if k != "total"}
assert components
assert cost_details["total"] == pytest.approx(sum(components.values()))
@@ -1218,35 +1108,6 @@ class TestCaptureModes:
text = "here sk-abcdefghijklmnop1234 done"
assert mod._capture_content(text) == text
- def test_capture_mode_recorded_in_trace_metadata(self, monkeypatch):
- mod = self._fresh_plugin()
- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "metadata")
- seen = {}
-
- class _Span:
- def update(self, **kw): pass
- def end(self, **kw): pass
- def set_trace_io(self, **kw): pass
- def start_observation(self, **kw): return _Span()
-
- class _RootCM:
- def __enter__(self): return _Span()
- def __exit__(self, *exc): return False
-
- class _Client:
- def create_trace_id(self, seed=None): return "t1"
- def start_as_current_observation(self, **kw):
- seen.update(kw)
- return _RootCM()
-
- state = mod._start_root_trace(
- "k", task_id="t", session_id="s", platform="cli", provider="p",
- model="m", api_mode="chat", messages=[{"role": "user", "content": "hi"}],
- client=_Client(),
- )
- assert seen["metadata"]["capture_mode"] == "metadata"
- assert state is not None
-
# ---------------------------------------------------------------------------
# api_request_error hook
@@ -1835,17 +1696,6 @@ class TestSystemPromptInGenerationInput:
kwargs["system_prompt"] = system_prompt
mod.on_pre_llm_request(**kwargs)
- def test_string_system_prompt_prepended(self, monkeypatch):
- mod = self._make_mod()
- captured = self._capture_generation(mod, monkeypatch)
- self._fire(
- mod,
- request_messages=[{"role": "user", "content": "hi"}],
- system_prompt="You are Hermes.",
- )
- assert captured["input"][0]["role"] == "system"
- assert captured["input"][0]["content"] == "You are Hermes."
- assert captured["input"][1]["role"] == "user"
def test_anthropic_block_list_flattened(self, monkeypatch):
"""Anthropic OAuth mode sends ``system`` as content blocks (with
@@ -1866,22 +1716,6 @@ class TestSystemPromptInGenerationInput:
assert "part one" in first["content"]
assert "part two" in first["content"]
- def test_no_duplicate_when_messages_already_carry_system(self, monkeypatch):
- """chat_completions keeps system in messages[0]; forwarding
- system_prompt as well must not produce two system entries."""
- mod = self._make_mod()
- captured = self._capture_generation(mod, monkeypatch)
- self._fire(
- mod,
- request_messages=[
- {"role": "system", "content": "You are Hermes."},
- {"role": "user", "content": "hi"},
- ],
- system_prompt="You are Hermes.",
- )
- roles = [m["role"] for m in captured["input"]]
- assert roles.count("system") == 1
- assert roles[0] == "system"
def test_absent_system_prompt_keeps_previous_shape(self, monkeypatch):
mod = self._make_mod()
@@ -1902,18 +1736,7 @@ class TestSystemPromptInGenerationInput:
]
self._fire(mod, request_messages=many, system_prompt="SYS")
assert captured["input"][0]["role"] == "system"
- # window (12) + prepended system
- assert len(captured["input"]) == 13
-
- def test_metadata_records_chars(self, monkeypatch):
- mod = self._make_mod()
- captured = self._capture_generation(mod, monkeypatch)
- self._fire(
- mod,
- request_messages=[{"role": "user", "content": "hi"}],
- system_prompt="You are Hermes.",
- )
- assert captured["metadata"]["system_prompt_chars"] == len("You are Hermes.")
+ assert captured["input"][0]["content"] == "SYS"
class TestSystemPromptCrossesHookBoundary:
diff --git a/tests/plugins/test_plugin_dashboard_auth_contract.py b/tests/plugins/test_plugin_dashboard_auth_contract.py
deleted file mode 100644
index 1d8ad035ae6..00000000000
--- a/tests/plugins/test_plugin_dashboard_auth_contract.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Guardrail: dashboard plugins must NOT read the session token directly.
-
-The dashboard host exposes a sanctioned, gated-mode-aware auth surface on the
-plugin SDK (``window.__HERMES_PLUGIN_SDK__``): ``fetchJSON`` (JSON REST),
-``authedFetch`` (uploads / blob downloads), and ``buildWsUrl`` /
-``buildWsAuthParam`` (WebSockets). These handle BOTH dashboard auth modes —
-loopback (``X-Hermes-Session-Token`` header) and gated OAuth
-(``hermes_session_at`` cookie / single-use ``?ticket=``).
-
-Plugins that hand-roll ``fetch`` / ``WebSocket`` and read
-``window.__HERMES_SESSION_TOKEN__`` directly send an empty token in gated mode
-and 401/1008. That bug shipped in the kanban and achievements plugins and was
-invisible until the dashboard ran gated on hosted Fly agents.
-
-This test fails if any bundled plugin's frontend reads the token global
-directly, forcing new/edited plugins through the SDK surface instead. It is
-the enforcement half of the "single sanctioned auth surface" design — the SDK
-helpers are the carrot, this test is the stick.
-
-If you have a legitimate reason to reference the token name (e.g. a comment
-explaining why NOT to use it), add the file to ``_ALLOWED_FILES`` with a note.
-"""
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-
-# Repo root: tests/plugins/<this file> → ../../
-_REPO_ROOT = Path(__file__).resolve().parents[2]
-_PLUGINS_DIR = _REPO_ROOT / "plugins"
-
-# The forbidden global. Reading it directly bypasses the gated-mode auth path.
-_FORBIDDEN = "__HERMES_SESSION_TOKEN__"
-
-# Files explicitly allowed to mention the token (none today). Map path →
-# reason so the allowance is self-documenting if one is ever needed.
-_ALLOWED_FILES: dict[str, str] = {}
-
-
-def _plugin_frontend_bundles() -> list[Path]:
- """Every plugin-shipped JS bundle the dashboard loads into the browser."""
- if not _PLUGINS_DIR.is_dir():
- return []
- # Plugin dashboards live at plugins/<name>/dashboard/dist/*.js
- return sorted(_PLUGINS_DIR.glob("*/dashboard/dist/*.js"))
-
-
-def test_there_are_plugin_bundles_to_check() -> None:
- """Sanity: the glob actually finds the bundles, so a future layout change
- doesn't silently turn this guard into a no-op."""
- bundles = _plugin_frontend_bundles()
- names = {b.parent.parent.parent.name for b in bundles}
- # kanban + hermes-achievements are bundled today; assert at least one is
- # found so the guard can't pass vacuously.
- assert bundles, "no plugin dashboard bundles found — glob/layout drift?"
- assert names, "could not resolve plugin names from bundle paths"
-
-
- "bundle",
- _plugin_frontend_bundles(),
- ids=lambda p: str(p.relative_to(_REPO_ROOT)),
-)
-def test_plugin_bundle_does_not_read_session_token(bundle: Path) -> None:
- rel = str(bundle.relative_to(_REPO_ROOT))
- text = bundle.read_text(encoding="utf-8", errors="replace")
-
- if rel in _ALLOWED_FILES:
- return # explicitly allowed (with a documented reason)
-
- # Only flag CODE reads of the token global, not mentions in ``//`` comments
- # (e.g. a comment explaining why the SDK helper is used instead). A line is
- # a code read if it contains the global and the global appears before any
- # ``//`` comment marker on that line.
- offending: list[str] = []
- for i, line in enumerate(text.splitlines(), start=1):
- idx = line.find(_FORBIDDEN)
- if idx == -1:
- continue
- comment_idx = line.find("//")
- in_comment = comment_idx != -1 and comment_idx < idx
- if not in_comment:
- offending.append(f" {i}: {line.strip()}")
-
- if not offending:
- return
-
- pytest.fail(
- f"{rel} reads {_FORBIDDEN} directly — this bypasses gated-mode auth "
- f"and 401/1008s on OAuth-gated dashboards. Use the plugin SDK instead: "
- f"SDK.fetchJSON (JSON), SDK.authedFetch (uploads/downloads), or "
- f"SDK.buildWsUrl (WebSockets). Offending lines:\n" + "\n".join(offending)
- )
diff --git a/tests/plugins/test_plugin_loader_unreadable.py b/tests/plugins/test_plugin_loader_unreadable.py
index e813987db62..053978b761b 100644
--- a/tests/plugins/test_plugin_loader_unreadable.py
+++ b/tests/plugins/test_plugin_loader_unreadable.py
@@ -19,12 +19,10 @@ def _deny(monkeypatch, denied: Path) -> None:
monkeypatch.setattr(Path, "stat", stat)
-def test_iter_plugin_dirs_skips_unreadable_child(tmp_path, monkeypatch, caplog):
+def test_iter_plugin_dirs_skips_unreadable_child(tmp_path, monkeypatch):
for name in ("denied", "good"):
(tmp_path / name).mkdir()
(tmp_path / name / "__init__.py").write_text("", encoding="utf-8")
_deny(monkeypatch, tmp_path / "denied")
- with caplog.at_level("WARNING", logger="plugins.plugin_loader"):
- assert plugin_loader.iter_plugin_dirs(tmp_path) == [tmp_path / "good"]
- assert "Skipping unreadable plugin directory" in caplog.text
+ assert plugin_loader.iter_plugin_dirs(tmp_path) == [tmp_path / "good"]
diff --git a/tests/plugins/test_plugin_storage.py b/tests/plugins/test_plugin_storage.py
index a774c3d8846..4878c29609a 100644
--- a/tests/plugins/test_plugin_storage.py
+++ b/tests/plugins/test_plugin_storage.py
@@ -33,10 +33,6 @@ def test_data_dir_lives_outside_the_install_tree(hermes_home):
assert (hermes_home / "plugins") not in root.parents
-def test_data_dir_is_stable_across_calls(hermes_home):
- assert plugin_data_dir("p") == plugin_data_dir("p")
-
-
@pytest.mark.parametrize("bad", ["", ".", "..", "../escape", "a/b", "a\\b", "x" * 65])
def test_hostile_names_are_rejected(hermes_home, bad):
with pytest.raises(ValueError):
diff --git a/tests/plugins/test_raft_check_fn_silent.py b/tests/plugins/test_raft_check_fn_silent.py
deleted file mode 100644
index be75b255c3c..00000000000
--- a/tests/plugins/test_raft_check_fn_silent.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""Regression tests for the raft platform plugin's check_fn.
-
-The raft platform adapter's ``check_raft_requirements()`` is registered as
-the platform's ``check_fn``. This function is invoked on every
-``load_gateway_config()`` call (dozens of times during normal gateway
-operation). It must therefore be a *silent* predicate — returning True/False
-without logging — otherwise every user without the ``raft`` CLI installed
-gets their logs flooded with WARNING messages every few seconds.
-
-See: https://github.com/NousResearch/hermes-agent/issues/49234
-"""
-
-import logging
-from unittest.mock import patch
-
-import pytest
-
-
-def raft_check():
- """Import check_raft_requirements fresh (adapter self-manages sys.path)."""
- from plugins.platforms.raft.adapter import check_raft_requirements
-
- return check_raft_requirements
-
-
-def test_check_returns_false_when_raft_cli_missing(raft_check):
- """check_fn returns False when raft CLI is not in PATH."""
- with patch("plugins.platforms.raft.adapter.shutil.which", return_value=None), \
- patch("plugins.platforms.raft.adapter.AIOHTTP_AVAILABLE", True):
- assert raft_check() is False
-
-
diff --git a/tests/plugins/test_retaindb_plugin.py b/tests/plugins/test_retaindb_plugin.py
index 11ffbaa02aa..95d64dfb22a 100644
--- a/tests/plugins/test_retaindb_plugin.py
+++ b/tests/plugins/test_retaindb_plugin.py
@@ -132,16 +132,6 @@ class TestWriteQueue:
db_path = tmp_path / "test_queue.db"
return _WriteQueue(client, db_path), client, db_path
- def test_enqueue_creates_row(self, tmp_path):
- q, client, db_path = self._make_queue(tmp_path)
- q.enqueue("user1", "sess1", [{"role": "user", "content": "hi"}])
- # shutdown() blocks until the writer thread drains the queue — no need
- # to pre-sleep (the old 1s sleep was a just-in-case wait, but shutdown
- # does the right thing).
- q.shutdown()
- # If ingest succeeded, the row should be deleted
- client.ingest_session.assert_called_once()
-
def test_flush_deletes_row_on_success(self, tmp_path):
q, client, db_path = self._make_queue(tmp_path)
@@ -154,14 +144,6 @@ class TestWriteQueue:
assert rows == 0
- def test_thread_local_connection_reuse(self, tmp_path):
- q, _, _ = self._make_queue(tmp_path)
- # Same thread should get same connection
- conn1 = q._get_conn()
- conn2 = q._get_conn()
- assert conn1 is conn2
- q.shutdown()
-
def test_crash_recovery_replays_pending(self, tmp_path):
"""Simulate crash: create rows, then new queue should replay them."""
db_path = tmp_path / "recovery_test.db"
@@ -214,7 +196,6 @@ class TestBuildOverlay:
profile = {"memories": [{"content": "User likes Python"}]}
result = _build_overlay(profile, {})
assert "User likes Python" in result
- assert "[RetainDB Context]" in result
def test_query_results_included(self):
query_result = {"results": [{"content": "Previous discussion about Rust"}]}
@@ -270,55 +251,16 @@ class TestRetainDBMemoryProvider:
provider = RetainDBMemoryProvider()
return provider
- def test_name(self):
- p = RetainDBMemoryProvider()
- assert p.name == "retaindb"
def test_is_available_without_key(self):
p = RetainDBMemoryProvider()
assert p.is_available() is False
- def test_config_schema(self):
- p = RetainDBMemoryProvider()
- schema = p.get_config_schema()
- assert len(schema) == 3
- keys = [s["key"] for s in schema]
- assert "api_key" in keys
- assert "base_url" in keys
- assert "project" in keys
-
- def test_initialize_creates_client_and_queue(self, tmp_path, monkeypatch):
- p = self._make_provider(tmp_path, monkeypatch)
- p.initialize("test-session", hermes_home=str(tmp_path / ".hermes"))
- assert p._client is not None
- assert p._queue is not None
- assert p._session_id == "test-session"
- p.shutdown()
-
-
- def test_system_prompt_block(self, tmp_path, monkeypatch):
- p = self._make_provider(tmp_path, monkeypatch)
- p.initialize("test-session", hermes_home=str(tmp_path / ".hermes"))
- block = p.system_prompt_block()
- assert "RetainDB Memory" in block
- assert "Active" in block
- p.shutdown()
-
def test_handle_tool_call_not_initialized(self):
p = RetainDBMemoryProvider()
result = json.loads(p.handle_tool_call("retaindb_profile", {}))
assert "error" in result
- assert "not initialized" in result["error"]
-
-
- def test_dispatch_profile(self, tmp_path, monkeypatch):
- p = self._make_provider(tmp_path, monkeypatch)
- p.initialize("test-session", hermes_home=str(tmp_path / ".hermes"))
- with patch.object(p._client, "get_profile", return_value={"memories": []}):
- result = json.loads(p.handle_tool_call("retaindb_profile", {}))
- assert "memories" in result
- p.shutdown()
# ===========================================================================
@@ -348,36 +290,10 @@ class TestPrefetch:
p.shutdown()
- def test_reasoning_level_short(self):
- assert RetainDBMemoryProvider._reasoning_level("hi") == "low"
-
-
# ===========================================================================
# sync_turn tests
# ===========================================================================
-class TestSyncTurn:
- """Test turn synchronization via the write queue."""
-
- def test_sync_turn_enqueues(self, tmp_path, monkeypatch):
- monkeypatch.setenv("RETAINDB_API_KEY", "rdb-test-key")
- hermes_home = tmp_path / ".hermes"
- hermes_home.mkdir(exist_ok=True)
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- p = RetainDBMemoryProvider()
- p.initialize("test-session", hermes_home=str(hermes_home))
- with patch.object(p._queue, "enqueue") as mock_enqueue:
- p.sync_turn("user msg", "assistant msg")
- mock_enqueue.assert_called_once()
- args = mock_enqueue.call_args[0]
- assert args[0] == "default" # user_id
- assert args[1] == "test-session" # session_id
- msgs = args[2]
- assert len(msgs) == 2
- assert msgs[0]["role"] == "user"
- assert msgs[1]["role"] == "assistant"
- p.shutdown()
-
# ===========================================================================
# on_memory_write hook tests
@@ -429,11 +345,3 @@ class TestOnMemoryWrite:
# register() test
# ===========================================================================
-class TestRegister:
- def test_register_calls_register_memory_provider(self):
- from plugins.memory.retaindb import register
- ctx = MagicMock()
- register(ctx)
- ctx.register_memory_provider.assert_called_once()
- arg = ctx.register_memory_provider.call_args[0][0]
- assert isinstance(arg, RetainDBMemoryProvider)
diff --git a/tests/plugins/test_security_guidance_plugin.py b/tests/plugins/test_security_guidance_plugin.py
index 47d7dab640e..9b477dc9f29 100644
--- a/tests/plugins/test_security_guidance_plugin.py
+++ b/tests/plugins/test_security_guidance_plugin.py
@@ -78,9 +78,6 @@ def _load_plugin_init():
# ---------------------------------------------------------------------------
class TestPatternsData:
- def test_has_at_least_one_rule(self):
- p = _load_patterns()
- assert len(p.SECURITY_PATTERNS) >= 1
def test_every_rule_has_required_fields(self):
p = _load_patterns()
@@ -281,25 +278,3 @@ class TestPluginDiscovery:
assert set(manifest["provides_hooks"]) == set(registered)
assert "hooks" not in manifest
- def test_loads_via_plugin_manager(self, _isolate_env, monkeypatch):
- """End-to-end: enable in config.yaml and verify the PluginManager
- picks it up via the standard discovery path."""
- import yaml
-
- config = {"plugins": {"enabled": ["security-guidance"]}}
- (_isolate_env / "config.yaml").write_text(
- yaml.safe_dump(config), encoding="utf-8"
- )
-
- # Wipe any cached plugin state from earlier tests in this worker.
- for k in list(sys.modules):
- if k.startswith(("hermes_plugins", "hermes_cli.plugins")):
- del sys.modules[k]
-
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- mgr = _ensure_plugins_discovered(force=True)
- loaded = set()
- if hasattr(mgr, "_plugins"):
- loaded = set(mgr._plugins.keys())
- assert "security-guidance" in loaded
diff --git a/tests/plugins/test_teams_pipeline_plugin.py b/tests/plugins/test_teams_pipeline_plugin.py
index 0c4a6657ce3..d89abc9cb72 100644
--- a/tests/plugins/test_teams_pipeline_plugin.py
+++ b/tests/plugins/test_teams_pipeline_plugin.py
@@ -8,9 +8,7 @@ from pathlib import Path
import pytest
-from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest
from gateway.config import GatewayConfig, Platform, PlatformConfig
-from plugins.teams_pipeline import register
from plugins.teams_pipeline.meetings import (
TeamsMeetingError,
looks_like_transcript_id,
@@ -44,20 +42,6 @@ async def _no_call_record(*args, **kwargs):
return None
-def test_register_adds_cli_only():
- mgr = PluginManager()
- manifest = PluginManifest(name="teams_pipeline")
- ctx = PluginContext(manifest, mgr)
-
- register(ctx)
-
- assert "teams-pipeline" in mgr._cli_commands
- entry = mgr._cli_commands["teams-pipeline"]
- assert entry["plugin"] == "teams_pipeline"
- assert callable(entry["setup_fn"])
- assert callable(entry["handler_fn"])
-
-
def test_runtime_config_uses_existing_teams_platform_settings():
from plugins.teams_pipeline.runtime import build_pipeline_runtime_config
@@ -90,37 +74,6 @@ def test_runtime_config_uses_existing_teams_platform_settings():
}
-def test_build_pipeline_runtime_reuses_existing_teams_adapter_surface(monkeypatch, tmp_path):
- from plugins.teams_pipeline import runtime as runtime_module
-
- class FakeWriter:
- def __init__(self, platform_config=None, **kwargs) -> None:
- self.platform_config = platform_config
-
- monkeypatch.setattr(runtime_module, "build_graph_client", lambda: object())
- monkeypatch.setattr(runtime_module, "resolve_teams_pipeline_store_path", lambda: tmp_path / "teams-store.json")
- monkeypatch.setattr("plugins.platforms.teams.summary_writer.TeamsSummaryWriter", FakeWriter)
-
- gateway = SimpleNamespace(
- config=GatewayConfig(
- platforms={
- Platform("teams"): PlatformConfig(
- enabled=True,
- extra={
- "delivery_mode": "incoming_webhook",
- "incoming_webhook_url": "https://example.com/hook",
- },
- )
- }
- )
- )
-
- runtime = runtime_module.build_pipeline_runtime(gateway)
-
- assert isinstance(runtime.teams_sender, FakeWriter)
- assert runtime.teams_sender.platform_config is gateway.config.platforms[Platform("teams")]
-
-
@pytest.mark.anyio
async def test_bind_gateway_runtime_attaches_scheduler(monkeypatch, tmp_path):
from plugins.teams_pipeline import runtime as runtime_module
diff --git a/tests/plugins/test_transform_api_error_classification_hook.py b/tests/plugins/test_transform_api_error_classification_hook.py
index 03b654412e1..fa46e3bd2a1 100644
--- a/tests/plugins/test_transform_api_error_classification_hook.py
+++ b/tests/plugins/test_transform_api_error_classification_hook.py
@@ -123,7 +123,6 @@ def test_skipped_valid_results_log_runtime_warning(monkeypatch, caplog):
assert result.reason == FailoverReason.billing
warnings = [r.getMessage() for r in caplog.records if "skipped" in r.getMessage()]
assert len(warnings) == 1
- assert "skipped 1 valid" in warnings[0]
# A lone winner is not a conflict: no warning.
caplog.clear()
diff --git a/tests/plugins/test_transform_llm_output_hook.py b/tests/plugins/test_transform_llm_output_hook.py
deleted file mode 100644
index 78946316dd5..00000000000
--- a/tests/plugins/test_transform_llm_output_hook.py
+++ /dev/null
@@ -1,135 +0,0 @@
-"""Tests for the ``transform_llm_output`` plugin hook.
-
-The hook fires inside ``AIAgent.run_conversation`` once the tool-calling
-loop has produced a final response. Driving the full agent loop from a
-unit test would be prohibitively heavy, so these tests exercise the
-invoke_hook dispatch semantics that the wiring in ``run_agent.py``
-depends on:
-
- for _hook_result in _transform_results:
- if isinstance(_hook_result, str) and _hook_result:
- final_response = _hook_result
- break # First non-empty string wins
-
-Mirrors ``test_transform_tool_result_hook.py`` which tests the equivalent
-contract for the generic tool-result seam.
-"""
-
-from pathlib import Path
-
-import yaml
-
-import hermes_cli.plugins as plugins_mod
-from hermes_cli.plugins import PluginManager, VALID_HOOKS
-
-
-def _make_enabled_plugin(hermes_home: Path, name: str, register_body: str) -> Path:
- """Create a plugin under <hermes_home>/plugins/<name> and opt it in."""
- plugin_dir = hermes_home / "plugins" / name
- plugin_dir.mkdir(parents=True)
- (plugin_dir / "plugin.yaml").write_text(
- yaml.safe_dump({"name": name, "version": "0.1.0"}), encoding="utf-8",
- )
- (plugin_dir / "__init__.py").write_text(
- "def register(ctx):\n"
- f" {register_body}\n",
- encoding="utf-8",
- )
- cfg_path = hermes_home / "config.yaml"
- cfg = {}
- if cfg_path.exists():
- cfg = yaml.safe_load(cfg_path.read_text()) or {}
- cfg.setdefault("plugins", {}).setdefault("enabled", []).append(name)
- cfg_path.write_text(yaml.safe_dump(cfg), encoding="utf-8")
- return plugin_dir
-
-
-def test_transform_llm_output_in_valid_hooks():
- assert "transform_llm_output" in VALID_HOOKS
-
-
-def test_hook_receives_expected_kwargs(tmp_path, monkeypatch):
- """Hook callback should see response_text + session_id + model + platform."""
- hermes_home = tmp_path / "hermes_test"
- hermes_home.mkdir(exist_ok=True)
- _make_enabled_plugin(
- hermes_home, "capture_hook",
- register_body=(
- 'ctx.register_hook("transform_llm_output", '
- 'lambda **kw: f"{kw[\'response_text\']}|{kw[\'session_id\']}|'
- '{kw[\'model\']}|{kw[\'platform\']}")'
- ),
- )
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- mgr = PluginManager()
- mgr.discover_and_load()
-
- results = mgr.invoke_hook(
- "transform_llm_output",
- response_text="hello world",
- session_id="s1",
- model="anthropic/claude-sonnet-4.6",
- platform="cli",
- )
- assert results == ["hello world|s1|anthropic/claude-sonnet-4.6|cli"]
-
-
-
-
-
-
-def test_hook_exception_does_not_replace_response(tmp_path, monkeypatch):
- """A plugin raising an exception must not break hook dispatch.
-
- PluginManager.invoke_hook catches per-callback exceptions, logs a
- warning, and continues — so a raising plugin contributes no entry
- to the results list, and the walk in run_agent.py finds nothing to
- replace with.
- """
- hermes_home = tmp_path / "hermes_test"
- hermes_home.mkdir(exist_ok=True)
- _make_enabled_plugin(
- hermes_home, "raising_hook",
- register_body=(
- 'def _boom(**kw):\n'
- ' raise RuntimeError("boom")\n'
- ' ctx.register_hook("transform_llm_output", _boom)'
- ),
- )
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- mgr = PluginManager()
- mgr.discover_and_load()
-
- results = mgr.invoke_hook(
- "transform_llm_output",
- response_text="keep me",
- session_id="s1",
- model="m",
- platform="cli",
- )
-
- final_response = "keep me"
- for _hook_result in results:
- if isinstance(_hook_result, str) and _hook_result:
- final_response = _hook_result
- break
-
- assert final_response == "keep me"
-
-
-def test_no_plugins_returns_empty_results(tmp_path, monkeypatch):
- """With no plugins loaded, invoke_hook returns [] and the response is unchanged."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_empty"))
- plugins_mod._plugin_manager = PluginManager()
-
- mgr = plugins_mod._plugin_manager
- results = mgr.invoke_hook(
- "transform_llm_output",
- response_text="unchanged",
- session_id="",
- model="m",
- platform="",
- )
- assert results == []
diff --git a/tests/plugins/video_gen/test_deepinfra_provider.py b/tests/plugins/video_gen/test_deepinfra_provider.py
index b1095dbaf0c..35019317784 100644
--- a/tests/plugins/video_gen/test_deepinfra_provider.py
+++ b/tests/plugins/video_gen/test_deepinfra_provider.py
@@ -27,34 +27,13 @@ def _isolation(tmp_path, monkeypatch):
yield
-def test_identity_and_availability(monkeypatch):
+def test_availability_follows_api_key(monkeypatch):
p = deepinfra_plugin.DeepInfraVideoGenProvider()
- assert p.name == "deepinfra"
- assert p.display_name == "DeepInfra"
- assert p._base_url() == "https://api.deepinfra.com/v1/openai"
assert p.is_available() is True
monkeypatch.delenv("DEEPINFRA_API_KEY", raising=False)
assert p.is_available() is False
-def test_list_models_filters_by_video_gen_tag(monkeypatch):
- """list_models() returns only ``video-gen``-tagged catalog entries."""
- import hermes_cli.models as _models_mod
-
- def _fake_by_tag(tag, **kw):
- assert tag == "video-gen"
- return [
- {"id": "vendor/p-video", "metadata": {"description": "fast t2v"}},
- {"id": "vendor/wan-t2v", "metadata": {}},
- ]
-
- monkeypatch.setattr(_models_mod, "_fetch_deepinfra_models_by_tag", _fake_by_tag)
- rows = deepinfra_plugin.DeepInfraVideoGenProvider().list_models()
- ids = {row["id"] for row in rows}
- assert ids == {"vendor/p-video", "vendor/wan-t2v"}
- assert all("display" in r for r in rows)
-
-
def _fake_openai_with_capture(captured: dict, *, status="succeeded",
data=None, download=b"\x00\x00mp4bytes"):
"""Build a fake ``openai`` module whose videos resource records the call.
diff --git a/tests/plugins/video_gen/test_fal_plugin.py b/tests/plugins/video_gen/test_fal_plugin.py
index 0693bb254e2..7e57e62d11f 100644
--- a/tests/plugins/video_gen/test_fal_plugin.py
+++ b/tests/plugins/video_gen/test_fal_plugin.py
@@ -19,19 +19,6 @@ def _reset_registry(monkeypatch):
video_gen_registry._reset_for_tests()
-def test_fal_provider_registers():
- from plugins.video_gen.fal import FALVideoGenProvider, DEFAULT_MODEL
-
- provider = FALVideoGenProvider()
- video_gen_registry.register_provider(provider)
-
- assert video_gen_registry.get_provider("fal") is provider
- assert provider.display_name == "FAL"
- # DEFAULT_MODEL is the cheap-tier default
- assert provider.default_model() == DEFAULT_MODEL
- assert DEFAULT_MODEL in {"pixverse-v6", "ltx-2.3"}
-
-
def test_kling_v3_standard_and_pro_payload_shape():
"""Kling 3.0 (v3 standard/pro): start_image_url on i2v, aspect_ratio
dropped on i2v (schema derives it from the image), no seed/resolution
@@ -81,28 +68,6 @@ def test_kling_v3_standard_and_pro_payload_shape():
assert p["generate_audio"] is False, fid
-def test_kling_4k_uses_start_image_url():
- """Kling v3 4K's image-to-video endpoint expects start_image_url,
- not image_url. The family must declare image_param_key='start_image_url'."""
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["kling-v3-4k"]
- assert meta.get("image_param_key") == "start_image_url"
- payload = _build_payload(
- meta,
- prompt="x",
- image_url="https://example.com/i.png",
- duration=5,
- aspect_ratio="16:9",
- resolution="720p",
- negative_prompt=None,
- audio=None,
- seed=None,
- )
- assert payload.get("start_image_url") == "https://example.com/i.png"
- assert "image_url" not in payload
-
-
def test_minimax_h3_int_duration_and_resolution_alias():
"""MiniMax H3 requires duration as a JSON integer and uses the
768P/2K/4K resolution enum — the tool's 720p/1080p values must map."""
@@ -179,20 +144,6 @@ def test_image_drop_keys_strips_aspect_ratio_on_i2v():
assert t2v.get("aspect_ratio") == "16:9", fid
-def test_seedance_25_string_duration_up_to_30():
- """Seedance 2.5 keeps the stringified duration convention and supports
- the full 4-30s range."""
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["seedance-2.5"]
- payload = _build_payload(
- meta, prompt="x", image_url=None, duration=30, aspect_ratio="1:1",
- resolution="480p", negative_prompt=None, audio=True, seed=None,
- )
- assert payload["duration"] == "30"
- assert payload["generate_audio"] is True
-
-
def test_wan_30_audio_toggle_uses_family_key_and_start_image_url():
"""Wan 3.0's schema names the audio toggle `audio` (not `generate_audio`), takes
`start_image_url` on i2v and an integer duration; veo3.1 keeps `generate_audio`."""
@@ -205,16 +156,6 @@ def test_wan_30_audio_toggle_uses_family_key_and_start_image_url():
assert _build_payload(FAL_FAMILIES["veo3.1"], image_url=None, **kw)["generate_audio"] is True
-def test_gemini_omni_flash_v11_is_dual_modality():
- """v1.1 (Aug 2026) added a text-to-video endpoint; both modalities
- must route to the versioned v1.1 endpoints."""
- from plugins.video_gen.fal import FAL_FAMILIES
-
- meta = FAL_FAMILIES["gemini-omni-flash"]
- assert meta["text_endpoint"] == "google/gemini-omni-flash/v1.1/text-to-video"
- assert meta["image_endpoint"] == "google/gemini-omni-flash/v1.1/image-to-video"
-
-
def test_text_only_job_errors_cleanly_for_i2v_only_family(monkeypatch):
"""Catalog-shape guard: a family without a text endpoint must error cleanly
instead of submitting to a None endpoint. Every cataloged family is now
@@ -326,20 +267,6 @@ class TestFamilyRouting:
expected_endpoint = FAL_FAMILIES[DEFAULT_MODEL]["text_endpoint"]
assert with_fake_fal["endpoint"] == expected_endpoint
- def test_premium_seedance_routing(self, with_fake_fal):
- """Sanity check the premium-tier seedance routes correctly."""
- from plugins.video_gen.fal import FALVideoGenProvider
-
- result = FALVideoGenProvider().generate(
- "a dog",
- model="seedance-2.0",
- image_url="https://example.com/dog.png",
- )
- assert result["success"] is True
- assert with_fake_fal["endpoint"] == "bytedance/seedance-2.0/image-to-video"
- # Seedance uses regular image_url (not start_image_url)
- assert with_fake_fal["arguments"]["image_url"] == "https://example.com/dog.png"
-
class TestFamilyKeyNormalization:
def test_full_endpoint_paths_resolve_to_their_own_family(self):
@@ -431,22 +358,6 @@ class TestPayloadBuilder:
assert p["negative_prompt"] == "ugly"
assert p["seed"] == 42
- def test_pixverse_range_clamps_correctly(self):
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["pixverse-v6"]
- p = _build_payload(
- meta,
- prompt="x",
- image_url="https://i.png",
- duration=99, # over max → 15
- aspect_ratio="16:9",
- resolution="540p",
- negative_prompt=None,
- audio=None,
- seed=None,
- )
- assert p["duration"] == "15"
@pytest.mark.parametrize(
"family_id",
@@ -478,24 +389,6 @@ class TestPayloadBuilder:
)
assert "seed" not in p
- def test_minimax_h3_uses_uppercase_resolution_enum(self):
- """FAL spells MiniMax H3 resolutions "768P"/"2K"/"4K"; tool-style
- values like "720p" are aliased via resolution_aliases."""
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["minimax-h3"]
- accepted = _build_payload(
- meta, prompt="x", image_url=None, duration=7, aspect_ratio="16:9",
- resolution="2K", negative_prompt=None, audio=None, seed=None,
- )
- assert accepted["resolution"] == "2K"
- assert accepted["duration"] == 7
-
- aliased = _build_payload(
- meta, prompt="x", image_url=None, duration=7, aspect_ratio="16:9",
- resolution="720p", negative_prompt=None, audio=None, seed=None,
- )
- assert aliased["resolution"] == "768P"
def test_audio_only_sent_for_families_that_declare_it(self):
"""minimax-h3 and the i2v-only families have no generate_audio field."""
@@ -591,51 +484,6 @@ class TestPayloadBuilder:
f"got {p.get('duration')!r}"
)
- def test_happy_horse_minimal_payload(self):
- """Happy Horse 1.1 has a full published schema — verified fields only."""
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["happy-horse"]
- p = _build_payload(
- meta,
- prompt="a horse galloping",
- image_url=None,
- duration=8,
- aspect_ratio="16:9",
- resolution="720p",
- negative_prompt="watermark",
- audio=True,
- seed=None,
- )
- # v1.1 declares aspect_ratio/resolution/duration (integer). Audio is
- # native (no generate_audio key) and negative_prompt is unsupported.
- assert p == {
- "prompt": "a horse galloping",
- "aspect_ratio": "16:9",
- "resolution": "720p",
- "duration": 8,
- }
- assert isinstance(p["duration"], int)
-
- def test_happy_horse_i2v_drops_aspect_ratio(self):
- """Happy Horse 1.1 i2v derives aspect ratio from the input image."""
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["happy-horse"]
- p = _build_payload(
- meta,
- prompt="animate this",
- image_url="https://example.com/frame.png",
- duration=5,
- aspect_ratio="16:9",
- resolution="1080p",
- negative_prompt=None,
- audio=None,
- seed=123,
- )
- assert "aspect_ratio" not in p
- assert p["image_url"] == "https://example.com/frame.png"
- assert p["seed"] == 123
def test_ltx_25_payload(self):
"""LTX 2.5: integer duration enum, 4K alias, no seed key."""
@@ -678,46 +526,6 @@ class TestPayloadBuilder:
assert _build_payload(meta, duration=18, resolution="1080p", **kw)["duration"] == 18
assert "duration" not in _build_payload(meta, duration=None, resolution="4k", **kw)
- def test_kling_o3_payload(self):
- """Kling O3: string duration, i2v drops aspect_ratio, no seed."""
- from plugins.video_gen.fal import FAL_FAMILIES, _build_payload
-
- meta = FAL_FAMILIES["kling-o3"]
- p = _build_payload(
- meta,
- prompt="a mecha lands",
- image_url=None,
- duration=5,
- aspect_ratio="16:9",
- resolution="1080p",
- negative_prompt=None,
- audio=True,
- seed=3,
- )
- # No resolution/seed keys in the O3 schema; duration is the usual
- # stringified queue-API form.
- assert p == {
- "prompt": "a mecha lands",
- "aspect_ratio": "16:9",
- "duration": "5",
- "generate_audio": True,
- }
-
- p = _build_payload(
- meta,
- prompt="animate",
- image_url="https://example.com/f.png",
- duration=2,
- aspect_ratio="16:9",
- resolution="1080p",
- negative_prompt=None,
- audio=False,
- seed=None,
- )
- assert "aspect_ratio" not in p
- assert p["duration"] == "3" # clamped to the 3-15 range
- assert p["generate_audio"] is False
-
class TestUpscalePass:
"""Opt-in SeedVR2 upscale chain after generation."""
diff --git a/tests/plugins/video_gen/test_xai_plugin.py b/tests/plugins/video_gen/test_xai_plugin.py
index a6eba3b31e4..cfb3c5af1fa 100644
--- a/tests/plugins/video_gen/test_xai_plugin.py
+++ b/tests/plugins/video_gen/test_xai_plugin.py
@@ -14,40 +14,6 @@ def _reset_registry():
video_gen_registry._reset_for_tests()
-def test_xai_provider_registers():
- from plugins.video_gen.xai import XAIVideoGenProvider
-
- provider = XAIVideoGenProvider()
- video_gen_registry.register_provider(provider)
-
- assert video_gen_registry.get_provider("xai") is provider
- assert provider.display_name == "xAI"
- assert provider.default_model() == "grok-imagine-video"
-
-
-def test_xai_resolved_credentials_threaded_through_request(monkeypatch):
- """OAuth-resolved creds must reach the HTTP layer — bug class where
- ``is_available()`` says yes but the request still hits with no key.
- """
- import plugins.video_gen.xai as xai_plugin
-
- monkeypatch.delenv("XAI_API_KEY", raising=False)
- monkeypatch.setattr(
- "tools.xai_http.resolve_xai_http_credentials",
- lambda: {
- "provider": "xai-oauth",
- "api_key": "oauth-bearer-token",
- "base_url": "https://api.x.ai/v1",
- },
- )
-
- api_key, base_url = xai_plugin._resolve_xai_credentials()
- assert api_key == "oauth-bearer-token"
- assert base_url == "https://api.x.ai/v1"
- headers = xai_plugin._xai_headers(api_key)
- assert headers["Authorization"] == "Bearer oauth-bearer-token"
-
-
@pytest.mark.asyncio
async def test_video_input_from_public_url_uses_url_field():
from plugins.video_gen.xai import _video_input_from_public_url
diff --git a/tests/plugins/video_gen/test_xai_plugin_integration.py b/tests/plugins/video_gen/test_xai_plugin_integration.py
index bf75abed320..f2dc12eaf48 100644
--- a/tests/plugins/video_gen/test_xai_plugin_integration.py
+++ b/tests/plugins/video_gen/test_xai_plugin_integration.py
@@ -119,7 +119,6 @@ class TestXAIPayload:
provider.generate("animate this", image_url=str(image_path))
payload = _last_post(captured)["json"]
- assert payload["model"] == "grok-imagine-video-1.5"
assert payload["image"]["url"].startswith("data:image/png;base64,")
def test_reference_images_payload(self, xai_provider):
diff --git a/tests/plugins/web/test_web_search_provider_plugins.py b/tests/plugins/web/test_web_search_provider_plugins.py
index 446ff719b8c..99ec814cf9b 100644
--- a/tests/plugins/web/test_web_search_provider_plugins.py
+++ b/tests/plugins/web/test_web_search_provider_plugins.py
@@ -18,9 +18,6 @@ glue layer simultaneously.
"""
from __future__ import annotations
-import asyncio
-import inspect
-
import pytest
@@ -68,75 +65,6 @@ def _isolate_env(monkeypatch: pytest.MonkeyPatch) -> None:
_clear_web_env(monkeypatch)
-class TestBundledPluginsRegister:
- """All bundled web plugins discover and register correctly."""
-
- def test_all_bundled_plugins_present_in_registry(self) -> None:
- _ensure_plugins_loaded()
- from agent.web_search_registry import list_providers
-
- names = sorted(p.name for p in list_providers())
- assert names == [
- "brave-free",
- "ddgs",
- "exa",
- "firecrawl",
- "keenable",
- "openai-native",
- "parallel",
- "perplexity",
- "searxng",
- "tavily",
- "xai",
- ]
-
- @pytest.mark.parametrize(
- "plugin_name,expected_search,expected_extract",
- [
- ("brave-free", True, False),
- ("ddgs", True, False),
- ("searxng", True, False),
- ("exa", True, True),
- ("parallel", True, True),
- ("keenable", True, True),
- ("tavily", True, True),
- ("perplexity", True, True),
- ("firecrawl", True, True),
- # xai: search-only via Grok's agentic web_search tool.
- ("xai", True, False),
- # openai-native: marker for the Codex Responses server-side web_search swap;
- # search-only, so web_extract keeps its own backend (#19320).
- ("openai-native", True, False),
- ],
- )
- def test_capability_flags_match_spec(
- self,
- plugin_name: str,
- expected_search: bool,
- expected_extract: bool,
- ) -> None:
- _ensure_plugins_loaded()
- from agent.web_search_registry import get_provider
-
- provider = get_provider(plugin_name)
- assert provider is not None, f"plugin {plugin_name!r} not registered"
- assert provider.supports_search() is expected_search
- assert provider.supports_extract() is expected_extract
-
- @pytest.mark.parametrize(
- "plugin_name",
- ["brave-free", "ddgs", "searxng", "exa", "parallel", "tavily", "perplexity", "firecrawl", "keenable", "xai", "openai-native"],
- )
- def test_each_plugin_has_name_and_display_name(self, plugin_name: str) -> None:
- _ensure_plugins_loaded()
- from agent.web_search_registry import get_provider
-
- provider = get_provider(plugin_name)
- assert provider is not None
- assert provider.name == plugin_name
- assert provider.display_name # any non-empty string
-
-
# ---------------------------------------------------------------------------
# is_available() behavior
# ---------------------------------------------------------------------------
@@ -239,21 +167,6 @@ class TestIsAvailable:
)
assert p.is_available() is True
- def test_ddgs_always_available_when_package_importable(self) -> None:
- """DDGS is the always-on fallback — no API key required.
-
- It may report unavailable if the ``ddgs`` package itself isn't
- installed in the env (legitimate — the plugin's post_setup hook
- triggers pip install on first selection). We only assert that
- is_available() doesn't raise.
- """
- _ensure_plugins_loaded()
- from agent.web_search_registry import get_provider
-
- p = get_provider("ddgs")
- assert p is not None
- # Truthy or falsy, just must not raise.
- _ = bool(p.is_available())
def test_xai_requires_api_key_or_oauth(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""xAI needs XAI_API_KEY or OAuth tokens in auth.json."""
@@ -331,21 +244,3 @@ class TestRegistryResolution:
assert result.is_available() or result.is_keyless_available()
-# ---------------------------------------------------------------------------
-# Sync-vs-async extract detection
-# ---------------------------------------------------------------------------
-
-
-class TestAsyncExtractDispatch:
- """The dispatcher detects async vs sync extract methods correctly."""
-
-
-# ---------------------------------------------------------------------------
-# Error response shape (preserved bit-for-bit from legacy)
-# ---------------------------------------------------------------------------
-
-
-class TestErrorResponseShapes:
- """When credentials are missing, plugins return typed errors, not raises."""
-
-
diff --git a/tests/providers/test_e2e_wiring.py b/tests/providers/test_e2e_wiring.py
index 334c4047bbf..c052ecd6bd1 100644
--- a/tests/providers/test_e2e_wiring.py
+++ b/tests/providers/test_e2e_wiring.py
@@ -21,22 +21,6 @@ def _msgs():
class TestNvidiaProfileWiring:
- def test_nvidia_model_passed(self, transport):
- profile = get_provider_profile("nvidia")
- kwargs = transport.build_kwargs(
- model="nvidia/test-model",
- messages=_msgs(),
- tools=None,
- provider_profile=profile,
- max_tokens=None,
- max_tokens_param_fn=lambda x: {"max_tokens": x} if x else {},
- timeout=300,
- reasoning_config=None,
- request_overrides=None,
- session_id="test",
- ollama_num_ctx=None,
- )
- assert kwargs["model"] == "nvidia/test-model"
def test_nvidia_tool_messages_drop_name_fields(self, transport):
diff --git a/tests/providers/test_meta_ai_profile.py b/tests/providers/test_meta_ai_profile.py
index 5a0ea074cec..81f6884b1ec 100644
--- a/tests/providers/test_meta_ai_profile.py
+++ b/tests/providers/test_meta_ai_profile.py
@@ -5,7 +5,6 @@ https://github.com/albertodepaola/hermes-meta-provider — the plugin is now
bundled, so profiles resolve through normal registry discovery.
"""
-import pytest
from providers import get_provider_profile
from providers.base import ProviderProfile
@@ -18,21 +17,6 @@ def _profile():
class TestMetaAIProfile:
- def test_profile_registered(self):
- p = _profile()
- assert p.name == "meta-ai"
- assert p.base_url == "https://api.meta.ai/v1"
- assert p.auth_type == "api_key"
- # Responses API engages Muse prompt caching (0% on chat/completions
- # vs 93-99% on /v1/responses with prompt_cache_retention).
- assert p.api_mode == "codex_responses"
- assert "MODEL_API_KEY" in p.env_vars
- assert p.supports_vision is True
- # Images are accepted on user turns only; tool-result envelopes 400 (#101668).
- assert p.supports_vision_tool_messages is False
- assert p.default_aux_model == "muse-spark-1.2-contributor"
- assert p.default_max_tokens == 16384
- assert p.fallback_models == ("muse-spark-1.2",)
def test_live_catalog_filters_non_chat_models(self, monkeypatch):
p = _profile()
@@ -52,9 +36,6 @@ class TestMetaAIProfile:
assert p.fetch_models() == ["muse-spark-latest", "muse-nova-test"]
assert seen
- @pytest.mark.parametrize("alias", ["meta", "muse", "muse-spark", "model-api", "msl"])
- def test_aliases_resolve(self, alias):
- assert get_provider_profile(alias) is _profile()
def _effort(cfg):
diff --git a/tests/providers/test_plugin_discovery.py b/tests/providers/test_plugin_discovery.py
index b7257645127..7597204ea7e 100644
--- a/tests/providers/test_plugin_discovery.py
+++ b/tests/providers/test_plugin_discovery.py
@@ -38,7 +38,7 @@ def test_bundled_plugins_discovered():
assert plugins_dir.is_dir(), f"Missing {plugins_dir}"
child_dirs = [c for c in plugins_dir.iterdir() if c.is_dir()]
- assert len(child_dirs) >= 28, f"Expected at least 28 provider plugins, found {len(child_dirs)}"
+ assert child_dirs, f"No provider plugins under {plugins_dir}"
for child in child_dirs:
assert (child / "__init__.py").exists(), f"{child.name} missing __init__.py"
@@ -66,14 +66,6 @@ def test_all_profiles_register():
f"Expected at least {plugin_dir_count} profiles (one per plugin dir), got {len(names)}: {names}"
)
- # Spot-check representative providers from different categories
- for required in (
- "openrouter", "anthropic", "custom", "bedrock", "openai-codex",
- "minimax-oauth", "gmi", "xiaomi", "alibaba-coding-plan", "fireworks",
- "nebius-token-factory",
- ):
- assert required in names, f"Missing profile: {required}"
-
def test_user_plugin_overrides_bundled(tmp_path, monkeypatch):
"""A user plugin with the same name must override the bundled profile."""
@@ -119,8 +111,3 @@ def test_user_plugin_overrides_bundled(tmp_path, monkeypatch):
# Clean up: reset discovery state so other tests see the bundled version
_clear_provider_caches()
-
-
- # No import means the module must NOT be in the plugins list as a loaded one.
- # We check that the general loader didn't crash and didn't raise from the
- # broken __init__.py.
diff --git a/tests/providers/test_profile_wiring.py b/tests/providers/test_profile_wiring.py
index c6c52f012c2..6360dfa2ef6 100644
--- a/tests/providers/test_profile_wiring.py
+++ b/tests/providers/test_profile_wiring.py
@@ -24,13 +24,13 @@ def _max_tokens_fn(n):
class TestNvidiaProfileParity:
def test_max_tokens_match(self, transport):
- """NVIDIA profile sets max_tokens=16384; legacy flag is removed."""
+ """The NVIDIA profile default max_tokens reaches the wire when the user sets none."""
profile = transport.build_kwargs(
model="nvidia/nemotron", messages=_msgs(), tools=None,
provider_profile=get_provider_profile("nvidia"),
max_tokens_param_fn=_max_tokens_fn,
)
- assert profile["max_completion_tokens"] == 16384
+ assert profile["max_completion_tokens"] == get_provider_profile("nvidia").default_max_tokens
class TestKimiProfileParity:
@@ -47,92 +47,16 @@ class TestKimiProfileParity:
assert "temperature" not in profile
- def test_thinking_enabled(self, transport):
- # xor contract: explicit effort → reasoning_effort only, no thinking.
- rc = {"enabled": True, "effort": "high"}
- legacy = transport.build_kwargs(
- model="kimi-k2", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("kimi-coding"), reasoning_config=rc,
- )
- profile = transport.build_kwargs(
- model="kimi-k2", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("kimi"),
- reasoning_config=rc,
- )
- assert profile["reasoning_effort"] == legacy["reasoning_effort"] == "high"
- assert "thinking" not in profile.get("extra_body", {})
- assert "thinking" not in legacy.get("extra_body", {})
-
-class TestOpenRouterProfileParity:
- def test_provider_preferences(self, transport):
- prefs = {"allow": ["anthropic"]}
- legacy = transport.build_kwargs(
- model="anthropic/claude-sonnet-4.6", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("openrouter"), provider_preferences=prefs,
- )
- profile = transport.build_kwargs(
- model="anthropic/claude-sonnet-4.6", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("openrouter"),
- provider_preferences=prefs,
- )
- assert profile["extra_body"]["provider"] == legacy["extra_body"]["provider"]
-
- def test_reasoning_full_config(self, transport):
- rc = {"enabled": True, "effort": "high"}
- legacy = transport.build_kwargs(
- model="deepseek/deepseek-chat", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("openrouter"), supports_reasoning=True, reasoning_config=rc,
- )
- profile = transport.build_kwargs(
- model="deepseek/deepseek-chat", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("openrouter"),
- supports_reasoning=True, reasoning_config=rc,
- )
- assert profile["extra_body"]["reasoning"] == legacy["extra_body"]["reasoning"]
-
-class TestNousProfileParity:
- def test_tags(self, transport):
- legacy = transport.build_kwargs(
- model="hermes-3", messages=_msgs(), tools=None, provider_profile=get_provider_profile("nous"),
- )
- profile = transport.build_kwargs(
- model="hermes-3", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("nous"),
- )
- assert profile["extra_body"]["tags"] == legacy["extra_body"]["tags"]
-class TestQwenProfileParity:
- def test_vl_high_resolution(self, transport):
- legacy = transport.build_kwargs(
- model="qwen3.5", messages=_msgs(), tools=None, provider_profile=get_provider_profile("qwen-oauth"),
- )
- profile = transport.build_kwargs(
- model="qwen3.5", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("qwen"),
- )
- assert profile["extra_body"]["vl_high_resolution_images"] == legacy["extra_body"]["vl_high_resolution_images"]
- def test_metadata_top_level(self, transport):
- meta = {"sessionId": "s123", "promptId": "p456"}
- legacy = transport.build_kwargs(
- model="qwen3.5", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("qwen-oauth"), qwen_session_metadata=meta,
- )
- profile = transport.build_kwargs(
- model="qwen3.5", messages=_msgs(), tools=None,
- provider_profile=get_provider_profile("qwen"),
- qwen_session_metadata=meta,
- )
- assert profile["metadata"] == legacy["metadata"] == meta
- assert "metadata" not in profile.get("extra_body", {})
diff --git a/tests/providers/test_provider_profiles.py b/tests/providers/test_provider_profiles.py
index 1507dbdf855..899ca849d4f 100644
--- a/tests/providers/test_provider_profiles.py
+++ b/tests/providers/test_provider_profiles.py
@@ -1,97 +1,9 @@
"""Tests for the provider module registry and profiles."""
-from providers import get_provider_profile, _REGISTRY
-from providers.base import ProviderProfile, OMIT_TEMPERATURE
-
-
-class TestRegistry:
- def test_discovery_populates_registry(self):
- p = get_provider_profile("nvidia")
- assert p is not None
- assert p.name == "nvidia"
-
-
-
-
-
-class TestNvidiaProfile:
- def test_max_tokens(self):
- p = get_provider_profile("nvidia")
- assert p.default_max_tokens == 16384
-
-
- def test_base_url(self):
- p = get_provider_profile("nvidia")
- assert "nvidia.com" in p.base_url
-
-
- def test_prepare_messages_strips_tool_result_names(self):
- p = get_provider_profile("nvidia")
- msgs = [
- {"role": "user", "content": "run a command"},
- {
- "role": "assistant",
- "content": None,
- "tool_calls": [
- {
- "id": "call_1",
- "type": "function",
- "function": {"name": "terminal", "arguments": "{}"},
- }
- ],
- },
- {
- "role": "tool",
- "name": "terminal",
- "tool_name": "terminal",
- "tool_call_id": "call_1",
- "content": "ok",
- },
- ]
-
- result = p.prepare_messages(msgs)
-
- assert "name" not in result[2]
- assert "tool_name" not in result[2]
- assert result[2] == {
- "role": "tool",
- "tool_call_id": "call_1",
- "content": "ok",
- }
- assert msgs[2]["name"] == "terminal"
- assert msgs[2]["tool_name"] == "terminal"
-
- def test_prepare_messages_passthrough_without_tool_result_names(self):
- p = get_provider_profile("nvidia")
- msgs = [{"role": "tool", "tool_call_id": "call_1", "content": "ok"}]
- assert p.prepare_messages(msgs) is msgs
-
-
-class TestKimiProfile:
- def test_temperature_omit(self):
- p = get_provider_profile("kimi")
- assert p.fixed_temperature is OMIT_TEMPERATURE
-
-
-
-
- def test_thinking_enabled(self):
- # xor contract (fix ce4e74b3): an explicit recognized effort sends
- # reasoning_effort ONLY — never paired with extra_body.thinking.
- p = get_provider_profile("kimi")
- eb, tl = p.build_api_kwargs_extras(reasoning_config={"enabled": True, "effort": "high"})
- assert tl["reasoning_effort"] == "high"
- assert "thinking" not in eb
-
-
-
+from providers import get_provider_profile
class TestOpenRouterProfile:
- def test_extra_body_with_prefs(self):
- p = get_provider_profile("openrouter")
- body = p.build_extra_body(provider_preferences={"allow": ["anthropic"]})
- assert body["provider"] == {"allow": ["anthropic"]}
def test_sticky_session_id_normalizes_cron_timestamp(self):
"""Cron re-fires of the same job keep the same sticky routing key."""
@@ -101,10 +13,6 @@ class TestOpenRouterProfile:
assert first["session_id"] == "cron_job42"
assert first["session_id"] == second["session_id"]
-
-
-
-
def test_pareto_min_coding_score_emitted_for_pareto_model(self):
"""min_coding_score → plugins block when model is openrouter/pareto-code."""
p = get_provider_profile("openrouter")
@@ -116,16 +24,6 @@ class TestOpenRouterProfile:
{"id": "pareto-router", "min_coding_score": 0.65}
]
-
-
-
-
-
-
-
-
-
-
def test_grok_session_id_sets_cache_affinity_header(self):
"""OpenRouter + Grok model + session_id => x-grok-conv-id header."""
p = get_provider_profile("openrouter")
@@ -151,10 +49,6 @@ class TestOpenRouterProfile:
== second["extra_headers"]["x-grok-conv-id"]
)
-
-
-
-
# --- reasoning-mandatory Anthropic effort → top-level verbosity (#43432) ---
#
# These models (Claude 4.6+ / fable / mythos-class) ignore
@@ -162,20 +56,7 @@ class TestOpenRouterProfile:
# requested effort on the top-level ``verbosity`` field instead (maps to
# Anthropic ``output_config.effort``). The profile must route the existing
# ``reasoning_config["effort"]`` there while still NEVER emitting a
- # ``reasoning`` field (which would 400 — see #42991). Gate every fixture on
- # the real predicate so this stays a behavior contract, not a name snapshot.
-
- @staticmethod
- def _is_mandatory(model):
- import inspect
- p = get_provider_profile("openrouter")
- mod = inspect.getmodule(type(p))
- return mod._anthropic_reasoning_is_mandatory(model)
-
-
-
-
-
+ # ``reasoning`` field (which would 400 — see #42991).
def test_mandatory_anthropic_verbosity_coexists_with_grok_header(self):
"""A reasoning-mandatory Anthropic model is never a Grok model, but the
@@ -211,11 +92,6 @@ class TestOpenRouterProfile:
class TestNousProfile:
- def test_tags(self):
- from agent.portal_tags import nous_portal_tags
- p = get_provider_profile("nous")
- body = p.build_extra_body()
- assert body["tags"] == nous_portal_tags()
def test_sticky_session_id_normalizes_cron_timestamp(self):
"""Cron re-fires of the same job keep the same sticky routing key."""
@@ -235,23 +111,8 @@ class TestNousProfile:
assert "tags" in body
-
-
-
- def test_auth_type(self):
- p = get_provider_profile("nous")
- assert p.auth_type == "oauth_device_code"
-
-
-
-
class TestQwenProfile:
-
-
-
-
-
def test_prepare_messages_protects_nested_image_url_retry_mutation(self):
qwen = get_provider_profile("qwen-oauth")
image_url = {"url": "data:image/png;base64,original"}
@@ -280,13 +141,6 @@ class TestQwenProfile:
"data:image/png;base64,original"
)
- def test_metadata_top_level(self):
- p = get_provider_profile("qwen-oauth")
- meta = {"sessionId": "s123", "promptId": "p456"}
- eb, tl = p.build_api_kwargs_extras(qwen_session_metadata=meta)
- assert tl["metadata"] == meta
- assert "metadata" not in eb
-
class TestAlibabaRegionalAndTokenPlanProfiles:
"""#73265: the models.dev catalog advertises alibaba-cn /
@@ -296,31 +150,6 @@ class TestAlibabaRegionalAndTokenPlanProfiles:
Profile names intentionally match the catalog keys exactly so model
metadata lines up."""
- def test_alibaba_cn_registered(self):
- p = get_provider_profile("alibaba-cn")
- assert p is not None and p.name == "alibaba-cn"
- assert p.base_url == "https://dashscope.aliyuncs.com/compatible-mode/v1"
- assert "DASHSCOPE_API_KEY" in p.env_vars
- assert "DASHSCOPE_CN_BASE_URL" in p.env_vars
-
- def test_alibaba_coding_plan_cn_registered(self):
- p = get_provider_profile("alibaba-coding-plan-cn")
- assert p is not None and p.name == "alibaba-coding-plan-cn"
- assert p.base_url == "https://coding.dashscope.aliyuncs.com/v1"
- assert "ALIBABA_CODING_PLAN_API_KEY" in p.env_vars
-
- def test_alibaba_token_plan_registered(self):
- p = get_provider_profile("alibaba-token-plan")
- assert p is not None and p.name == "alibaba-token-plan"
- assert p.base_url == "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
- assert "ALIBABA_TOKEN_PLAN_API_KEY" in p.env_vars
-
- def test_alibaba_token_plan_cn_registered(self):
- p = get_provider_profile("alibaba-token-plan-cn")
- assert p is not None and p.name == "alibaba-token-plan-cn"
- assert p.base_url == "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
- assert "ALIBABA_TOKEN_PLAN_API_KEY" in p.env_vars
-
def test_cn_variants_resolve_in_auth_registry(self, monkeypatch):
"""The reporter's exact failure site: ``auth.resolve_provider()`` only
consults PROVIDER_REGISTRY (auto-extended from provider profiles,
@@ -337,5 +166,5 @@ class TestAlibabaRegionalAndTokenPlanProfiles:
"alibaba-token-plan", "alibaba-token-plan-cn"):
assert pid in PROVIDER_REGISTRY, f"{pid} missing from PROVIDER_REGISTRY"
assert resolve_provider(pid) == pid
- assert (PROVIDER_REGISTRY["alibaba-token-plan-cn"].inference_base_url
- == "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
+ assert (PROVIDER_REGISTRY[pid].inference_base_url
+ == get_provider_profile(pid).base_url)
diff --git a/tests/providers/test_transport_parity.py b/tests/providers/test_transport_parity.py
index ffe45864b63..e15ddfe1d1a 100644
--- a/tests/providers/test_transport_parity.py
+++ b/tests/providers/test_transport_parity.py
@@ -46,15 +46,6 @@ class TestNvidiaParity:
class TestKimiParity:
"""Kimi: OMIT temperature, max_tokens=32000, thinking + reasoning_effort."""
- def test_temperature_omitted(self, transport):
- kw = transport.build_kwargs(
- model="kimi-k2",
- messages=_simple_messages(),
- tools=None,
- provider_profile=get_provider_profile("kimi-coding"),
- omit_temperature=True,
- )
- assert "temperature" not in kw
def test_thinking_enabled(self, transport):
@@ -69,20 +60,10 @@ class TestKimiParity:
)
assert kw.get("reasoning_effort") == "high"
assert "thinking" not in kw.get("extra_body", {})
+ assert "reasoning_effort" not in kw.get("extra_body", {})
- def test_reasoning_effort_top_level(self, transport):
- """Kimi reasoning_effort is a TOP-LEVEL api_kwargs key, NOT in extra_body."""
- kw = transport.build_kwargs(
- model="kimi-k2",
- messages=_simple_messages(),
- tools=None,
- provider_profile=get_provider_profile("kimi-coding"),
- reasoning_config={"enabled": True, "effort": "high"},
- )
- assert kw.get("reasoning_effort") == "high"
- assert "reasoning_effort" not in kw.get("extra_body", {})
diff --git a/tests/scripts/desktop_update/test_desktop_update_gateway_flag.py b/tests/scripts/desktop_update/test_desktop_update_gateway_flag.py
index 825a41adc6a..51337857614 100644
--- a/tests/scripts/desktop_update/test_desktop_update_gateway_flag.py
+++ b/tests/scripts/desktop_update/test_desktop_update_gateway_flag.py
@@ -13,7 +13,6 @@ opt-out can silently regress.
from __future__ import annotations
-import json
import os
import subprocess
import time
@@ -94,11 +93,3 @@ def test_no_gateway_flag_omits_gateway_from_update(tmp_path):
assert "--yes" in argv
-@requires_posix_handoff
-def test_no_gateway_flag_leaves_the_result_clean(tmp_path):
- """The opt-out only drops --gateway; the hand-off still completes OK."""
- calls = _run_handoff(tmp_path, ["--no-gateway"])
-
- assert calls, "hand-off never invoked hermes"
- result = json.loads((tmp_path / ".hermes-update-result.json").read_text())
- assert result.get("status") != "error", result
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py b/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py
deleted file mode 100644
index 62467333e96..00000000000
--- a/tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""The Windows hand-off's `--gateway` flag, source-level (Linux CI cannot run PowerShell).
-
-`hermes update --gateway` (re)starts the local messaging gateway after the
-update. A Desktop served by a remote gateway (#117529) must not ask for that:
-the restarted local gateway shares the remote host's channel credentials and
-becomes a competing long-poll consumer — Telegram answers the conflict by
-rejecting one of the two `getUpdates` callers, taking the production bot
-offline. The Desktop passes `-NoGateway` on that path; these tests pin the
-script side of the contract the same source-level way
-`test_desktop_update_windows_python_handoff.py` guards its invocation rule.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-WINDOWS_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
-
-
-def _handoff_source() -> str:
- """The script with its ``-SelfTest*`` fixture blocks removed (same strip as
- test_desktop_update_windows_python_handoff.py), normalized to LF."""
- source = WINDOWS_PS1.read_text(encoding="utf-8").replace("\r\n", "\n")
- return re.sub(
- r"\n(?P<indent> *)if \(\$SelfTest\w+\) \{.*?\n(?P=indent)\}\n",
- "\n",
- source,
- )
-
-
-def test_no_gateway_switch_is_declared() -> None:
- assert re.search(r"^\s{4}\[switch\]\$NoGateway,\s*$", _handoff_source(), re.M), (
- "scripts/desktop-update/windows.ps1 must declare [switch]$NoGateway so "
- "a remote-served Desktop (#117529) can opt out of the local gateway "
- "restart."
- )
-
-
-def test_gateway_flag_is_conditional_not_inline() -> None:
- """`--gateway` may only reach the update argv through $gatewayArg.
-
- An inline literal would mean someone reintroduced an unconditional local
- gateway restart — the exact regression (#117529) this guards against.
- """
- source = _handoff_source()
-
- gateway_literals = [line for line in source.splitlines() if '"--gateway"' in line]
- assert len(gateway_literals) == 1, (
- "Expected exactly one \"--gateway\" literal in windows.ps1 (the "
- f"$gatewayArg default); found: {gateway_literals}"
- )
- assert "$gatewayArg = @(\"--gateway\")" in gateway_literals[0]
-
- assert re.search(r"if \(\$NoGateway\)\s*\{\s*\n\s*\$gatewayArg = @\(\)", source), (
- "-NoGateway must empty $gatewayArg before the update argv is assembled."
- )
- assert "$gatewayArg + @(\"--force\"" in source, (
- "The update argv must be assembled from $gatewayArg so -NoGateway "
- "actually removes --gateway from the invocation."
- )
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_pipe_drain.py b/tests/scripts/desktop_update/test_desktop_update_windows_pipe_drain.py
index 850f40bb464..20922f951ae 100644
--- a/tests/scripts/desktop_update/test_desktop_update_windows_pipe_drain.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_pipe_drain.py
@@ -56,72 +56,6 @@ REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
WINDOWS_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
-class TestIdleWatchdogCountsUpdateLogGrowth:
- """The idle watchdog must count logs/update.log growth as progress.
-
- Real updates are stdout-silent for 40+ minutes: ``hermes update`` captures
- the (very loud) Electron/vite build into ``logs/update.log`` — NOT the
- child's stdout (``hermes_cli/update_cmd.py``, the update-log tee) — so the
- step's pipes go quiet for the whole build while the update is demonstrably
- progressing. A no-output ceiling that watches only stdout/stderr would
- kill every healthy large update at ``StepIdleTimeoutSeconds`` and mark it
- exit 124.
-
- These are source-contract assertions (the executable proof is the
- ``logstall`` arm of ``-SelfTestPipeDrain``, ``windows_only`` below):
- Linux CI cannot run the PowerShell hand-off, but it CAN pin that the
- drain loop consults update-log growth before terminating the tree.
- Sabotage-proof: removing the ``Get-StepProgressLogStamp`` consult from
- the stall branch, dropping the ``logstall`` self-test arm, or dropping
- the ``HERMES_UPDATE_STEP_IDLE_SECONDS`` override each fails a test here.
- """
-
- def _src(self) -> str:
- return WINDOWS_PS1.read_text(encoding="utf-8")
-
- def test_progress_log_default_is_update_log(self):
- src = self._src()
- assert '$script:StepProgressLogPath = Join-Path $LogDir "update.log"' in src
-
- def test_progress_log_overridable_for_self_test(self):
- assert "HERMES_UPDATE_PROGRESS_LOG" in self._src()
-
- def test_idle_override_env_retained(self):
- # The user/test-facing idle override must survive the amendment.
- assert "HERMES_UPDATE_STEP_IDLE_SECONDS" in self._src()
-
- def test_stall_branch_consults_log_growth_before_terminating(self):
- src = self._src()
- assert "function Get-StepProgressLogStamp" in src
- # The consult must sit inside the idle-ceiling branch, upstream of
- # TerminateAndWait: growth resets the progress clock instead of
- # cancelling the tree. Pin the exact consult + compare + reset shape
- # so an inert consult (or a removed one) fails here.
- msg = (
- "the idle watchdog no longer checks logs/update.log growth "
- "before declaring a stall -- a healthy 40+ min build whose "
- "output goes to update.log would be killed at the idle ceiling"
- )
- assert "$currentLogStamp = Get-StepProgressLogStamp" in src, msg
- assert "if ($currentLogStamp -ne $progressLogStamp)" in src, msg
- # The growth check must gate the termination: compare-and-reset
- # appears before the 124 tree-termination inside the drain loop.
- consult = src.index("if ($currentLogStamp -ne $progressLogStamp)")
- terminate = src.index("TerminateAndWait($job, 124")
- assert consult < terminate, msg
- # And the clock actually resets on growth.
- growth_block = src[consult:terminate]
- assert "$progressLogStamp = $currentLogStamp" in growth_block, msg
- assert "$lastProgressAt = Get-Date" in growth_block, msg
-
- def test_self_test_has_silent_but_logging_arm(self):
- src = self._src()
- assert "logstall" in src, (
- "-SelfTestPipeDrain lost its silent-but-logging arm: the fixture "
- "no longer proves that a step which is quiet on its pipes but "
- "growing update.log is NOT killed by the idle watchdog"
- )
- assert "silent but logging" in src
@pytest.mark.windows_only
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
deleted file mode 100644
index 321be355544..00000000000
--- a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
+++ /dev/null
@@ -1,141 +0,0 @@
-"""Regression: the Windows Desktop update hand-off must run through python.exe.
-
-`scripts/desktop-update/windows.ps1` drives `hermes update` for the in-app
-Desktop updater. It used to invoke the update through the venv's
-`venv\\Scripts\\hermes.exe` console-script launcher. On Windows that launcher is
-a real process that keeps `hermes.exe` mapped as its running image and spawns
-`python.exe` as a child. The update ends in `uv pip install -e .`, which rewrites
-the console-script shims -- including the `hermes.exe` the launcher still has
-mapped -- and Windows refuses to replace a file mapped as a running image
-("os error 32"). The rename fallback then defers to next reboot via
-`MOVEFILE_DELAY_UNTIL_REBOOT`, which needs elevation a Desktop-driven update
-does not have, so `uv pip install -e .` exits non-zero, the ZIP fallback repeats
-the same sequence, the desktop build stage is never reached, and the pre-build
-clean has already removed `apps/desktop/release` -- leaving an install whose
-Start Menu shortcut points at a `Hermes.exe` that no longer exists.
-
-Driving the update as `python.exe -m hermes_cli.main update` puts the inherited
-image handle on `python.exe`, which uv never has to replace, so the shim is an
-ordinary unlocked file when uv rewrites it.
-
-This test is source-level because Linux CI cannot execute the PowerShell
-hand-off. The invariant it guards is that every `Invoke-HermesStep` call site
-(the update, its retry, and the desktop rebuild) drives `$pythonExe`, never the
-`$hermesExe` shim. `hermes.exe` may still be *named* in the file for the
-step-2 unlock preflight -- that is a lock probe, not an invocation -- so we
-assert against the invocation sites specifically.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-WINDOWS_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
-
-
-def _read() -> str:
- # windows.ps1 is eol=crlf in .gitattributes, so checkouts materialize
- # CRLF on disk (CI included). Normalize so the SelfTest-block strip's
- # `\n}\n` anchors match regardless of the working-copy line endings.
- return WINDOWS_PS1.read_text(encoding="utf-8").replace("\r\n", "\n")
-
-
-def _handoff_source() -> str:
- """The script with its ``-SelfTest*`` fixture blocks removed.
-
- Those blocks exercise the hand-off machinery deliberately -- the pipe-drain
- fixture runs a synthetic PowerShell step through ``Invoke-HermesStep`` to
- prove the drain cannot deadlock (#90455) -- so they are not update steps
- and the "must drive python.exe" rule does not apply to them. Each exits
- before any venv/desktop machinery runs.
-
- Scoped here rather than allow-listing a target, so the rule stays absolute
- for every real step. The non-greedy match ends at the first closing brace
- at the opening statement's indentation; inner braces are deeper.
- """
- return re.sub(
- r"\n(?P<indent> *)if \(\$SelfTest\w+\) \{.*?\n(?P=indent)\}\n",
- "\n",
- _read(),
- flags=re.S,
- )
-
-
-def test_invoke_hermes_step_calls_drive_python_not_the_shim() -> None:
- source = _handoff_source()
-
- invocations = re.findall(r"Invoke-HermesStep\s+(\$\w+)", source)
- assert invocations, (
- "Expected at least one Invoke-HermesStep call in "
- "scripts/desktop-update/windows.ps1; the update hand-off structure "
- "changed -- update this guard."
- )
-
- offenders = [exe for exe in invocations if exe != "$pythonExe"]
- assert not offenders, (
- "Every Invoke-HermesStep call in scripts/desktop-update/windows.ps1 "
- "must drive $pythonExe, not the hermes.exe shim. Driving the update "
- "through the shim keeps hermes.exe mapped as a running image, so uv's "
- "final shim rewrite fails with os error 32 and the Desktop update can "
- "never complete. Offending target(s): "
- f"{sorted(set(offenders))}."
- )
-
-
-def test_update_invocation_uses_module_entrypoint() -> None:
- source = _read()
-
- assert '@("-m", "hermes_cli.main", "update"' in source, (
- "The update step must invoke `python.exe -m hermes_cli.main update ...` "
- "so the inherited image handle lands on python.exe, which uv never has "
- "to replace."
- )
- assert (
- '@("-m", "hermes_cli.main", "desktop", "--force-build", "--build-only")'
- in source
- ), (
- "The desktop rebuild step must also go through "
- "`python.exe -m hermes_cli.main desktop ...` for the same reason."
- )
-
-
-def test_update_no_longer_invokes_the_hermes_exe_shim() -> None:
- source = _read()
-
- assert "Invoke-HermesStep $hermesExe" not in source, (
- "scripts/desktop-update/windows.ps1 still invokes the update through "
- "the hermes.exe shim (`Invoke-HermesStep $hermesExe`). That is the "
- "exact self-lock this fix removes -- route it through $pythonExe "
- "instead."
- )
-
-
-def test_handoff_resolves_uv_default_dotvenv_before_building_python_and_shim_paths() -> None:
- source = _read()
-
- assert "function Resolve-HermesVenvDir" in source
- assert 'Join-Path $Root ".venv"' in source
- assert "$VenvDir = Resolve-HermesVenvDir $InstallRoot" in source
- assert 'Join-Path $VenvDir "Scripts\\python.exe"' in source
- assert 'Join-Path $VenvDir "Scripts\\hermes.exe"' in source
-
-
-def test_desktop_relaunch_waits_for_an_in_place_rebuild() -> None:
- source = _read()
- relaunch = re.search(
- r"function Start-DesktopRelaunch \{(?P<body>.*?)\n\}\n\nfunction Invoke-HermesStep",
- source,
- re.DOTALL,
- )
- assert relaunch, "Expected Start-DesktopRelaunch in the Windows hand-off script."
-
- body = relaunch.group("body")
- assert "if (-not $RelaunchExe) { return $false }" in body
- assert "$relaunchDeadline = (Get-Date).AddSeconds(120)" in body
- assert "while (-not (Test-Path -LiteralPath $RelaunchExe))" in body
- assert "if ((Get-Date) -ge $relaunchDeadline)" in body
- assert "Start-Sleep -Milliseconds 500" in body
- assert "[System.Windows.Forms.Application]::DoEvents()" in body
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py b/tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
deleted file mode 100644
index e8bd8306d98..00000000000
--- a/tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Regression tests for Windows desktop-update Unix timestamps.
-
-PowerShell's ``Get-Date -UFormat %s`` is locale-sensitive. Under an ``es-ES``
-culture it can produce a comma decimal separator, and parsing that string with
-``InvariantCulture`` turns a ten-digit Unix timestamp plus fractional seconds
-into a value too large for ``System.Int32``. The detached Windows updater must
-use a locale-independent Unix timestamp API for both marker and result files.
-
-The updater script is not executable on the Linux CI lane, so these tests lock
-the source-level contract and reject the exact broken conversion.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-WINDOWS_UPDATE_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
-
-
-def test_windows_update_uses_locale_independent_unix_seconds() -> None:
- source = WINDOWS_UPDATE_PS1.read_text(encoding="utf-8")
- safe_expression = "[DateTimeOffset]::UtcNow.ToUnixTimeSeconds()"
- unsafe_expression = "[int][double]::Parse((Get-Date -UFormat %s)"
-
- assert source.count(safe_expression) == 2, (
- "windows.ps1 must use DateTimeOffset Unix seconds for both the "
- "update marker and the finished result timestamp"
- )
- assert unsafe_expression not in source, (
- "windows.ps1 must not parse locale-sensitive Get-Date -UFormat %s "
- "output through System.Int32"
- )
diff --git a/tests/scripts/install/test_install_clone_throttle_fallback.py b/tests/scripts/install/test_install_clone_throttle_fallback.py
deleted file mode 100644
index 973649e8ff9..00000000000
--- a/tests/scripts/install/test_install_clone_throttle_fallback.py
+++ /dev/null
@@ -1,135 +0,0 @@
-"""Fresh-install clone throttle handling (#89624).
-
-GitHub throttles packfile generation for this repo with repo-scoped HTTP
-429s (not client IP limits): the single big pack behind `--depth 1` dies
-mid-transfer with "RPC failed; HTTP 429 / expected 'packfile'", and
-clone_repo's HTTPS branch had no retry and no fallback — a fresh install
-on an ordinary unauthenticated machine exited 1 at the download stage
-(same throttle as the update path in #89287).
-
-The contract pinned here:
-- The HTTPS clone is retried with backoff before giving up.
-- A failed direct attempt is retried after removing the partial clone.
-- When every direct attempt fails, the installer degrades to a blobless
- partial clone (`--filter=blob:none --no-checkout`) and materializes the
- working tree with `git reset --hard HEAD` — the clone itself is
- commits+trees only (small, passes the throttle) and the reset becomes
- the separate blob fetch the retry can wrap (review of #89629: without
- --no-checkout the blob fetch runs inside `git clone`'s own checkout,
- so the throttle kills the whole clone and the fallback degrades to one
- more failed clone).
-- Materialization fails closed: both reset attempts failing must remove
- the checkout and report a clone failure, never report success over an
- unusable tree.
-"""
-
-from __future__ import annotations
-
-import re
-import shutil
-from pathlib import Path
-
-import pytest
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-pytestmark = pytest.mark.skipif(
- shutil.which("git") is None or shutil.which("bash") is None,
- reason="needs git and bash",
-)
-
-
-def _https_branch() -> str:
- text = INSTALL_SH.read_text()
- m = re.search(
- r"log_info \"SSH failed, trying HTTPS\.\.\..*?(?=\n fi\n)",
- text,
- re.DOTALL,
- )
- assert m is not None, "HTTPS clone branch not found in install.sh"
- return m.group(0)
-
-
-def test_https_clone_is_retried_with_backoff():
- branch = _https_branch()
- assert re.search(r"for attempt in \$\(seq 1 \"\$max_attempts\"\)", branch), (
- "the HTTPS clone must be retried a bounded number of times, with the "
- "loop bound driven by the same variable the messages report"
- )
- assert re.search(r"sleep \$\(\(attempt \* 5\)\)", branch), (
- "retries must back off between attempts"
- )
- # A failed direct attempt leaves a partial clone; it must be removed
- # before the next attempt or git refuses to clone into a non-empty dir.
- assert re.search(
- r"rm -rf \"\$INSTALL_DIR\" 2>/dev/null # partial clone is unusable",
- branch,
- ), "each failed direct attempt must clean up the partial clone"
-
-
-def test_blobless_partial_clone_fallback_exists():
- branch = _https_branch()
- assert "--filter=blob:none" in branch, (
- "after direct attempts fail, degrade to a blobless partial clone "
- "(many small packs — what gets past the repo-scoped 429)"
- )
- assert re.search(
- r"git clone --depth 1 --single-branch --filter=blob:none \\\n"
- r"\s*--no-checkout --branch \"\$BRANCH\"",
- branch,
- ), (
- "the partial clone must defer the checkout (--no-checkout): the blob "
- "fetch otherwise runs inside git clone's own checkout step, the "
- "throttle kills the whole clone, and the fallback never engages"
- )
- assert re.search(r"git reset --hard HEAD", branch), (
- "the partial clone's working tree must be materialized so the rest "
- "of the installer sees the normal files"
- )
-
-
-def test_materialization_fails_closed():
- """A failed blob materialization must not report a successful clone.
-
- The reset on a --no-checkout clone is the step that fetches the blobs,
- so it is the step most likely to be throttled. `|| true` plus an
- unconditional `clone_ok=true` would hand the rest of the installer a
- half-materialized tree while printing "Cloned via HTTPS".
- """
- branch = _https_branch()
- fallback = branch.split('log_info "Direct clone throttled')[1]
- assert "|| true" not in fallback, (
- "the materialization retry must not swallow a hard failure"
- )
- m = re.search(
- r"if \(cd \"\$INSTALL_DIR\" \\\n"
- r"\s*&& \(git reset --hard HEAD",
- fallback,
- )
- assert m is not None, (
- "the reset must be guarded: its success is the condition that sets "
- "clone_ok, and a failed reset must clean up the checkout"
- )
-
-
-def test_partial_clone_failure_still_cleans_up_and_exits():
- branch = _https_branch()
- m = re.search(
- r'if \[ "\$clone_ok" = true \]; then\n\s*log_success "Cloned via HTTPS"'
- r"\n\s*else\n\s*log_error \"Failed to clone repository\"\n\s*exit 1",
- branch,
- )
- assert m is not None, (
- "when the fallback also fails the installer must still report the "
- "failure and exit 1"
- )
-
-
-def test_fallback_runs_only_after_all_direct_attempts_fail():
- branch = _https_branch()
- direct = branch.split('log_info "Direct clone throttled')[0]
- assert re.search(r"clone_ok != true|clone_ok\" != true", direct), (
- "the blobless fallback must be gated on every direct attempt having "
- "failed — a successful direct clone must never take the fallback path"
- )
diff --git a/tests/scripts/install/test_install_diverged_update.py b/tests/scripts/install/test_install_diverged_update.py
deleted file mode 100644
index 04cb2db0a75..00000000000
--- a/tests/scripts/install/test_install_diverged_update.py
+++ /dev/null
@@ -1,67 +0,0 @@
-"""Regression: installer/bootstrap must recover from diverged managed clones.
-
-When ``~/.hermes/hermes-agent`` has local-only commits (or diverged history),
-``git pull --ff-only`` fails with exit 128 and bootstrap aborts at the
-repository stage. ``hermes update`` already resets to ``origin/$BRANCH`` in
-that case; both installer scripts must do the same.
-
-Fixes the bootstrap failure seen in #53257 and desktop update paths that run
-``install.ps1`` / ``install.sh`` non-interactively.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def _extract_install_sh_update_block() -> str:
- text = INSTALL_SH.read_text()
- match = re.search(
- r"(?P<block>git checkout \"\$BRANCH\".*?fi\n\n if \[ -n \"\$autostash_ref\" \])",
- text,
- re.DOTALL,
- )
- assert match is not None, "managed-install update block not found in install.sh"
- return match["block"]
-
-
-def _extract_install_ps1_branch_update_block() -> str:
- text = INSTALL_PS1.read_text()
- match = re.search(
- r"(?P<block>git -c windows\.appendAtomically=false checkout \$Branch.*?elseif \(\$Tag\))",
- text,
- re.DOTALL,
- )
- assert match is not None, "branch update block not found in install.ps1"
- return match["block"]
-
-
-def test_install_sh_resets_when_ff_only_pull_fails() -> None:
- block = _extract_install_sh_update_block()
-
- assert 'git pull --ff-only origin "$BRANCH"' in block
- assert 'git reset --hard "origin/$BRANCH"' in block
- assert "Fast-forward not possible" in block
-
- pull_idx = block.find('git pull --ff-only origin "$BRANCH"')
- reset_idx = block.find('git reset --hard "origin/$BRANCH"')
- assert pull_idx != -1 and reset_idx != -1
- assert pull_idx < reset_idx, "ff-only pull must be attempted before reset fallback"
-
-
-def test_install_ps1_resets_when_ff_only_pull_fails() -> None:
- block = _extract_install_ps1_branch_update_block()
-
- assert "pull --ff-only origin $Branch" in block
- assert 'reset --hard "origin/$Branch"' in block
- assert "Fast-forward not possible" in block
-
- pull_idx = block.find("pull --ff-only origin $Branch")
- reset_idx = block.find('reset --hard "origin/$Branch"')
- assert pull_idx != -1 and reset_idx != -1
- assert pull_idx < reset_idx, "ff-only pull must be attempted before reset fallback"
diff --git a/tests/scripts/install/test_install_lockfile_churn.py b/tests/scripts/install/test_install_lockfile_churn.py
index 97187add25e..a2cbccb1ae9 100644
--- a/tests/scripts/install/test_install_lockfile_churn.py
+++ b/tests/scripts/install/test_install_lockfile_churn.py
@@ -21,7 +21,6 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
pytestmark = pytest.mark.skipif(
shutil.which("git") is None or shutil.which("bash") is None,
@@ -126,20 +125,5 @@ def test_install_sh_keeps_root_lockfile_for_dirty_workspace_manifest(
assert (repo / "package-lock.json").read_text() == '{"lock":"old"}\n'
-def test_install_sh_discards_lockfile_churn_before_status_probe() -> None:
- text = INSTALL_SH.read_text()
- idx_cleanup = text.index('discard_update_lockfile_churn "$INSTALL_DIR"')
- idx_status = text.index('if [ -n "$(git status --porcelain)" ]')
- idx_stash = text.index("git stash push --include-untracked")
- assert idx_cleanup < idx_status < idx_stash
-
-
-def test_install_ps1_discards_lockfile_churn_before_status_probe() -> None:
- text = INSTALL_PS1.read_text()
- assert "function Discard-LockfileChurn" in text
- idx_cleanup = text.index("Discard-LockfileChurn $InstallDir")
- idx_status = text.index(
- "$statusOut = git -c windows.appendAtomically=false status --porcelain"
- )
- idx_stash = text.index("stash push --include-untracked")
- assert idx_cleanup < idx_status < idx_stash
+
+
diff --git a/tests/scripts/install/test_install_no_initial_commit.py b/tests/scripts/install/test_install_no_initial_commit.py
index 7f028f5f82d..e969688f73a 100644
--- a/tests/scripts/install/test_install_no_initial_commit.py
+++ b/tests/scripts/install/test_install_no_initial_commit.py
@@ -23,7 +23,6 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
pytestmark = pytest.mark.skipif(
shutil.which("git") is None or shutil.which("bash") is None,
@@ -114,23 +113,3 @@ def test_install_sh_guard_ignores_non_repo_dir(tmp_path: Path) -> None:
assert (install_dir / "f.txt").exists()
-def test_install_ps1_validity_requires_initial_commit() -> None:
- """The PowerShell repo-validity gate must also require a resolvable HEAD."""
- text = INSTALL_PS1.read_text()
- assert "rev-parse --verify HEAD" in text, (
- "install.ps1 must probe for an initial commit (#40998)"
- )
- # Contract: $repoValid is only set when the HEAD probe succeeded too.
- assert re.search(
- r"if \(\$revParseOk -and \$statusOk -and \$hasCommit\) \{",
- text,
- ), "repo validity must be gated on $hasCommit, not just rev-parse + status"
- # Cleanup must be non-destructive: move the broken checkout aside, never
- # `Remove-Item -Recurse -Force` it (review feedback on #40998).
- assert "Move-Item -LiteralPath $InstallDir" in text, (
- "install.ps1 must move an invalid checkout aside, not delete it"
- )
- assert "Remove-Item -Recurse -Force $InstallDir -ErrorAction Stop" not in text, (
- "the destructive wipe of an existing install dir must be gone "
- "(transient cleanup of a just-failed clone is fine)"
- )
diff --git a/tests/scripts/install/test_install_ps1_browser_install.py b/tests/scripts/install/test_install_ps1_browser_install.py
deleted file mode 100644
index 372f648a527..00000000000
--- a/tests/scripts/install/test_install_ps1_browser_install.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""Regression test for install.ps1 browser setup (PR #44772 review).
-
-agent-browser resolves lazily via npx everywhere else in the system
-(tools/browser_tool.py::_find_agent_browser); Install-AgentBrowser was the
-last place that still eagerly npm-installed a second, separately
-version-pinned copy of it. Removed: agent-browser acquisition now happens
-only via `hermes update`'s npx cache warm or an actual browser-tool call's
-lazy npx resolution.
-
-Linux CI cannot execute the PowerShell installer, so verification here is
-source-text-level only, matching tests/scripts/install/test_install_sh_browser_install.py
-and tests/scripts/install/test_install_ps1_ascii_only.py.
-"""
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def _extract_function_body(source: str, name: str) -> str:
- m = re.search(
- rf"^function {re.escape(name)} \{{.*?^\}}", source, re.MULTILINE | re.DOTALL
- )
- assert m, f"could not extract function {name} from install.ps1"
- return m.group(0)
-
-
-def test_install_agent_browser_no_longer_npm_installs_agent_browser() -> None:
- body = _extract_function_body(INSTALL_PS1.read_text(), "Install-AgentBrowser")
-
- assert "agent-browser@" not in body
- assert "Installing Chromium via agent-browser install" not in body
- # camofox is unrelated to this change and must still be installed here.
- assert "@askjo/camofox-browser@^1.5.2" in body
- # System-browser detection is still cheap/valuable without agent-browser.
- assert "Find-SystemBrowser" in body
- assert "Write-BrowserEnv" in body
-
-
-def test_install_agent_browser_drops_unused_skip_chromium_param() -> None:
- """$SkipChromium only existed to gate the now-removed Chromium-download
- branch; grep confirms it's never passed at the one real call site, so a
- lingering param would be dead code implying a control path that no
- longer exists."""
- body = _extract_function_body(INSTALL_PS1.read_text(), "Install-AgentBrowser")
-
- assert "SkipChromium" not in body
-
- # And the one real call site must not pass it either.
- text = INSTALL_PS1.read_text()
- call_site = re.search(r"^\s*Install-AgentBrowser.*$", text, re.MULTILINE)
- assert call_site, "could not find Install-AgentBrowser call site"
- assert "SkipChromium" not in call_site.group(0)
-
-
-def test_install_agent_browser_still_ignore_scripts_hardened() -> None:
- """The removal of agent-browser must not have also dropped the
- supply-chain hardening that still applies to the remaining camofox
- install."""
- body = _extract_function_body(INSTALL_PS1.read_text(), "Install-AgentBrowser")
-
- assert "--ignore-scripts" in body
-
-
-def test_install_agent_browser_no_longer_references_agent_browser_cmd_shim() -> None:
- """No dangling reference to the agent-browser.cmd shim should remain
- now that this function never installs it."""
- body = _extract_function_body(INSTALL_PS1.read_text(), "Install-AgentBrowser")
-
- assert "agent-browser.cmd" not in body
diff --git a/tests/scripts/install/test_install_ps1_managed_node_swap.py b/tests/scripts/install/test_install_ps1_managed_node_swap.py
deleted file mode 100644
index d17d06f2b9a..00000000000
--- a/tests/scripts/install/test_install_ps1_managed_node_swap.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Regression: the Test-Node managed-Node stage-and-swap must stay same-directory.
-
-Review concern on #81500: ``Rename-Item`` rejects a path in ``-NewName`` --
-with one carve-out. PowerShell's FileSystemProvider strips the directory and
-keeps the leaf when the ``-NewName`` path shares the directory of ``-Path``
-(``FileSystemProvider.RenameItem``: ``Path.GetDirectoryName(path) ==
-Path.GetDirectoryName(newName)`` -> ``newName = Path.GetFileName(newName)``);
-only a path that *differs in directory* throws "represents a path or device
-name". The official docs state the same exception ("you can't supply a path
-for the value of the NewName parameter, unless the path is identical to the
-path specified in the Path parameter").
-
-The swap in ``Test-Node`` relies on exactly that carve-out: it renames
-between ``$HermesHome\node`` and sibling ``node.new-*`` / ``node.old-*``
-paths (same directory, same volume -- atomic rename). This test pins the
-invariant so a future refactor cannot silently introduce a cross-directory
-rename, which would throw on every Windows install and read as a false
-"in use" deferral.
-
-Source-level because Linux CI cannot execute the Windows installer (same
-rationale as the other ``tests/test_install_ps1_*.py`` probes).
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def _swap_block() -> str:
- text = INSTALL_PS1.read_text(encoding="utf-8")
- start = text.index("# Rename-swap instead of delete-then-move:")
- end = text.index("# Session PATH so the rest of this run sees node/npm.")
- return text[start:end]
-
-
-def test_managed_node_swap_defines_staged_and_backup_as_siblings() -> None:
- swap = _swap_block()
- # $staged / $backup must be siblings of the live tree -- that is what
- # makes every Rename-Item -NewName below a same-directory path.
- assert re.search(r'\$staged\s*=\s*"\$HermesHome\\node\.new-\$stamp"', swap), (
- "$staged must be defined as a sibling of the live tree "
- '("$HermesHome\\node.new-$stamp")'
- )
- assert re.search(r'\$backup\s*=\s*"\$HermesHome\\node\.old-\$stamp"', swap), (
- "$backup must be defined as a sibling of the live tree "
- '("$HermesHome\\node.old-$stamp")'
- )
-
-
-def test_managed_node_swap_renames_stay_within_hermes_home() -> None:
- swap = _swap_block()
-
- renames = re.findall(
- r"Rename-Item\s+(\S+)\s+(\S+)\s+-ErrorAction", swap
- )
- assert len(renames) == 4, (
- f"expected 4 Rename-Item calls in the swap block, found {len(renames)}"
- )
- # -NewName accepts a path only when it shares the directory of -Path.
- # $staged / $backup are pinned to same-directory siblings by the test
- # above, so every call is a same-directory rename. Pin the actual swap
- # state machine too: live tree aside to $backup, staged tree into
- # place, and $backup restored on the rollback path. A cross-directory
- # path (e.g. "$HermesHome\sub\node") or a swapped direction must fail.
- allowed_pairs = {
- ('"$HermesHome\\node"', "$backup"), # live tree aside
- ("$staged", '"$HermesHome\\node"'), # staged into place (existing + fresh)
- ("$backup", '"$HermesHome\\node"'), # rollback restore
- }
- for src, dst in renames:
- assert (src, dst) in allowed_pairs, (
- f"Rename-Item {src} {dst}: not one of the expected swap "
- "transitions (live->backup, staged->live, backup->live rollback) "
- "-- Rename-Item rejects paths that differ in directory from -Path"
- )
diff --git a/tests/scripts/install/test_install_ps1_native_stderr_eap.py b/tests/scripts/install/test_install_ps1_native_stderr_eap.py
deleted file mode 100644
index 7ec4df9fbeb..00000000000
--- a/tests/scripts/install/test_install_ps1_native_stderr_eap.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""Regression tests for #48352: Windows PowerShell 5.1 native stderr.
-
-PowerShell 5.1 turns stderr from native commands into ``NativeCommandError``
-records when ``$ErrorActionPreference = "Stop"``. ``scripts/install.ps1`` has a
-few git/uv calls where stderr can be normal progress output, so those calls must
-run with EAP temporarily relaxed and then inspect ``$LASTEXITCODE``.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def _install_ps1() -> str:
- return INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def _assert_relaxed_call(text: str, command_pattern: str) -> None:
- helper_block_pattern = (
- r"Invoke-NativeWithRelaxedErrorAction\s*\{[^}]*"
- + command_pattern
- + r"[^}]*\}"
- )
- inline_pattern = (
- r"\$ErrorActionPreference\s*=\s*\"Continue\"[\s\S]{0,900}?"
- + command_pattern
- )
- assert re.search(helper_block_pattern, text) or re.search(inline_pattern, text), (
- f"install.ps1 must relax ErrorActionPreference around {command_pattern}"
- )
-
-
-def test_repository_stage_relieves_eap_for_ssh_and_https_git_clone() -> None:
- text = _install_ps1()
- assert "function Invoke-NativeWithRelaxedErrorAction" in text
- _assert_relaxed_call(
- text,
- r"git -c windows\.appendAtomically=false clone --depth 1 --branch \$Branch \$RepoUrlSsh \$InstallDir",
- )
- _assert_relaxed_call(
- text,
- r"git -c windows\.appendAtomically=false clone --depth 1 --branch \$Branch \$RepoUrlHttps \$InstallDir",
- )
-
-
-def test_dependency_installs_relax_eap() -> None:
- text = _install_ps1()
- _assert_relaxed_call(text, r"& \$UvCmd sync --extra all --locked")
- _assert_relaxed_call(text, r"& \$UvCmd pip install -e \$tier\.Spec")
-
-
-def test_native_eap_helper_always_restores_previous_preference() -> None:
- text = _install_ps1()
- m = re.search(
- r"function Invoke-NativeWithRelaxedErrorAction \{(?P<body>[\s\S]*?)^\}",
- text,
- re.MULTILINE,
- )
- assert m is not None, "expected a shared helper for NativeCommandError-safe calls"
- body = m.group("body")
- assert "$prevEAP = $ErrorActionPreference" in body
- assert '$ErrorActionPreference = "Continue"' in body
- assert "finally" in body
- assert "$ErrorActionPreference = $prevEAP" in body
diff --git a/tests/scripts/install/test_install_ps1_node_path_for_npm.py b/tests/scripts/install/test_install_ps1_node_path_for_npm.py
deleted file mode 100644
index 47f296f39c3..00000000000
--- a/tests/scripts/install/test_install_ps1_node_path_for_npm.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Regression tests for #48130: Windows npm lifecycle scripts need node on PATH.
-
-The desktop installer can resolve ``npm.cmd`` while postinstall hooks fail with
-``'node' is not recognized`` because child ``cmd.exe`` processes do not inherit
-a PATH that includes ``node.exe``'s directory.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def _install_ps1() -> str:
- return INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def test_install_ps1_defines_ensure_node_exe_on_path_helper() -> None:
- text = _install_ps1()
- assert "function Ensure-NodeExeOnPath" in text
- assert re.search(
- r"\$env:Path\s*=\s*\"\$nodeExeDir;\$env:Path\"",
- text,
- ), "Ensure-NodeExeOnPath must prepend node.exe's directory to PATH"
-
-
-def test_test_node_prepends_node_dir_before_success() -> None:
- text = _install_ps1()
- assert re.search(
- r"if \(Test-NodeVersionOk \$version\) \{[\s\S]{0,200}?Ensure-NodeExeOnPath",
- text,
- ), "Test-Node must call Ensure-NodeExeOnPath when a system Node passes the version floor"
-
-
-def test_install_node_deps_prepends_node_dir_before_npm() -> None:
- text = _install_ps1()
- assert re.search(
- r"function Install-NodeDeps \{[\s\S]{0,900}?Ensure-NodeExeOnPath[\s\S]{0,900}?Resolve npm explicitly",
- text,
- ), "Install-NodeDeps must call Ensure-NodeExeOnPath before invoking npm"
diff --git a/tests/scripts/install/test_install_ps1_python_fallback_venv.py b/tests/scripts/install/test_install_ps1_python_fallback_venv.py
deleted file mode 100644
index 58ef44f1a8e..00000000000
--- a/tests/scripts/install/test_install_ps1_python_fallback_venv.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""Regression: the Windows installer must honor its Python fallback at venv time.
-
-A user on Windows 11 reported (#50769) that the installer correctly detected a
-Python 3.12 fallback when 3.11 was absent::
-
- [OK] Found fallback: Python 3.12.8
- ...
- -> Creating virtual environment with Python 3.11...
-
-and then failed with ``Failed to create virtual environment (uv venv exited
-with 2)``.
-
-Root cause: ``Test-Python`` records the fallback via an in-memory
-``$script:PythonVersion = $fallbackVer`` mutation, but under Hermes-Setup.exe
-each ``-Stage NAME`` runs in its *own* fresh ``powershell.exe`` process. The
-``venv`` stage therefore starts with ``$PythonVersion`` back at its ``"3.11"``
-default, so ``uv venv venv --python 3.11`` runs on a machine that has no 3.11.
-
-The fix re-resolves the interpreter inside ``Install-Venv`` (via the
-cross-process-safe ``Resolve-AvailablePythonVersion`` helper) before creating
-the venv, so the venv stage uses whatever interpreter is actually present.
-These tests lock that contract at the source level (the script only runs on
-Windows, so there's no runner to execute it on Linux CI).
-"""
-
-import re
-from pathlib import Path
-
-import pytest
-
-_INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
[email protected](scope="module")
-def source() -> str:
- return _INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def _function_body(source: str, name: str) -> str:
- """Return the text of a PowerShell ``function <name> { ... }`` block."""
- start = source.index(f"function {name}")
- brace = source.index("{", start)
- depth = 0
- for i in range(brace, len(source)):
- if source[i] == "{":
- depth += 1
- elif source[i] == "}":
- depth -= 1
- if depth == 0:
- return source[brace : i + 1]
- raise AssertionError(f"unterminated function body for {name}")
-
-
-def test_resolver_helper_is_defined(source: str):
- """A cross-process-safe Python-version resolver must exist."""
- assert "function Resolve-AvailablePythonVersion" in source, (
- "expected a Resolve-AvailablePythonVersion helper that re-resolves the "
- "interpreter independently of the in-memory $script:PythonVersion mutation"
- )
-
-
-def test_install_venv_reresolves_before_creating_venv(source: str):
- """Install-Venv must re-resolve the interpreter BEFORE `uv venv`.
-
- Otherwise the venv stage's fresh process trusts the stale "3.11" default
- and fails on machines where only the fallback (e.g. 3.12) is installed.
- """
- body = _function_body(source, "Install-Venv")
- resolve_at = body.find("Resolve-AvailablePythonVersion")
- assert resolve_at != -1, (
- "Install-Venv must call Resolve-AvailablePythonVersion so the venv "
- "stage doesn't trust the stale $PythonVersion default across processes"
- )
- create_at = body.find("Creating virtual environment with Python")
- assert create_at != -1, "expected the venv-creation log line in Install-Venv"
- assert resolve_at < create_at, (
- "the interpreter must be re-resolved BEFORE the 'Creating virtual "
- "environment' step (and before `uv venv` runs)"
- )
-
-
-def test_fallback_list_is_single_source_of_truth(source: str):
- """The fallback versions live in one shared constant, used by both paths.
-
- A drifting second copy of the list is how detection and venv creation
- disagree in the first place.
- """
- assert re.search(r"\$PythonFallbackVersions\s*=", source), (
- "expected a shared $PythonFallbackVersions constant"
- )
- # Test-Python's fallback loop must iterate the shared constant, not an
- # inline literal list.
- test_python = _function_body(source, "Test-Python")
- assert "foreach ($fallbackVer in $PythonFallbackVersions)" in test_python, (
- "Test-Python must iterate the shared $PythonFallbackVersions constant"
- )
- # The resolver must seed its candidate list from the same constant.
- resolver = _function_body(source, "Resolve-AvailablePythonVersion")
- assert "$PythonFallbackVersions" in resolver, (
- "Resolve-AvailablePythonVersion must reuse the shared fallback constant"
- )
-
-
-def test_resolver_prefers_requested_version_then_fallbacks(source: str):
- """The resolver tries the requested version first, then the fallbacks."""
- resolver = _function_body(source, "Resolve-AvailablePythonVersion")
- assert "@($PythonVersion) + $PythonFallbackVersions" in resolver, (
- "resolver candidate order must be: requested $PythonVersion first, "
- "then the shared fallbacks"
- )
- assert "uv" in resolver and "python find" in resolver, (
- "resolver must probe availability via `uv python find`"
- )
diff --git a/tests/scripts/install/test_install_ps1_resolver_strictmode.py b/tests/scripts/install/test_install_ps1_resolver_strictmode.py
deleted file mode 100644
index c5d9d60b7a5..00000000000
--- a/tests/scripts/install/test_install_ps1_resolver_strictmode.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""Regression: the ResolvedPathReport must not read an unset resolver.
-
-Issue #93017: fresh Windows installs died at the ``$script:ResolvedPathReport``
-block with ``The variable '$script:LastResolver' cannot be retrieved because
-it has not been set`` — before any install stage ran. The mechanism:
-``ConvertTo-LongPath`` short-circuits at the top for ordinary long paths
-(``-notmatch '~\\d'`` returns early, per the comment "skip every resolver for
-ordinary long paths, which is the overwhelmingly common case"), so
-``$script:LastResolver`` is only ever assigned when a 8.3 short path actually
-needs expansion. The report block read it unconditionally, which is fatal in
-a ``Set-StrictMode`` session (the reporter hit it through three different
-invocation styles, i.e. their host/session enables strict mode).
-
-The fix initializes ``$script:LastResolver = 'none'`` at script scope before
-``Set-LongProfileEnvVars`` can run any resolver — ``'none'`` being the
-resolver's own value for "nothing ran".
-
-install.ps1 only runs on Windows, so these tests lock the contract at the
-source-text level (same style as test_install_ps1_uv_install_fallback.py).
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-_INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
-def _ps1() -> str:
- return _INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def test_last_resolver_initialized_at_script_scope():
- source = _ps1()
- match = re.search(r"^\$script:LastResolver = 'none'\s*$", source, re.MULTILINE)
- assert match is not None, (
- "$script:LastResolver must be initialized at script scope ('none') — "
- "ConvertTo-LongPath only assigns it when a short path needs expanding, "
- "so an ordinary long profile leaves it unset (#93017)"
- )
-
-
-def test_initialization_precedes_resolver_run_and_report_read():
- source = _ps1()
- init = re.search(r"^\$script:LastResolver = 'none'\s*$", source, re.MULTILINE)
- run = re.search(r"^\$script:NormalizedProfilePaths = Set-LongProfileEnvVars", source, re.MULTILINE)
- read = re.search(r"^\s+resolver\s+= \$script:LastResolver\s*$", source, re.MULTILINE)
- assert init and run and read, "init / Set-LongProfileEnvVars / report read must all exist"
- assert init.start() < run.start() < read.start(), (
- "initialization must come before Set-LongProfileEnvVars can invoke a "
- "resolver, and before the ResolvedPathReport reads the variable"
- )
-
-
-def test_convert_to_long_path_still_short_circuits_before_assigning():
- """Pin the mechanism that leaves the variable unset on normal paths.
-
- The early return for paths without an 8.3 alias is what makes the
- initialization load-bearing: if someone removes the short-circuit the
- resolver always assigns, but the guard is a deliberate performance
- choice (skip Add-Type for the overwhelmingly common case) and must
- stay — so the init must stay too.
- """
- source = _ps1()
- start = source.index("function ConvertTo-LongPath")
- body = source[start : start + 2000]
- assert re.search(r"-notmatch '~\\d'", body), (
- "ConvertTo-LongPath must keep its ordinary-long-path short-circuit "
- "(the reason $script:LastResolver can be unset without an init)"
- )
diff --git a/tests/scripts/install/test_install_ps1_uv_install_fallback.py b/tests/scripts/install/test_install_ps1_uv_install_fallback.py
deleted file mode 100644
index 9435c07a9dc..00000000000
--- a/tests/scripts/install/test_install_ps1_uv_install_fallback.py
+++ /dev/null
@@ -1,130 +0,0 @@
-"""Regression: Install-Uv must surface installer errors and have fallbacks.
-
-Issue #69216: Windows installs died with only the generic message
-``uv installed but not found at ...\\bin\\uv.exe``. Two root causes:
-
-1. ``Install-Uv`` piped the astral installer's entire output straight into
- ``Out-Null`` (``2>&1 | Out-Null``), so any real failure -- download error,
- corporate proxy block, AV quarantine, permissions -- was swallowed and
- the user only ever saw the generic post-condition failure (first
- identified in #69366).
-2. There was exactly one install source, ``astral.sh``. Corporate proxies
- commonly block astral.sh while the byte-identical installer published at
- GitHub releases downloads fine (diagnosed by @gakugaku on #69216).
-
-The fix installs a three-rung ladder inside ``Install-Uv``:
-
-- Rung 1: astral.sh installer, output captured via ``Tee-Object``.
-- Rung 2: GitHub releases installer mirror, same ``UV_INSTALL_DIR``.
-- Rung 3: salvage an existing ``uv.exe`` (``Get-Command uv`` or
- ``%USERPROFILE%\\.local\\bin\\uv.exe``) by copying it into
- ``$HermesHome\\bin\\uv.exe`` so the managed-first invariant holds.
-
-Only after all three rungs fail does it error out -- and then it prints the
-tail of the captured installer output so the real cause reaches the user.
-
-install.ps1 only runs on Windows, so these tests lock the contract at the
-source-text level (same style as test_install_ps1_uv_powershell_host.py).
-"""
-
-import re
-from pathlib import Path
-
-import pytest
-
-_INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-_GITHUB_INSTALLER_URL = (
- "https://github.com/astral-sh/uv/releases/latest/download/uv-installer.ps1"
-)
-
-
[email protected](scope="module")
-def source() -> str:
- return _INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def _install_uv_body(source: str) -> str:
- """Extract the text of Install-Uv up to the next top-level function."""
- start = source.index("function Install-Uv")
- tail = source[start + 1 :]
- match = re.search(r"^function ", tail, flags=re.MULTILINE)
- end = start + 1 + (match.start() if match else len(tail))
- return source[start:end]
-
-
-def test_astral_installer_output_not_swallowed_by_out_null(source: str):
- """Regression pin for the suppression bug (#69366 / #69216).
-
- The astral invocation must not discard the installer's merged output
- stream; a failed download/AV block has to reach the user.
- """
- forbidden = 'irm https://astral.sh/uv/install.ps1 | iex" 2>&1 | Out-Null'
- assert forbidden not in source, (
- "Install-Uv pipes the astral uv installer's output straight to "
- "Out-Null again -- failures become the generic 'uv installed but "
- "not found' message. Capture the output (e.g. Tee-Object) instead."
- )
-
-
-def test_astral_installer_output_is_captured(source: str):
- body = _install_uv_body(source)
- astral_lines = [
- ln
- for ln in body.splitlines()
- if "irm https://astral.sh/uv/install.ps1 | iex" in ln
- ]
- assert astral_lines, "astral uv installer invocation not found in Install-Uv"
- for ln in astral_lines:
- assert "Tee-Object" in ln, (
- "astral uv installer output must be captured (Tee-Object) so the "
- f"failure path can show it to the user, got: {ln.strip()!r}"
- )
-
-
-def test_github_releases_fallback_installer_present(source: str):
- """Rung 2: the GitHub releases mirror of the installer must be tried."""
- body = _install_uv_body(source)
- assert _GITHUB_INSTALLER_URL in body, (
- "Install-Uv must fall back to the GitHub releases uv installer "
- f"({_GITHUB_INSTALLER_URL}) when astral.sh is blocked "
- "(corporate proxies, #69216)."
- )
- fallback_lines = [ln for ln in body.splitlines() if _GITHUB_INSTALLER_URL in ln and "irm " in ln]
- for ln in fallback_lines:
- stripped = ln.strip()
- assert stripped.startswith("& $"), (
- "GitHub fallback installer must be invoked via the resolved "
- f"PowerShell host variable (`& $...`), got: {stripped!r}"
- )
- assert "Tee-Object" in ln, (
- f"GitHub fallback installer output must be captured too: {stripped!r}"
- )
-
-
-def test_existing_uv_salvage_rung_present(source: str):
- """Rung 3: probe PATH and the astral default dir, copy into managed bin."""
- body = _install_uv_body(source)
- assert "Get-Command uv" in body, (
- "Install-Uv must probe for an existing uv on PATH (Get-Command uv) "
- "before failing."
- )
- assert '".local\\bin\\uv.exe"' in body and "$env:USERPROFILE" in body, (
- "Install-Uv must probe the astral default install location "
- "(%USERPROFILE%\\.local\\bin\\uv.exe)."
- )
- assert "Copy-Item" in body and "$managedUv" in body, (
- "A salvaged uv.exe must be copied into the managed location "
- "($HermesHome\\bin\\uv.exe) so managed-first resolution holds."
- )
-
-
-def test_failure_path_keeps_manual_install_pointer_and_shows_output(source: str):
- body = _install_uv_body(source)
- assert "https://docs.astral.sh/uv/getting-started/installation/" in body, (
- "the manual-install pointer must survive in the failure path"
- )
- assert "$installerOutput" in body and "Select-Object -Last" in body, (
- "the failure path must print the tail of the captured installer "
- "output so the real error reaches the user"
- )
diff --git a/tests/scripts/install/test_install_ps1_uv_powershell_host.py b/tests/scripts/install/test_install_ps1_uv_powershell_host.py
deleted file mode 100644
index 89df184ead6..00000000000
--- a/tests/scripts/install/test_install_ps1_uv_powershell_host.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""Regression: the Windows installer must not spawn a bare ``powershell``.
-
-A user on Windows reported the installer getting stuck; running
-``irm https://hermes-agent.nousresearch.com/install.ps1 | iex`` failed at the
-uv step with::
-
- [X] Failed to install uv: The term 'powershell' is not recognized as the
- name of a cmdlet, function, script file, or operable program.
-
-Root cause: ``Install-Uv`` spawned the astral uv installer via a hardcoded
-bare ``powershell`` command. That name resolves only to *Windows PowerShell*
-and only when its System32 directory is on ``PATH``. Under PowerShell 7+
-(``pwsh``) -- or any session where ``powershell`` isn't on ``PATH`` -- the
-spawn dies and uv installation aborts.
-
-The fix resolves the PowerShell host executable (preferring the absolute path
-of the running host, then ``powershell``/``pwsh`` via ``Get-Command``) and
-invokes *that* instead of a bare name. These tests lock that contract at the
-source level (the script only runs on Windows, so there's no runner to
-execute it on Linux CI).
-"""
-
-from pathlib import Path
-
-import pytest
-
-_INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
[email protected](scope="module")
-def source() -> str:
- return _INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def test_astral_uv_installer_not_spawned_via_bare_powershell(source: str):
- """The exact failing literal must be gone."""
- forbidden = 'powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv'
- assert forbidden not in source, (
- "Install-Uv still spawns the astral uv installer via a bare "
- "`powershell` — it must use the resolved PowerShell host exe so it "
- "works under pwsh / when powershell isn't on PATH."
- )
-
-
-def test_astral_uv_installer_invoked_via_resolved_host_variable(source: str):
- """The astral uv installer line must use the call operator on a variable.
-
- i.e. ``& $psHostExe -ExecutionPolicy ... irm https://astral.sh/uv...``
- rather than naming a fixed executable.
- """
- lines = [ln for ln in source.splitlines() if "astral.sh/uv/install.ps1 | iex" in ln]
- # Exactly one invocation line carries the astral installer.
- invocation = [ln for ln in lines if "irm https://astral.sh/uv/install.ps1 | iex" in ln]
- assert invocation, "astral uv install invocation line not found"
- for ln in invocation:
- stripped = ln.strip()
- assert stripped.startswith("& $"), (
- f"astral uv installer must be invoked via the call operator on a "
- f"resolved host variable (`& $...`), got: {stripped!r}"
- )
-
-
-def test_powershell_host_resolver_is_defined_and_portable(source: str):
- """A host-resolver helper must exist and be PATH-independent + pwsh-aware."""
- assert "function Get-PowerShellHostExe" in source, (
- "expected a Get-PowerShellHostExe helper that resolves the host exe"
- )
- # PATH-independent: derive the absolute path of the running host.
- assert "Get-Process -Id $PID" in source, (
- "resolver must derive the current host's absolute path "
- "(Get-Process -Id $PID), which is independent of PATH"
- )
- # pwsh-aware fallback: PowerShell 7's executable is `pwsh`, not `powershell`.
- assert "pwsh" in source, (
- "resolver must fall back to pwsh (PowerShell 7) when powershell is "
- "unavailable"
- )
diff --git a/tests/scripts/install/test_install_ps1_venv_process_tree.py b/tests/scripts/install/test_install_ps1_venv_process_tree.py
deleted file mode 100644
index 05df59c6ee4..00000000000
--- a/tests/scripts/install/test_install_ps1_venv_process_tree.py
+++ /dev/null
@@ -1,179 +0,0 @@
-"""Windows installer regression for Hermes children outside the venv.
-
-The venv sweep deliberately selects process roots by executable path so it
-does not kill unrelated Python processes. A selected Hermes process can spawn
-a managed-runtime child whose executable lives outside the venv, though. The
-installer must stop that whole tree before replacing the venv.
-"""
-
-from __future__ import annotations
-
-import os
-import shutil
-import subprocess
-import time
-from pathlib import Path
-
-import psutil
-import pytest
-
-from tests.install_ps1_fake_uv import compile_fake_uv
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-POWERSHELL = next(
- (candidate for candidate in ("powershell", "pwsh") if shutil.which(candidate)),
- None,
-)
-
-
-def _pid_is_running(pid: int) -> bool:
- return psutil.pid_exists(pid)
-
-
-def _wait_until_stopped(pid: int, timeout: float = 10) -> bool:
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- if not _pid_is_running(pid):
- return True
- time.sleep(0.1)
- return not _pid_is_running(pid)
-
-
-def _find_child_pid(parent_pid: int, executable: Path, timeout: float = 10) -> int:
- expected = str(executable).replace("'", "''")
- query = (
- f"$expected = '{expected}'; "
- f"Get-CimInstance Win32_Process -Filter 'ParentProcessId = {parent_pid}' | "
- "Where-Object { $_.ExecutablePath -and "
- "[string]::Equals($_.ExecutablePath, $expected, "
- "[System.StringComparison]::OrdinalIgnoreCase) } | "
- "Select-Object -First 1 -ExpandProperty ProcessId"
- )
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- result = subprocess.run(
- [POWERSHELL, "-NoProfile", "-Command", query],
- capture_output=True,
- text=True,
- )
- if result.returncode == 0 and result.stdout.strip():
- return int(result.stdout.strip())
- time.sleep(0.1)
- raise AssertionError(f"child process did not start under PID {parent_pid}")
-
-
-def _stop_tree(pid: int) -> None:
- subprocess.run(
- ["taskkill", "/PID", str(pid), "/T", "/F"],
- capture_output=True,
- text=True,
- )
-
-
-def _write_cmd(path: Path, text: str) -> None:
- with path.open("w", encoding="ascii", newline="\r\n") as handle:
- handle.write(text)
-
-
[email protected]_system_guard_bypass
- os.name != "nt" or POWERSHELL is None,
- reason="needs Windows and PowerShell",
-)
-def test_venv_sweep_stops_managed_runtime_children_but_not_unrelated_processes(
- tmp_path: Path,
-) -> None:
- hermes_home = tmp_path / "hermes-home"
- install_dir = hermes_home / "hermes-agent"
- venv_scripts = install_dir / "venv" / "Scripts"
- runtime_dir = install_dir / ".hermes-runtime" / "python" / "generation-test"
- unrelated_dir = tmp_path / "unrelated"
- fake_bin = tmp_path / "fake-bin"
- for directory in (venv_scripts, runtime_dir, unrelated_dir, fake_bin):
- directory.mkdir(parents=True)
-
- system_cmd = Path(os.environ["SystemRoot"]) / "System32" / "cmd.exe"
- venv_parent_exe = venv_scripts / "python.exe"
- runtime_child_exe = runtime_dir / "python.exe"
- unrelated_exe = unrelated_dir / "python.exe"
- for target in (venv_parent_exe, runtime_child_exe, unrelated_exe):
- shutil.copy2(system_cmd, target)
-
- parent_script = tmp_path / "parent.cmd"
- _write_cmd(
- parent_script,
- f'@"{runtime_child_exe}" /d /c ping -t 127.0.0.1 ^>nul\n',
- )
- unrelated_script = tmp_path / "unrelated.cmd"
- _write_cmd(unrelated_script, "@ping -t 127.0.0.1 >nul\n")
-
- # Keep the test away from real gateway tasks and real Hermes launchers
- # while still exercising the installer's actual process enumeration and
- # per-PID taskkill behavior.
- _write_cmd(fake_bin / "schtasks.cmd", "@exit /b 0\n")
- _write_cmd(
- fake_bin / "taskkill.cmd",
- "@echo off\n"
- 'echo %* | "%SystemRoot%\\System32\\findstr.exe" /I '
- '/C:"/IM hermes.exe" >nul\n'
- "if not errorlevel 1 exit /b 0\n"
- '"%SystemRoot%\\System32\\taskkill.exe" %*\n',
- )
- uv = hermes_home / "bin" / "uv.exe"
- uv.parent.mkdir(parents=True)
- compile_fake_uv(POWERSHELL, uv)
- wrapper = tmp_path / "run-venv-stage.ps1"
- wrapper.write_text(
- f"function global:schtasks {{ & '{fake_bin / 'schtasks.cmd'}' @args }}\n"
- f"function global:taskkill {{ & '{fake_bin / 'taskkill.cmd'}' @args }}\n"
- f"& '{INSTALL_PS1}' -Stage venv -NonInteractive "
- f"-InstallDir '{install_dir}' -HermesHome '{hermes_home}'\n"
- "exit $LASTEXITCODE\n",
- encoding="utf-8",
- )
-
- creation_flags = subprocess.CREATE_NO_WINDOW
- parent = subprocess.Popen(
- [str(venv_parent_exe), "/d", "/c", str(parent_script)],
- creationflags=creation_flags,
- )
- unrelated = subprocess.Popen(
- [str(unrelated_exe), "/d", "/c", str(unrelated_script)],
- creationflags=creation_flags,
- )
- child_pid = 0
- try:
- child_pid = _find_child_pid(parent.pid, runtime_child_exe)
- assert _pid_is_running(child_pid)
- assert _pid_is_running(unrelated.pid)
-
- env = os.environ | {
- "OS": "Windows_NT",
- "PATH": str(fake_bin) + os.pathsep + os.environ["PATH"],
- "FAKE_UV_LOG": str(tmp_path / "uv.log"),
- "FAKE_MANAGED_PYTHON": str(runtime_child_exe),
- "FAKE_THIRD_PARTY_PYTHON": str(unrelated_exe),
- }
- result = subprocess.run(
- [
- POWERSHELL,
- "-NoProfile",
- "-File",
- str(wrapper),
- ],
- cwd=tmp_path,
- env=env,
- capture_output=True,
- text=True,
- )
-
- assert result.returncode == 0, result.stdout + result.stderr
- assert _wait_until_stopped(parent.pid)
- assert _wait_until_stopped(child_pid)
- assert _pid_is_running(unrelated.pid)
- finally:
- for pid in (child_pid, parent.pid, unrelated.pid):
- if pid:
- _stop_tree(pid)
diff --git a/tests/scripts/install/test_install_ps1_venv_recreate_safety.py b/tests/scripts/install/test_install_ps1_venv_recreate_safety.py
deleted file mode 100644
index 542d3d582d9..00000000000
--- a/tests/scripts/install/test_install_ps1_venv_recreate_safety.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""Regression tests for transactional Windows venv recreation (#83149).
-
-The installer must never delete the live venv in place. Windows can remove
-unlocked files before it reaches a locked interpreter or native extension,
-leaving a half-installed venv that the next health/blocker probe cannot use.
-"""
-
-from pathlib import Path
-
-
-INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
-def _function_body(source: str, function_name: str) -> str:
- start = source.index(f"function {function_name}")
- opening_brace = source.index("{", start)
- depth = 0
- for index in range(opening_brace, len(source)):
- if source[index] == "{":
- depth += 1
- elif source[index] == "}":
- depth -= 1
- if depth == 0:
- return source[opening_brace : index + 1]
- raise AssertionError(f"unterminated function: {function_name}")
-
-
-def _install_venv_body() -> str:
- return _function_body(INSTALL_PS1.read_text(encoding="ascii"), "Install-Venv")
-
-
-def test_rename_failure_cannot_fall_back_to_destructive_delete() -> None:
- body = _install_venv_body()
-
- assert "falling back to in-place delete" not in body.lower()
- assert 'Remove-Item -Recurse -Force "venv"' not in body
-
-
-def test_manual_recovery_hints_do_not_delete_live_venv() -> None:
- source = INSTALL_PS1.read_text(encoding="ascii")
-
- assert "Remove-Item -Recurse -Force venv" not in source
- assert "Do not delete venv in place" in source
-
-
-def test_recreate_restores_parked_venv_after_failure() -> None:
- body = _install_venv_body()
-
- failure = body.index("Failed to create virtual environment")
- restore = body.index(
- 'Rename-Item -LiteralPath $venvBackupName -NewName "venv"'
- )
- assert failure < restore
- assert "rollback failed" in body.lower()
-
-
-def test_recreate_rejects_success_without_venv_interpreter() -> None:
- body = _install_venv_body()
-
- missing_python = body.index("$venvPythonExe")
- success = body.index("Virtual environment ready")
- assert "Test-Path -LiteralPath $venvPythonExe -PathType Leaf" in body[
- missing_python:success
- ]
- assert "throw" in body[missing_python:success]
diff --git a/tests/scripts/install/test_install_ps1_venv_rename_abort.py b/tests/scripts/install/test_install_ps1_venv_rename_abort.py
deleted file mode 100644
index e59ca8ec93c..00000000000
--- a/tests/scripts/install/test_install_ps1_venv_rename_abort.py
+++ /dev/null
@@ -1,64 +0,0 @@
-"""Regression: Windows installer must not gut the venv on rename failure (#83149).
-
-When recreating an existing venv, ``Install-Venv`` renames the directory aside
-first. An older fallback deleted the tree in place when rename was denied; a
-partial ``Remove-Item`` could wipe most of ``site-packages`` and then fail on
-one locked ``.pyd``, leaving Hermes unusable with no rollback.
-
-These tests lock the contract at the source level (the script only runs on
-Windows, so Linux CI cannot execute the PowerShell path).
-"""
-
-from pathlib import Path
-
-import pytest
-
-_INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
[email protected](scope="module")
-def source() -> str:
- return _INSTALL_PS1.read_text(encoding="utf-8")
-
-
-def _function_body(source: str, name: str) -> str:
- """Return the text of a PowerShell ``function <name> { ... }`` block."""
- start = source.index(f"function {name}")
- brace = source.index("{", start)
- depth = 0
- for i in range(brace, len(source)):
- if source[i] == "{":
- depth += 1
- elif source[i] == "}":
- depth -= 1
- if depth == 0:
- return source[brace : i + 1]
- raise AssertionError(f"unterminated function body for {name}")
-
-
-def test_install_venv_aborts_when_rename_aside_fails(source: str):
- """Rename failure must throw with the previous install left intact."""
- body = _function_body(source, "Install-Venv")
- assert (
- "Rename-Item -LiteralPath \"venv\"" in body
- or "Rename-Item -LiteralPath 'venv'" in body
- )
- assert "falling back to in-place delete" not in body
- throw_at = body.find("Could not move the existing venv aside")
- assert throw_at != -1, "rename failure must abort with an actionable error"
- assert "throw" in body[max(0, throw_at - 80) : throw_at + 40]
-
-
-def test_install_venv_never_removes_live_venv_in_place_on_rename_fail(source: str):
- """After a failed rename, Install-Venv must not Remove-Item the live venv.
-
- Parked ``venv.stale.*`` trees may still be deleted best-effort; the live
- ``venv`` directory must only disappear via Rename-Item.
- """
- body = _function_body(source, "Install-Venv")
- # The only Remove-Item targeting the active tree used to be the fallback:
- # Remove-Item -Recurse -Force "venv"
- # That path must be gone. Stale-parking cleanup uses $staleName / filter.
- assert 'Remove-Item -Recurse -Force "venv"' not in body
- assert "Remove-Item -Recurse -Force 'venv'" not in body
- assert "venv.stale." in body
diff --git a/tests/scripts/install/test_install_ps1_venv_transaction_boundary.py b/tests/scripts/install/test_install_ps1_venv_transaction_boundary.py
deleted file mode 100644
index b0ddf23911a..00000000000
--- a/tests/scripts/install/test_install_ps1_venv_transaction_boundary.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Transaction-boundary regression for Windows venv recreation (#83149).
-
-Review finding on PR #83194 (egilewski): the rollback source (the parked
-previous venv) was deleted as soon as ``Install-Venv`` saw a working
-interpreter in the replacement — but ``Install-Dependencies`` is a separate,
-later stage (a separate *process* under the stage-per-process bootstrap) and
-every dependency tier or the baseline-import gate can still fail after that
-point. Deleting the backup early re-creates exactly the availability failure
-the transactional recreate exists to prevent.
-
-The contract locked here:
-
-* ``Install-Venv`` records the parked backup in ``venv.pending-backup``
- instead of deleting it, and its stale-tree sweep excludes that backup.
-* ``Install-Dependencies`` restores the previous venv on failure
- (``Restore-VenvBackup``) and commits the cleanup only after the
- baseline-import gate passes (``Complete-VenvTransaction``).
-
-The script only runs on Windows, so Linux CI locks the contract at the
-source level, same approach as tests/scripts/install/test_install_ps1_venv_recreate_safety.py.
-"""
-
-from pathlib import Path
-
-INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
-def _function_body(source: str, function_name: str) -> str:
- start = source.index(f"function {function_name}")
- opening_brace = source.index("{", start)
- depth = 0
- for index in range(opening_brace, len(source)):
- if source[index] == "{":
- depth += 1
- elif source[index] == "}":
- depth -= 1
- if depth == 0:
- return source[opening_brace : index + 1]
- raise AssertionError(f"unterminated function: {function_name}")
-
-
-def _source() -> str:
- return INSTALL_PS1.read_text(encoding="ascii")
-
-
-def test_install_venv_does_not_delete_backup_before_dependency_stage() -> None:
- """The parked previous venv must survive Install-Venv's success path."""
- body = _function_body(_source(), "Install-Venv")
-
- # The success path records the rollback source instead of deleting it.
- assert "venv.pending-backup" in body
- # The only backup deletion allowed inside Install-Venv is the *rollback*
- # rename in the catch block; a Remove-Item of the backup must not appear.
- assert "Remove-Item -LiteralPath $venvBackupName" not in body
-
-
-def test_install_venv_stale_sweep_excludes_current_backup() -> None:
- """The venv.stale.* sweep must not delete this run's rollback source."""
- body = _function_body(_source(), "Install-Venv")
-
- sweep_at = body.index('Get-ChildItem -Directory -Filter "venv.stale.*"')
- window = body[sweep_at : sweep_at + 400]
- assert "$_.Name -ne $venvBackupName" in window, (
- "the stale-tree sweep must exclude the backup parked by this run"
- )
-
-
-def test_install_dependencies_restores_backup_on_failure() -> None:
- """A failed dependency tier or import gate must restore the parked venv."""
- body = _function_body(_source(), "Install-Dependencies")
-
- assert "Restore-VenvBackup" in body
- catch_at = body.index("Restore-VenvBackup")
- assert "throw" in body[catch_at : catch_at + 400], (
- "rollback must rethrow the original failure after restoring"
- )
-
-
-def test_install_dependencies_commits_only_after_import_gate() -> None:
- """Backup cleanup must come after the baseline-import verification."""
- body = _function_body(_source(), "Install-Dependencies")
-
- import_gate = body.index("Baseline imports verified in venv")
- commit = body.index("Complete-VenvTransaction")
- assert import_gate < commit, (
- "the venv transaction must commit only after imports prove the "
- "replacement usable"
- )
-
-
-def test_restore_helper_parks_failed_replacement_and_restores_previous() -> None:
- body = _function_body(_source(), "Restore-VenvBackup")
-
- park = body.index("venv.failed.")
- restore = body.index('-NewName "venv"')
- assert park < restore, (
- "the failed replacement must be parked before the previous venv is "
- "renamed back into place"
- )
-
-
-def test_commit_helper_deletes_backup_and_clears_marker() -> None:
- body = _function_body(_source(), "Complete-VenvTransaction")
-
- assert "Remove-Item" in body
- assert "venv.pending-backup" in body
diff --git a/tests/scripts/install/test_install_ps1_web_server_syntax_probe.py b/tests/scripts/install/test_install_ps1_web_server_syntax_probe.py
deleted file mode 100644
index 6378d509a00..00000000000
--- a/tests/scripts/install/test_install_ps1_web_server_syntax_probe.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""Regression: install.ps1 must syntax-check the dashboard backend source.
-
-Issue #59004 reported a fresh Windows desktop install crashing on launch
-because ``hermes_cli/web_server.py`` inside the installed checkout still
-contained merge-conflict markers. Import-only dependency probes (fastapi /
-uvicorn) do not catch that: the packages can be present while the backend
-source itself is unparsable.
-
-This test is source-level because Linux CI cannot execute the PowerShell
-installer. It locks the contract that install.ps1 runs ``py_compile`` against
-``hermes_cli/web_server.py`` and fails the stage when that syntax probe fails.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def test_install_ps1_compiles_web_server_source_after_web_deps_probe() -> None:
- text = INSTALL_PS1.read_text(encoding="utf-8")
-
- probe = re.search(
- r'import fastapi, uvicorn[\s\S]{0,1200}?-m py_compile "\$InstallDir\\hermes_cli\\web_server\.py"',
- text,
- )
- assert probe is not None, (
- "install.ps1 must syntax-check hermes_cli/web_server.py after the "
- "dashboard dependency probe so a fresh desktop install fails early on "
- "merge-conflict markers or other SyntaxErrors."
- )
-
-
-def test_install_ps1_fails_stage_when_web_server_syntax_probe_fails() -> None:
- text = INSTALL_PS1.read_text(encoding="utf-8")
-
- assert "if ($LASTEXITCODE -eq 0) { $webServerSyntaxOk = $true }" in text
- assert "if (-not $webServerSyntaxOk) {" in text
- assert (
- 'throw "dashboard backend source failed syntax check: hermes_cli/web_server.py"'
- in text
- ), (
- "install.ps1 must fail the install stage when hermes_cli/web_server.py "
- "does not compile, instead of writing a broken desktop/backend install."
- )
diff --git a/tests/scripts/install/test_install_scripts_computer_use.py b/tests/scripts/install/test_install_scripts_computer_use.py
deleted file mode 100644
index cb6d8975f1b..00000000000
--- a/tests/scripts/install/test_install_scripts_computer_use.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""Regression tests: installers provision cua-driver (Computer Use).
-
-Policy: choosing Computer Use should be a config flip, not a surprise
-multi-minute binary fetch. The installers pre-install cua-driver
-(best-effort, skippable), and the dashboard toggle auto-installs when the
-binary is still missing (see test_web_routers_tools_install_on_enable.py).
-"""
-
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-class TestInstallSh:
- def test_has_skip_flag(self) -> None:
- text = INSTALL_SH.read_text()
- assert "--skip-computer-use)" in text
- assert "SKIP_COMPUTER_USE=true" in text
- assert "SKIP_COMPUTER_USE=false" in text # default off
- assert "--skip-computer-use Skip the cua-driver" in text
-
- def test_install_function_wired_into_main_and_stage(self) -> None:
- text = INSTALL_SH.read_text()
- assert "install_computer_use_driver() {" in text
- # main() flow and the node-deps stage both run it.
- assert text.count("install_computer_use_driver\n") >= 2
-
- def test_install_is_timeboxed_above_upstream_lock_window(self) -> None:
- """The upstream installer serializes on a lock with a 600s stale
- window; a ceiling below that reintroduces the self-perpetuating
- wedge (#58762). Must stay >= 660."""
- text = INSTALL_SH.read_text()
- assert "run_with_timeout 660 /bin/bash -c" in text
-
- def test_install_is_best_effort(self) -> None:
- text = INSTALL_SH.read_text()
- assert "Computer Use driver install failed" in text
- assert "hermes computer-use install" in text
-
- def test_skips_unwritable_applications_dir(self) -> None:
- """Non-admin macOS accounts can't receive CuaDriver.app (#47865
- class) — skip cleanly instead of failing every install."""
- text = INSTALL_SH.read_text()
- assert '[ -d /Applications ] && [ ! -w /Applications ]' in text
-
-
-class TestInstallPs1:
- def test_has_skip_switch(self) -> None:
- text = INSTALL_PS1.read_text()
- assert "[switch]$SkipComputerUse," in text
- assert "if ($SkipComputerUse)" in text
-
- def test_install_function_wired_into_node_deps(self) -> None:
- text = INSTALL_PS1.read_text()
- assert "function Install-CuaDriver {" in text
- assert " Install-CuaDriver\n" in text
-
- def test_install_is_timeboxed_above_upstream_lock_window(self) -> None:
- text = INSTALL_PS1.read_text()
- assert "Wait-Job $job -Timeout 660" in text
-
- def test_install_is_best_effort(self) -> None:
- text = INSTALL_PS1.read_text()
- assert "Computer Use driver install timed out" in text
- assert "hermes computer-use install" in text
-
- def test_install_rechecks_runtime_contract_before_success(self) -> None:
- text = INSTALL_PS1.read_text()
- assert "$installedCuaDriver = Get-Command cua-driver" in text
- assert (
- "Test-CuaDriverRuntimeContract -DriverPath $installedCuaDriver.Source"
- in text
- )
- assert "did not produce a compatible runtime" in text
diff --git a/tests/scripts/install/test_install_sh_browser_install.py b/tests/scripts/install/test_install_sh_browser_install.py
index e2f5f0323ce..0482dcf024c 100644
--- a/tests/scripts/install/test_install_sh_browser_install.py
+++ b/tests/scripts/install/test_install_sh_browser_install.py
@@ -12,72 +12,6 @@ REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def test_install_script_honors_explicit_browser_override_only() -> None:
- """find_system_browser consults only an explicit AGENT_BROWSER_EXECUTABLE_PATH."""
- text = INSTALL_SH.read_text()
-
- assert 'override="${AGENT_BROWSER_EXECUTABLE_PATH:-}"' in text
- # An explicit override still skips the bundled download (override, not fallback).
- assert "Skipping bundled Chromium download" in text
-
-
-
-
-def test_playwright_installs_are_timeout_guarded() -> None:
- text = INSTALL_SH.read_text()
-
- # The timeout wrapper still exists and is used internally by the install
- # wrapper, so every Playwright download remains bounded.
- assert "run_browser_install_with_timeout()" in text
- # Playwright installs now go through run_playwright_install(), which wraps
- # run_browser_install_with_timeout (timeout-guarded) and adds an
- # unrecognized-platform fallback retry.
- assert "run_playwright_install 600 npx playwright install chromium" in text
- # --with-deps is still invoked on apt-based systems, but only when sudo
- # is available non-interactively (root or passwordless sudo). Non-sudo
- # service users fall back to the browser-only install — see
- # install_node_deps() in install.sh.
- assert "run_playwright_install 600 npx playwright install --with-deps chromium" in text
- # The wrapper still bounds the download with the timeout helper.
- assert 'run_browser_install_with_timeout "$timeout_seconds" "$@"' in text
-
-
-
-def test_install_script_supports_skip_browser_flag() -> None:
- """--skip-browser (and --no-playwright alias) skips the Playwright install."""
- text = INSTALL_SH.read_text()
-
- assert "--skip-browser|--no-playwright)" in text
- assert "SKIP_BROWSER=true" in text
- assert 'if [ "$SKIP_BROWSER" = true ]; then' in text
- assert "--skip-browser Skip Playwright/Chromium install" in text
-
-
-
-
-
-
-def test_browser_install_timeout_stays_interruptible() -> None:
- """The Playwright download must stay Ctrl+C-able and force-kill if wedged.
-
- GNU `timeout` runs the child in its own process group, so a terminal Ctrl+C
- reaches `timeout` but never the download — it looks frozen and ignores
- Ctrl+C (#35166). `--foreground` keeps it in the shell's foreground group;
- `-k 10` guarantees a SIGKILL after the deadline. Both are GNU-only, so the
- installer probes support once and falls back to plain `timeout`.
- """
- text = INSTALL_SH.read_text()
-
- # GNU-flag probe + the guarded invocation must both be present. The timeout
- # binary is parameterized ($timeout_bin) so macOS gtimeout works too (#39219).
- assert '"$timeout_bin" --foreground -k 10 1 true' in text
- assert '"$timeout_bin" --foreground -k 10 "$timeout_seconds" "$@"' in text
- # Plain-timeout fallback preserved for BusyBox/non-GNU.
- assert '"$timeout_bin" "$timeout_seconds" "$@"' in text
-
-
# ---------------------------------------------------------------------------
# Behavioral tests: source the install.sh helpers in a stubbed shell and assert
# the override retry fires ONLY on a too-new apt release (#35166), and not on a
@@ -177,10 +111,6 @@ def test_override_retry_fires_on_ubuntu_26() -> None:
assert r["final_rc"] == 0
-
-
-
-
def test_override_retry_fires_on_debian_14() -> None:
"""Debian 14 (> 13) is the too-new apt case → retry with override."""
r = _run_install_fn("debian", "14", native_fails=True)
@@ -197,53 +127,3 @@ def test_no_retry_when_native_succeeds_on_ubuntu_26() -> None:
assert r["final_rc"] == 0
-import re
-
-
-def _extract_function_body(source: str, name: str) -> str:
- m = re.search(rf"^{re.escape(name)}\(\) \{{.*?^\}}", source, re.MULTILINE | re.DOTALL)
- assert m, f"could not extract {name}() from install.sh"
- return m.group(0)
-
-
-def test_ensure_browser_no_longer_npm_installs_agent_browser() -> None:
- """agent-browser resolves lazily via npx everywhere else in the system
- (tools/browser_tool.py::_find_agent_browser); this was the last place
- that still eagerly npm-installed a second, separately version-pinned
- copy of it. Removed: agent-browser acquisition now happens only via
- `hermes update`'s npx cache warm or an actual browser-tool call's lazy
- npx resolution (PR #44772 review)."""
- body = _extract_function_body(INSTALL_SH.read_text(), "ensure_browser")
-
- assert "agent-browser@" not in body
- assert "Installing Chromium via agent-browser install" not in body
- # camofox is unrelated to this change and must still be installed here.
- assert "@askjo/camofox-browser@^1.5.2" in body
- # System-browser detection is still cheap/valuable without agent-browser.
- assert "find_system_browser" in body
- assert "configure_browser_env_from_system_browser" in body
-
-
-def test_ensure_browser_still_ignore_scripts_and_timeout_guarded() -> None:
- """The removal of agent-browser must not have also dropped the
- supply-chain and hang-protection hardening that still applies to the
- remaining camofox install."""
- body = _extract_function_body(INSTALL_SH.read_text(), "ensure_browser")
-
- assert "--ignore-scripts" in body
- assert "run_with_timeout" in body
-
-
-def test_ensure_browser_no_longer_references_agent_browser_binary_path() -> None:
- """No dangling reference to a local agent-browser binary path should
- remain now that this function never installs it — a leftover reference
- would be dead code pointing at a binary that no longer gets placed
- there by this function."""
- body = _extract_function_body(INSTALL_SH.read_text(), "ensure_browser")
-
- assert "$HERMES_HOME/node/bin/agent-browser" not in body
-
-
-
-
-
diff --git a/tests/scripts/install/test_install_sh_install_method_stamp.py b/tests/scripts/install/test_install_sh_install_method_stamp.py
deleted file mode 100644
index 6ca5f09ed28..00000000000
--- a/tests/scripts/install/test_install_sh_install_method_stamp.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""Contract test: install.sh stamps the install method next to the code tree
-($INSTALL_DIR), not into the shared $HERMES_HOME.
-
-Background (shared-$HERMES_HOME bug)
-------------------------------------
-$HERMES_HOME is a data directory users frequently bind-mount into a Docker
-gateway as well (``~/.hermes:/opt/data``). The published image stamps 'docker'
-there on boot, so if install.sh had written its 'git' marker into the same
-$HERMES_HOME the two installs would fight over one slot — and the container,
-booting last, would win and wrongly make the host install look like 'docker'
-(blocking ``hermes update``).
-
-The fix: detect_install_method() reads a CODE-scoped stamp first, and the
-installer writes ``git`` into $INSTALL_DIR (the git checkout, e.g.
-``~/.hermes/hermes-agent``), which is unique to this install and immune to the
-shared data dir.
-"""
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def test_install_sh_stamps_code_tree_not_home() -> None:
- text = INSTALL_SH.read_text()
-
- # Stamps the code tree.
- assert text.count('echo "git" > "$INSTALL_DIR/.install_method"') >= 1, (
- "install.sh must stamp $INSTALL_DIR/.install_method (code-scoped)"
- )
-
- # Never stamps the shared data dir.
- assert not re.search(r'>\s*"\$HERMES_HOME/\.install_method"', text), (
- "install.sh must not stamp $HERMES_HOME/.install_method — that data "
- "dir may be shared with a Docker gateway whose 'docker' stamp would "
- "clobber it and block host-side `hermes update`"
- )
diff --git a/tests/scripts/install/test_install_sh_node_global_prefix.py b/tests/scripts/install/test_install_sh_node_global_prefix.py
deleted file mode 100644
index f2ac4cb929a..00000000000
--- a/tests/scripts/install/test_install_sh_node_global_prefix.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""Regression tests for the Hermes-managed Node's npm global prefix.
-
-When the installer falls back to a bundled Node under ``$HERMES_HOME/node``,
-npm's default global prefix is that Node dir, so ``npm install -g <pkg>``
-drops the package binary in ``$HERMES_HOME/node/bin`` — which is NOT on PATH
-(only the command link dir is) and is wiped on every Node upgrade. Users then
-report "I can ``npm i -g`` but the package isn't usable on the command line".
-
-The fix redirects the bundled Node's global prefix to the command link dir's
-parent (so global bins land in the already-on-PATH link dir alongside
-node/npm/npx), scoped to the bundled Node via its prefix-local global npmrc.
-"""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-NODE_BOOTSTRAP = REPO_ROOT / "scripts" / "lib" / "node-bootstrap.sh"
-
-
-def test_install_sh_redirects_bundled_npm_global_prefix_to_link_dir() -> None:
- text = INSTALL_SH.read_text()
-
- # The redirect must target the link dir's PARENT so global bins resolve to
- # <parent>/bin == the command link dir (node/npm/npx live there and it is
- # guaranteed on PATH by the installer's PATH setup).
- assert "configure_managed_node_npm_prefix()" in text
- assert 'printf \'prefix=%s\\n\' "$(dirname "$link_dir")" > "$HERMES_HOME/node/etc/npmrc"' in text
-
-
-def test_install_sh_repairs_existing_managed_node_on_rerun() -> None:
- """The redirect must run on every install (not just fresh Node installs),
- so re-running the installer repairs pre-existing managed installs whose
- Node is already up to date and would otherwise skip install_node."""
- text = INSTALL_SH.read_text()
-
- check_node_body = text.split("check_node()", 1)[1].split("\ninstall_node()", 1)[0]
- assert "configure_managed_node_npm_prefix" in check_node_body
-
- # No-op guard so it's safe to call when there is no managed Node.
- assert '[ -x "$HERMES_HOME/node/bin/npm" ] || return 0' in text
-
-
-def test_node_bootstrap_redirects_bundled_npm_global_prefix_to_link_dir() -> None:
- text = NODE_BOOTSTRAP.read_text()
-
- assert "_nb_configure_npm_prefix()" in text
- assert 'printf \'prefix=%s\\n\' "$(dirname "$_link_dir")" > "$HERMES_HOME/node/etc/npmrc"' in text
-
- # Runs at the top of ensure_node so existing managed installs are repaired
- # even when a modern Node is already present (early return path).
- ensure_node_body = text.split("ensure_node()", 1)[1]
- assert "_nb_configure_npm_prefix" in ensure_node_body
- assert '[ -x "$HERMES_HOME/node/bin/npm" ] || return 0' in text
- assert "heal_managed_node()" in text
- assert "_nb_managed_tool_broken" in text
- assert "for tool in node npm npx" in text
diff --git a/tests/scripts/install/test_install_sh_node_npm_check.py b/tests/scripts/install/test_install_sh_node_npm_check.py
deleted file mode 100644
index 2c1f84319ce..00000000000
--- a/tests/scripts/install/test_install_sh_node_npm_check.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""Regression tests for install.sh Node/npm checks (#77003).
-
-A stray `node` symlink without a sibling `npm` (leftover from a node
-version manager) made the installer report "✓ Node.js found" and then fail
-opaquely at the desktop stage. Node must only count as found when npm
-resolves on the same PATH, and npm install stages must not report success
-when the install actually failed.
-"""
-
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def test_check_node_requires_npm_alongside_node() -> None:
- """check_node must not report success when only `node` resolves.
-
- Before the fix, `command -v node` succeeding was enough — a stray node
- symlink (no sibling npm) passed the check, every later `npm install`
- failed silently, and the desktop build died with an opaque
- "Node.js / npm unavailable" (#77003).
- """
- text = INSTALL_SH.read_text()
-
- # The system-toolchain branch now gates on BOTH node and npm.
- assert (
- "if command -v node &> /dev/null && command -v npm &> /dev/null \\" in text
- )
- # The "node found but npm missing" case has its own explicit branch that
- # falls through to installing the Hermes-managed Node (which bundles npm).
- assert "node found but npm is not on PATH (stray node symlink?)" in text
-
-
-def test_check_node_managed_requires_npm() -> None:
- """The Hermes-managed Node fallback also requires its npm to exist."""
- text = INSTALL_SH.read_text()
- assert (
- '[ -x "$HERMES_HOME/node/bin/node" ] && [ -x "$HERMES_HOME/node/bin/npm" ] \\'
- in text
- )
-
diff --git a/tests/scripts/install/test_install_sh_node_prerelease.py b/tests/scripts/install/test_install_sh_node_prerelease.py
index 3f07dbb87ea..c4635014a9a 100644
--- a/tests/scripts/install/test_install_sh_node_prerelease.py
+++ b/tests/scripts/install/test_install_sh_node_prerelease.py
@@ -21,7 +21,6 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-NODE_BOOTSTRAP = REPO_ROOT / "scripts" / "lib" / "node-bootstrap.sh"
def _extract_function(text: str, name: str) -> str:
@@ -100,23 +99,6 @@ install_node
assert tried.read_text(encoding="utf-8").split() == ["26", "24"]
-def test_downloaded_tree_is_probed_before_it_replaces_anything() -> None:
- """The filename is not evidence — the extracted binary must be checked.
- Guarded as a text assertion because the surrounding block downloads; the
- fallback behaviour it feeds is covered functionally above.
- """
- text = INSTALL_SH.read_text(encoding="utf-8")
- probe = text.index('candidate_ver=$("$extracted_dir/bin/node" --version 2>/dev/null)')
- reject = text.index('if ! node_satisfies_build "$candidate_ver"; then', probe)
- # The probe has to run before the tree is moved into place, or a bad build
- # has already clobbered a working managed Node.
- assert reject < text.index('mv "$extracted_dir" "$HERMES_HOME/node"', probe)
-
-
-def test_node_bootstrap_mirrors_the_prerelease_guard() -> None:
- """The sourceable helper answers the same question and must agree."""
- text = NODE_BOOTSTRAP.read_text(encoding="utf-8")
- assert "_nb_node_is_prerelease" in text
- assert "_nb_node_is_prerelease && return 1" in text
+
diff --git a/tests/scripts/install/test_install_sh_pythonpath_sanitization.py b/tests/scripts/install/test_install_sh_pythonpath_sanitization.py
deleted file mode 100644
index 533a1da3e1c..00000000000
--- a/tests/scripts/install/test_install_sh_pythonpath_sanitization.py
+++ /dev/null
@@ -1,30 +0,0 @@
-"""Regression tests for install.sh Python environment sanitization.
-
-When install.sh is launched from another Python-driven tool session, inherited
-PYTHONPATH/PYTHONHOME can shadow the freshly installed checkout. The installer
-must sanitize those vars both during installation and at runtime launch.
-"""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def test_install_script_unsets_pythonpath_and_pythonhome_early() -> None:
- text = INSTALL_SH.read_text()
-
- # During install, inherited Python env must be sanitized before pip/venv use.
- assert 'unset PYTHONPATH' in text
- assert 'unset PYTHONHOME' in text
-
-
-def test_hermes_launcher_wrapper_clears_python_env_before_exec() -> None:
- text = INSTALL_SH.read_text()
-
- # Wrapper should clear env and forward args untouched to the venv entrypoint.
- assert 'cat > "$command_link_dir/hermes" <<EOF' in text
- assert 'unset PYTHONPATH' in text
- assert 'unset PYTHONHOME' in text
- assert 'exec "$HERMES_BIN" "\\$@"' in text
diff --git a/tests/scripts/install/test_install_sh_root_fhs_uv_python_path.py b/tests/scripts/install/test_install_sh_root_fhs_uv_python_path.py
deleted file mode 100644
index 31cb2695d09..00000000000
--- a/tests/scripts/install/test_install_sh_root_fhs_uv_python_path.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""Regression test for install.sh root-mode uv Python install path.
-
-When installing as root with the FHS layout (INSTALL_DIR=/usr/local/lib/...),
-``uv python install`` must place the managed Python under a world-readable
-location, otherwise the venv interpreter ends up at ``/root/.local/share/uv/...``
-and the shared ``/usr/local/bin/hermes`` wrapper fails for non-root users with
-"bad interpreter: Permission denied". See #21457.
-"""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def _resolve_install_layout_body() -> str:
- """Return just the body of resolve_install_layout(), bounded by its
- opening signature and the next top-level ``}`` close brace.
-
- Using the function body (not "first ``return 0`` after a marker") guards
- the tests below against future refactors that hoist the export above
- another conditional with its own early-return, or that insert an early-
- return between the marker and the export — both of which would leave the
- export unreachable while a less-strict assertion still passed.
- """
- text = INSTALL_SH.read_text(encoding="utf-8")
- head, _, rest = text.partition("resolve_install_layout() {\n")
- assert rest, "Could not find resolve_install_layout() in scripts/install.sh"
- body, _, _ = rest.partition("\n}\n")
- assert body, "Could not find resolve_install_layout() closing brace"
- return body
-
-
-def test_root_fhs_layout_exports_world_readable_uv_python_dirs() -> None:
- text = INSTALL_SH.read_text(encoding="utf-8")
-
- assert 'export UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-/usr/local/share/uv/python}"' in text
- assert 'export UV_PYTHON_BIN_DIR="${UV_PYTHON_BIN_DIR:-/usr/local/share/uv/bin}"' in text
-
-
-def test_root_fhs_uv_python_export_is_inside_root_branch() -> None:
- """The export must live in the root-FHS branch of resolve_install_layout,
- after ``ROOT_FHS_LAYOUT=true`` and before the branch's ``return 0``, so
- non-root and Termux installs are unaffected. Bound the slice by the
- function body (not "next return 0" in the whole file) so the assertion
- can't accept an unreachable export."""
- body = _resolve_install_layout_body()
-
- marker = 'ROOT_FHS_LAYOUT=true'
- assert marker in body
- after_marker = body.split(marker, 1)[1]
- return_idx = after_marker.find('return 0')
- export_idx = after_marker.find('UV_PYTHON_INSTALL_DIR')
- assert export_idx != -1, "UV_PYTHON_INSTALL_DIR export missing from root-FHS branch"
- assert return_idx != -1, "root-FHS branch must end with `return 0`"
- assert export_idx < return_idx, (
- "Export must precede the branch's `return 0` — otherwise unreachable"
- )
diff --git a/tests/scripts/install/test_install_sh_setup_wizard_tty_probe.py b/tests/scripts/install/test_install_sh_setup_wizard_tty_probe.py
deleted file mode 100644
index b36cd322eff..00000000000
--- a/tests/scripts/install/test_install_sh_setup_wizard_tty_probe.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Regression for #16746: install.sh /dev/tty gates must actually open /dev/tty.
-
-In a Docker build, ``/dev/tty`` exists as a device node (so a bare ``-e``
-existence test returns true) but opening it fails with ``ENXIO: No such
-device or address``. Under the old gates the script proceeded past the "no
-terminal available" skip and then crashed on the ``< /dev/tty`` redirect a
-few lines later, aborting the entire image build. The fix replaces every
-existence-based check that guards a subsequent ``< /dev/tty`` redirect with
-an open-based probe so the skip kicks in correctly.
-
-This module covers all three affected functions: ``run_setup_wizard()``
-(the reproducer in #16746), ``install_system_packages()`` (the apt sudo
-prompt fallback), and ``maybe_start_gateway()`` (the gateway-install gate).
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-# Every function in scripts/install.sh that previously gated on a bare
-# ``[ -e /dev/tty ]`` check before redirecting stdin from ``/dev/tty``.
-GATED_FUNCTIONS = ("run_setup_wizard", "install_system_packages", "maybe_start_gateway")
-
-
-def _extract_function_body(name: str) -> str:
- """Return the body of ``<name>()`` as a single string.
-
- Anchored to ``<name>()`` and a top-of-line ``}`` so the helper keeps
- working if neighbouring functions are renamed.
- """
- text = INSTALL_SH.read_text()
- match = re.search(
- rf"^{re.escape(name)}\(\)\s*\{{\s*\n(?P<body>.*?)^\}}",
- text,
- re.MULTILINE | re.DOTALL,
- )
- assert match is not None, f"{name}() not found in scripts/install.sh"
- return match["body"]
-
-
[email protected]("fn_name", GATED_FUNCTIONS)
-def test_tty_gate_does_not_use_existence_only_check(fn_name: str) -> None:
- """The bare ``-e`` test is the bug — no spelling of it should remain."""
- body = _extract_function_body(fn_name)
- # Cover ``[ -e /dev/tty ]``, ``[ -e "/dev/tty" ]``, ``test -e /dev/tty``
- # and friends, with arbitrary surrounding whitespace.
- pattern = re.compile(
- r"""(
- \[\s*-e\s+["']?/dev/tty["']?\s*\]
- |
- \btest\s+-e\s+["']?/dev/tty["']?
- )""",
- re.VERBOSE,
- )
- match = pattern.search(body)
- assert match is None, (
- f"{fn_name} contains an existence-only check on /dev/tty "
- f"({match.group(0)!r}). Bare `-e` tests pass in Docker builds "
- "where the device node is in the mount namespace but cannot be "
- "opened (ENXIO). Use an open-based probe (e.g. "
- "`(: </dev/tty) 2>/dev/null` or `exec 3</dev/tty`) so the skip "
- "kicks in before the function tries to read from /dev/tty. "
- "See #16746."
- )
-
-
[email protected]("fn_name", GATED_FUNCTIONS)
-def test_tty_gate_uses_open_based_probe(fn_name: str) -> None:
- """The gate must actually attempt to open ``/dev/tty``.
-
- Any ``if``/``if !``/``elif`` whose condition opens ``/dev/tty`` for
- input counts: ``(: </dev/tty)``, ``exec 3</dev/tty``,
- ``{ exec 3</dev/tty; }``, etc. Asserting the higher-level invariant
- rather than a specific spelling so equivalent refactors stay green.
- """
- body = _extract_function_body(fn_name)
- gate = re.compile(
- r"^\s*(?:if|elif)\s+!?\s*[^\n]*<\s*/dev/tty[^\n]*;\s*then",
- re.MULTILINE,
- )
- assert gate.search(body), (
- f"{fn_name} must gate on an open-based probe of /dev/tty "
- "(an `if`/`if !`/`elif` whose test redirects stdin from /dev/tty), "
- "not a mere existence check. See #16746."
- )
diff --git a/tests/scripts/install/test_install_sh_symlink_stomp.py b/tests/scripts/install/test_install_sh_symlink_stomp.py
index 21deab8f854..628c9804351 100644
--- a/tests/scripts/install/test_install_sh_symlink_stomp.py
+++ b/tests/scripts/install/test_install_sh_symlink_stomp.py
@@ -21,7 +21,6 @@ import subprocess
from pathlib import Path
-
REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
@@ -40,23 +39,6 @@ def _extract_setup_path_shim_block() -> str:
return match["block"]
-def test_setup_path_shim_block_removes_old_link_before_writing() -> None:
- """Static guard: the rm must precede the cat heredoc, not follow it."""
- block = _extract_setup_path_shim_block()
- rm_idx = block.find('rm -f "$command_link_dir/hermes"')
- cat_idx = block.find('cat > "$command_link_dir/hermes" <<EOF')
- assert rm_idx != -1, (
- "setup_path() must `rm -f` $command_link_dir/hermes before the "
- "`cat >` heredoc, otherwise an existing symlink (left by older "
- "installs) will be followed and the pip entry point overwritten. "
- "See #21454."
- )
- assert cat_idx != -1, "expected `cat >` heredoc still present"
- assert rm_idx < cat_idx, (
- "`rm -f` must come *before* the `cat >` heredoc, not after."
- )
-
-
def test_re_running_setup_path_block_preserves_pip_entry_point(tmp_path: Path) -> None:
"""Behavioral repro: simulate prior-install symlink + new-install heredoc.
diff --git a/tests/scripts/install/test_install_sh_termux_network_prereqs.py b/tests/scripts/install/test_install_sh_termux_network_prereqs.py
deleted file mode 100644
index ebd1dac4606..00000000000
--- a/tests/scripts/install/test_install_sh_termux_network_prereqs.py
+++ /dev/null
@@ -1,22 +0,0 @@
-"""Regression tests for Termux network prerequisite handling in install.sh."""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def test_termux_pkg_list_includes_network_basics() -> None:
- text = INSTALL_SH.read_text()
- assert "local termux_pkgs=(clang rust make pkg-config libffi openssl ca-certificates curl)" in text
-
-
-def test_install_script_has_connectivity_probe_and_termux_guidance() -> None:
- text = INSTALL_SH.read_text()
- assert "check_network_prerequisites()" in text
- assert "https://pypi.org/simple/" in text
- assert "https://duckduckgo.com/" in text
- assert "termux-change-repo" in text
- assert "pkg install -y ca-certificates curl && pkg update" in text
- assert "check_network_prerequisites" in text
diff --git a/tests/scripts/install/test_install_sh_uv_lock_config.py b/tests/scripts/install/test_install_sh_uv_lock_config.py
index f9f6dca1133..b04541af009 100644
--- a/tests/scripts/install/test_install_sh_uv_lock_config.py
+++ b/tests/scripts/install/test_install_sh_uv_lock_config.py
@@ -35,25 +35,6 @@ def _bash_path(path: Path) -> str:
return f"/mnt/{drive}/{tail}"
-def test_installers_keep_bootstrap_isolation_but_restore_project_config_for_lock() -> None:
- install_text = INSTALL_SCRIPTS[0].read_text(encoding="utf-8")
- setup_text = INSTALL_SCRIPTS[1].read_text(encoding="utf-8")
-
- assert "export UV_NO_CONFIG=1" in install_text
- assert "export UV_NO_CONFIG=1" in setup_text
- assert _locked_sync_helper(INSTALL_SCRIPTS[0]) == _locked_sync_helper(
- INSTALL_SCRIPTS[1]
- )
-
- helper = _locked_sync_helper(INSTALL_SCRIPTS[0])
- assert "unset UV_NO_CONFIG UV_CONFIG_FILE" in helper
- assert 'export XDG_CONFIG_HOME="$isolated_uv_config"' in helper
- assert 'export XDG_CONFIG_DIRS="$isolated_uv_config"' in helper
- assert "$UV_CMD sync --extra all --locked" in helper
- assert 'run_locked_uv_sync "$INSTALL_DIR/venv"' in install_text
- assert 'run_locked_uv_sync "$SCRIPT_DIR/venv"' in setup_text
-
-
def test_locked_sync_helper_sanitizes_only_its_subprocess(tmp_path: Path) -> None:
bash = shutil.which("bash")
if bash is None:
@@ -113,67 +94,3 @@ test "$XDG_CONFIG_DIRS" = /poison/system
]
[email protected](os.name == "nt", reason="Unix installer behavior")
-def test_real_uv_accepts_lock_when_project_config_is_restored(tmp_path: Path) -> None:
- uv = shutil.which("uv")
- if uv is None:
- pytest.skip("uv is unavailable")
-
- project = tmp_path / "project"
- project.mkdir()
- (project / "pyproject.toml").write_text(
- """[project]
-name = "installer-lock-regression"
-version = "0.1.0"
-requires-python = ">=3.11"
-
-[project.optional-dependencies]
-all = []
-
-[tool.uv]
-package = false
-exclude-newer = "14 days"
-""",
- encoding="utf-8",
- )
-
- isolated_config = tmp_path / "isolated-config"
- isolated_config.mkdir()
- clean_env = os.environ.copy()
- clean_env.pop("UV_NO_CONFIG", None)
- clean_env.pop("UV_CONFIG_FILE", None)
- clean_env["XDG_CONFIG_HOME"] = str(isolated_config)
- clean_env["XDG_CONFIG_DIRS"] = str(isolated_config)
- clean_env["UV_OFFLINE"] = "1"
-
- locked = subprocess.run(
- [uv, "lock"],
- cwd=project,
- env=clean_env,
- capture_output=True,
- text=True,
- check=False,
- )
- assert locked.returncode == 0, locked.stderr
-
- hidden_config_env = clean_env.copy()
- hidden_config_env["UV_NO_CONFIG"] = "1"
- rejected = subprocess.run(
- [uv, "lock", "--check"],
- cwd=project,
- env=hidden_config_env,
- capture_output=True,
- text=True,
- check=False,
- )
- assert rejected.returncode != 0
-
- accepted = subprocess.run(
- [uv, "lock", "--check"],
- cwd=project,
- env=clean_env,
- capture_output=True,
- text=True,
- check=False,
- )
- assert accepted.returncode == 0, accepted.stderr
diff --git a/tests/scripts/install/test_install_unmerged_index.py b/tests/scripts/install/test_install_unmerged_index.py
index cc15998de71..64bae2b5277 100644
--- a/tests/scripts/install/test_install_unmerged_index.py
+++ b/tests/scripts/install/test_install_unmerged_index.py
@@ -22,7 +22,6 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
pytestmark = pytest.mark.skipif(
shutil.which("git") is None or shutil.which("bash") is None,
@@ -127,65 +126,7 @@ def test_install_sh_clears_unmerged_index_then_stashes(tmp_path: Path) -> None:
)
-def test_install_ps1_clears_unmerged_index_before_stash() -> None:
- """install.ps1 must clear an unmerged index before stash/checkout, and do
- so *before* the stash push (order matters — the fix is a no-op otherwise)."""
- text = INSTALL_PS1.read_text()
- assert "ls-files --unmerged" in text, (
- "install.ps1 must detect an unmerged index before updating"
- )
- idx_unmerged = text.index("ls-files --unmerged")
- idx_reset = text.index("reset -q", idx_unmerged)
- idx_stash = text.index("stash push --include-untracked")
- assert idx_unmerged < idx_stash, (
- "the unmerged-index clear must run before `git stash push`"
- )
- assert idx_reset < idx_stash, "`git reset` must run before `git stash push`"
-def test_install_sh_clears_unmerged_index_before_stash_source_order() -> None:
- """Same ordering contract for install.sh's source."""
- text = INSTALL_SH.read_text()
- assert "ls-files --unmerged" in text
- idx_unmerged = text.index("ls-files --unmerged")
- idx_stash = text.index("stash push --include-untracked")
- assert idx_unmerged < idx_stash
-
-
-def test_install_ps1_stops_venv_resident_processes_before_parking_venv() -> None:
- """The Windows venv-recreate path must stop every process running out of the
- old venv before moving it aside.
-
- A gateway autostarted by a scheduled task runs as
- ``venv\\Scripts\\pythonw.exe -m hermes_cli.main gateway run`` — image name
- ``pythonw``, not ``hermes.exe`` — so the ``taskkill /IM hermes.exe`` guard
- misses it and the loaded ``.pyd`` stays locked (issues #47036/#47557/#47910).
- The recreate branch must sweep by venv path prefix before Rename-Item, and
- must never fall back to an in-place ``Remove-Item`` of the live ``venv``
- (#83149 — that path can gut site-packages with no rollback).
- """
- text = INSTALL_PS1.read_text()
-
- # The hermes.exe tree-kill is preserved (kills spawned child processes too).
- assert 'taskkill /F /T /IM hermes.exe' in text
-
- # The venv path-prefix sweep exists. It must match by case-insensitive
- # StartsWith, NOT PowerShell -like: a venv path containing wildcard
- # metacharacters ('[', ']') — legal in a Windows user name — silently fails
- # to match under -like, reintroducing the exact miss this fix closes.
- idx_recreate = text.index("Virtual environment already exists, recreating")
- idx_sweep = text.index("StartsWith($venvPrefix", idx_recreate)
- assert "[System.StringComparison]::OrdinalIgnoreCase" in text[idx_sweep:idx_sweep + 200]
- assert 'ExecutablePath -like "$venvRoot' not in text, (
- "the -like wildcard match must not be used for venv path scoping"
- )
- # The process sweep must run before the venv is parked, or it is a no-op.
- idx_park = text.index('Rename-Item -LiteralPath "venv"', idx_recreate)
- assert idx_sweep < idx_park, (
- "venv-resident processes must be stopped before Rename-Item parks the venv"
- )
- assert 'Remove-Item -Recurse -Force "venv"' not in text[idx_recreate:], (
- "must not fall back to in-place delete of the live venv (#83149)"
- )
- assert "Could not move the existing venv aside" in text[idx_recreate:]
+
diff --git a/tests/scripts/test_check_no_tmp_literals.py b/tests/scripts/test_check_no_tmp_literals.py
index e700a5e32c9..2d30b046caa 100644
--- a/tests/scripts/test_check_no_tmp_literals.py
+++ b/tests/scripts/test_check_no_tmp_literals.py
@@ -149,7 +149,3 @@ def test_baseline_entries_are_burned_down_not_grown(tmp_path, monkeypatch, capsy
assert mod.main(["--all"]) == 1 # burn-down view ignores the baseline
-def test_repo_tree_has_no_hits_outside_the_baseline():
- """What CI runs: every literal /tmp in the tree is either marked or listed in _BASELINE."""
- mod = _load()
- assert mod.main([]) == 0
diff --git a/tests/scripts/test_contributor_map.py b/tests/scripts/test_contributor_map.py
index b6082ccfe5d..ae58e3e49d8 100644
--- a/tests/scripts/test_contributor_map.py
+++ b/tests/scripts/test_contributor_map.py
@@ -32,10 +32,6 @@ def test_loader_reads_login_from_first_noncomment_line(tmp_path):
assert mapping == {"[email protected]": "janedoe"}
-
-
-
-
def test_effective_map_merges_legacy_and_directory():
# Invariant: every legacy entry survives into the effective map unless
# shadowed by a directory entry, and the directory contributes on top.
@@ -46,8 +42,6 @@ def test_effective_map_merges_legacy_and_directory():
assert release.AUTHOR_MAP[email] == login
-
-
# ── add_contributor.py CLI behavior ───────────────────────────────────
@@ -69,18 +63,12 @@ def test_add_creates_mapping_file(emails_dir):
assert "# PR #999 salvage" in path.read_text()
-
-
-
-
def test_add_refuses_login_conflicting_with_legacy_map(emails_dir):
email, login = next(iter(release.LEGACY_AUTHOR_MAP.items()))
assert add_contributor(email, login + "x") == 1
assert not (emails_dir / email).exists()
-
-
def test_add_accepts_legacy_consecutive_hyphen_login(emails_dir):
# Legacy GitHub accounts with consecutive hyphens are real (Roger--Han);
# current signup rules forbid them but existing logins remain valid.
@@ -121,43 +109,8 @@ def test_cli_entrypoint_end_to_end(tmp_path):
# ── case-insensitive filename collisions ──────────────────────────────
#
# The mapping key IS the filename, so two emails differing only in case are the
-# same file on Windows and on default macOS. When both exist, git writes one and
-# then reports the other as modified in a FRESH clone, permanently: the repo can
-# never be checked out clean on those platforms.
-#
-# The historical [email protected] / [email protected] pair
-# was removed from the tree (fcdae2cf0b), so there is no allowlist: any pair
-# is a regression. scripts/check-case-collisions.py enforces the same
-# invariant repo-wide in CI; this test keeps it visible next to the writer.
-EMAILS_DIR = REPO_ROOT / "contributors" / "emails"
-
-
-def test_no_case_insensitive_mapping_collisions():
- groups: dict[str, set[str]] = {}
- for entry in EMAILS_DIR.iterdir():
- if entry.is_file():
- groups.setdefault(entry.name.casefold(), set()).add(entry.name)
-
- collisions = {frozenset(names) for names in groups.values() if len(names) > 1}
-
- assert not collisions, (
- "contributor mappings differing only in case cannot coexist on "
- "case-insensitive filesystems (Windows, default macOS) — a fresh clone "
- f"there is permanently dirty: {sorted(sorted(c) for c in collisions)}"
- )
-
-
-def test_add_contributor_refuses_a_case_collision(tmp_path, monkeypatch):
- d = tmp_path / "emails"
- d.mkdir()
- (d / "[email protected]").write_text("someone\n")
-
- import add_contributor as mod
-
- monkeypatch.setattr(mod, "EMAILS_DIR", d)
-
- assert mod.add_contributor("[email protected]", "otherperson") == 1
- assert not (d / "[email protected]").exists()
+# same file on Windows and default macOS; add_contributor must refuse them.
+# scripts/check-case-collisions.py enforces the repo-wide invariant in CI.
def test_add_contributor_refuses_case_collision_even_for_same_login(emails_dir, capsys):
diff --git a/tests/scripts/test_footgun_subprocess_encoding.py b/tests/scripts/test_footgun_subprocess_encoding.py
index bd5f13b549a..968db8d37f6 100644
--- a/tests/scripts/test_footgun_subprocess_encoding.py
+++ b/tests/scripts/test_footgun_subprocess_encoding.py
@@ -88,8 +88,6 @@ RULE_NAME = "subprocess text=True without explicit encoding="
class TestDetection:
-
-
def test_flags_subprocess_check_output_text_true(self, linter):
line = ' out = subprocess.check_output(["git", "status"], text=True)'
assert _scan_line(linter, line, RULE_NAME)
@@ -111,12 +109,6 @@ class TestDetection:
class TestSuppression:
-
-
-
-
-
-
def test_does_not_flag_comment_only_line(self, linter):
line = ' # subprocess.run(cmd, text=True) — example'
assert not _scan_line(linter, line, RULE_NAME)
@@ -129,11 +121,6 @@ class TestSuppression:
class TestHelpers:
- def test_is_likely_subprocess_call_matches_subprocess_run(self, linter):
- assert linter._is_likely_subprocess_call("subprocess.run(cmd, text=True)")
-
-
-
def test_is_likely_subprocess_call_rejects_plain_assignment(self, linter):
assert not linter._is_likely_subprocess_call("config.text = True")
@@ -161,74 +148,4 @@ class TestHelpers:
# ---------------------------------------------------------------------------
-class TestFullRepoScan:
- def test_new_rule_find_only_known_violations(self, linter, monkeypatch):
- """Scan the full repo and assert the new rule's matches are exactly
- the set of call sites that PR #60741 fixes (or zero, if PR #60741
- is already merged into this branch).
-
- This is a regression guard: if someone adds a new
- ``subprocess.run(text=True)`` without ``encoding=``, this test
- catches it.
- """
- # The 7 call sites that PR #60741 fixes. If PR #60741 is merged
- # into this branch, this set should be empty. If not, these are
- # the expected matches.
- pr_60741_sites = {
- "hermes_cli/main.py",
- "hermes_cli/onepassword_secrets_cli.py",
- "hermes_cli/setup.py",
- "tools/transcription_tools.py",
- "tools/tts_tool.py",
- }
-
- # Run the full scan
- roots = [
- REPO_ROOT / "hermes_cli",
- REPO_ROOT / "gateway",
- REPO_ROOT / "tools",
- REPO_ROOT / "cron",
- REPO_ROOT / "agent",
- REPO_ROOT / "plugins",
- REPO_ROOT / "scripts",
- REPO_ROOT / "acp_adapter",
- REPO_ROOT / "acp_registry",
- ]
- roots = [r for r in roots if r.exists()]
-
- fg = _find_footgun(linter, RULE_NAME)
- new_rule_matches: dict[str, list[int]] = {}
-
- for path in linter.iter_files(roots):
- matches = linter.scan_file(path, [fg]) # scan with ONLY the new rule
- if matches:
- rel = path.relative_to(REPO_ROOT).as_posix()
- new_rule_matches[rel] = [m[0] for m in matches]
-
- # Determine which sites remain. PR #60741's fixes are on a separate
- # branch; if this branch doesn't include them, the 7 call sites
- # will still be flagged — that's expected, not a failure.
- if new_rule_matches:
- # Filter out the linter itself (it mentions text=True in its
- # own pattern/message, but EXCLUDED_FILES handles that for the
- # CLI entry point; the helper functions could trip it).
- new_rule_matches = {
- k: v for k, v in new_rule_matches.items()
- if k != "scripts/check-windows-footguns.py"
- }
-
- if not new_rule_matches:
- # PR #60741 already merged — clean tree. This is the goal state.
- return
-
- # Matches remain — they must be exactly the PR #60741 sites.
- matched_files = set(new_rule_matches.keys())
- unexpected = matched_files - pr_60741_sites
- if unexpected:
- pytest.fail(
- f"New footgun rule found UNEXPECTED matches in files not "
- f"covered by PR #60741: {sorted(unexpected)}.\n"
- f"These are either new regressions or call sites that need "
- f"a `# windows-footgun: ok` suppression."
- )
# All matches are the expected PR #60741 sites — OK on this branch.
diff --git a/tests/scripts/test_run_tests_parallel.py b/tests/scripts/test_run_tests_parallel.py
index 584c7c86584..b98135f2b94 100644
--- a/tests/scripts/test_run_tests_parallel.py
+++ b/tests/scripts/test_run_tests_parallel.py
@@ -349,8 +349,6 @@ def test_bare_value_flag_keeps_its_value(tmp_path: Path) -> None:
)
-
-
def test_positional_path_not_treated_as_flag(tmp_path: Path) -> None:
"""A positional path arg still overrides discovery (not routed to pytest)."""
probe_dir = _make_probe_dir(tmp_path)
@@ -417,8 +415,6 @@ def test_file_retry_self_heals_and_prints_both_attempts(tmp_path: Path) -> None:
assert "retry output" in proc.stdout
-
-
# ---------------------------------------------------------------------------
# Zero-collection is not a pass; node ids are translated, not dropped.
#
@@ -437,8 +433,6 @@ def test_zero_collected_across_run_fails_and_says_so(tmp_path: Path) -> None:
assert "NOT a pass" in proc.stdout
-
-
def test_node_id_selector_runs_the_named_test(tmp_path: Path) -> None:
"""``file.py::test_alpha`` runs that test instead of discovering nothing."""
probe_dir = _make_probe_dir(tmp_path)
@@ -500,25 +494,6 @@ def test_multiple_absolute_paths_split_on_pathsep(tmp_path: Path) -> None:
assert "Discovered 2 test files" in proc.stdout, proc.stdout
[email protected](sys.platform != "win32", reason="drive-letter paths")
-def test_drive_letter_colon_is_not_a_path_separator(tmp_path: Path) -> None:
- """An absolute ``--paths`` value stays one root on Windows.
-
- The naive split used to produce a phantom relative root ``'C'`` (the
- drive letter) alongside the real path; discovery only worked by the
- accident of ``repo_root / '\\rooted\\rest'`` re-anchoring onto the
- repo's drive.
- """
- probe_dir = _make_probe_dir(tmp_path)
- proc = _run_runner(probe_dir, "-q")
- assert proc.returncode == 0, proc.stdout
- drive = str(probe_dir)[0]
- assert f"['{drive}', " not in proc.stdout, (
- f"drive letter split off as a phantom root:\n{proc.stdout}"
- )
- assert "Discovered 1 test files" in proc.stdout, proc.stdout
-
-
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal death; Windows has no SIGSEGV exit")
def test_interpreter_crash_is_reported_as_a_crash_not_as_no_tests_ran(tmp_path: Path) -> None:
"""A file whose interpreter dies by signal is classified as CRASHED (#113186).
diff --git a/tests/scripts/test_run_tests_parallel_stdio.py b/tests/scripts/test_run_tests_parallel_stdio.py
index f1dbad30841..542c95aa38c 100644
--- a/tests/scripts/test_run_tests_parallel_stdio.py
+++ b/tests/scripts/test_run_tests_parallel_stdio.py
@@ -30,16 +30,6 @@ def _cp1252_stream() -> tuple[io.TextIOWrapper, io.BytesIO]:
return io.TextIOWrapper(raw, encoding="cp1252", errors="strict"), raw
-def test_cp1252_stream_reproduces_the_crash_without_the_fix() -> None:
- # Baseline for the bug: a strict cp1252 stream cannot take the glyph.
- stream, _raw = _cp1252_stream()
- try:
- stream.write("✓")
- except UnicodeEncodeError:
- return
- raise AssertionError("expected UnicodeEncodeError on strict cp1252")
-
-
def test_glyph_safe_stdio_survives_cp1252(monkeypatch) -> None:
mod = _load_runner()
stream, raw = _cp1252_stream()
diff --git a/tests/scripts/test_smoke_nemo_relay_shared_metrics.py b/tests/scripts/test_smoke_nemo_relay_shared_metrics.py
index d31a90bb439..4dbd4c78e8e 100644
--- a/tests/scripts/test_smoke_nemo_relay_shared_metrics.py
+++ b/tests/scripts/test_smoke_nemo_relay_shared_metrics.py
@@ -27,13 +27,6 @@ def test_resolve_hermes_executable_from_repository_venv(
assert smoke._resolve_hermes_executable(tmp_path) == executable
-def test_resolve_hermes_executable_falls_back_to_path(tmp_path, monkeypatch):
- executable = tmp_path / "bin" / "hermes"
- monkeypatch.setattr(smoke.shutil, "which", lambda _name: str(executable))
-
- assert smoke._resolve_hermes_executable(tmp_path / "repo") == executable
-
-
def test_resolve_hermes_executable_reports_missing_binary(tmp_path, monkeypatch):
monkeypatch.setattr(smoke.shutil, "which", lambda _name: None)
diff --git a/tests/scripts/test_windows_footguns_full_repo_scan.py b/tests/scripts/test_windows_footguns_full_repo_scan.py
deleted file mode 100644
index 9d14d368595..00000000000
--- a/tests/scripts/test_windows_footguns_full_repo_scan.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Full-repo self-scan wrapper for scripts/check-windows-footguns.py.
-
-scripts/check_subprocess_stdin.py has had a pytest wrapper (see
-tests/tools/test_subprocess_stdin_guard.py's test_all_tui_subprocess_calls_
-have_stdin) that runs the checker with its default full-scan behavior and
-asserts a clean exit — so a normal pytest run of that file catches
-regressions even when no one remembers to run the standalone script by hand.
-check-windows-footguns.py had no equivalent: only a narrow rule-level test
-(tests/scripts/test_footgun_subprocess_encoding.py, scoped to the
-text=True/encoding= rule) existed, so a bare ``os.killpg``/``signal.SIGKILL``
-regression (caught by CI running the real script with --all, not by any
-local pytest run) shipped in the T1-T3 npx-agent-browser hardening commit
-before anyone ran the script directly. This closes that gap the same way
-the stdin guard already closes its equivalent one.
-"""
-
-from __future__ import annotations
-
-import subprocess
-import sys
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-SCRIPT = REPO_ROOT / "scripts" / "check-windows-footguns.py"
-
-
-def test_full_repo_scan_has_no_unsuppressed_windows_footguns():
- """Mirrors check_subprocess_stdin.py's wrapper: run the real checker
- against the whole repo (--all) and require a clean exit, so this test
- file — not just institutional memory — is what catches the next
- bare os.killpg/signal.SIGKILL-style regression."""
- result = subprocess.run(
- [sys.executable, str(SCRIPT), "--all"],
- capture_output=True,
- text=True,
- timeout=60,
- stdin=subprocess.DEVNULL,
- )
- assert result.returncode == 0, (
- f"Windows footgun check failed:\n{result.stdout}\n{result.stderr}"
- )
diff --git a/tests/secret_sources/test_error_remediation.py b/tests/secret_sources/test_error_remediation.py
index 852c65bd746..a7dcd9105e8 100644
--- a/tests/secret_sources/test_error_remediation.py
+++ b/tests/secret_sources/test_error_remediation.py
@@ -6,17 +6,12 @@ identity reject, the bws stderr summarizer, the per-source
"""
from __future__ import annotations
-from pathlib import Path
-from unittest import mock
-import pytest
from agent.secret_sources import bitwarden as bw
-from agent.secret_sources import onepassword as op
from agent.secret_sources.base import ErrorKind, FetchResult, SecretSource
from agent.secret_sources.bitwarden import (
BitwardenSource,
- _classify_bws_error,
_summarize_bws_stderr,
)
from agent.secret_sources.onepassword import OnePasswordSource
@@ -80,7 +75,6 @@ def test_fetch_auth_failure_gets_friendly_error(monkeypatch, tmp_path):
monkeypatch.setattr(bw, "fetch_bitwarden_secrets", boom)
result = src.fetch({"enabled": True, "project_id": "p"}, tmp_path)
assert result.error_kind == ErrorKind.AUTH_FAILED
- assert "revoked, expired" in result.error
assert "BWS_ACCESS_TOKEN" in result.error
assert "invalid_client" in result.error # mechanics preserved
@@ -92,10 +86,6 @@ def test_fetch_auth_failure_gets_friendly_error(monkeypatch, tmp_path):
-def test_onepassword_auth_remediation_points_at_token_command():
- hint = OnePasswordSource().remediation(ErrorKind.AUTH_FAILED, {})
- assert "hermes secrets onepassword token" in hint
- assert "OP_SERVICE_ACCOUNT_TOKEN" in hint
@@ -145,8 +135,10 @@ def test_env_loader_prints_remediation_hint(tmp_path, monkeypatch, capsys):
env_loader.reset_secret_source_cache()
err = capsys.readouterr().err
- assert "rejected the machine-account access token" in err
- assert "hermes secrets bitwarden token" in err
+ expected = BitwardenSource().remediation(
+ ErrorKind.AUTH_FAILED, {"enabled": True, "project_id": "proj"}
+ ).strip()
+ assert expected and expected in err
def test_remediation_hint_uses_explicit_profile_scope(tmp_path, monkeypatch):
diff --git a/tests/secret_sources/test_profile_secrets.py b/tests/secret_sources/test_profile_secrets.py
index c1ab88d28fc..a825dabd479 100644
--- a/tests/secret_sources/test_profile_secrets.py
+++ b/tests/secret_sources/test_profile_secrets.py
@@ -18,7 +18,7 @@ from pathlib import Path
import pytest
from agent.secret_sources import registry
-from agent.secret_sources.base import ErrorKind, FetchResult, SecretSource
+from agent.secret_sources.base import FetchResult, SecretSource
class _FakeBulk(SecretSource):
@@ -101,8 +101,6 @@ def test_profile_suffixed_var_hydrates_canonical():
assert env["TELEGRAM_BOT_TOKEN_MILLA"] == "123:tok"
assert env["TELEGRAM_BOT_TOKEN"] == "123:tok"
assert "TELEGRAM_BOT_TOKEN" in report.provenance
- assert any("applied profile-scoped" in w
- for w in report.sources[0].result.warnings)
diff --git a/tests/skills/test_actual_setup_skill.py b/tests/skills/test_actual_setup_skill.py
deleted file mode 100644
index f2a110e418d..00000000000
--- a/tests/skills/test_actual_setup_skill.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""
-Smoke tests for the actual-setup optional skill.
-
-Validates:
- - SKILL.md frontmatter conforms to the ≤60-char description standard
- - Frontmatter has required fields
- - The skill references the first-class ``actual`` provider (not the
- legacy custom-provider config path that conflicts with it)
- - The bundled OpenCode reference exists
-"""
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-import yaml
-
-SKILL_DIR = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "devops"
- / "actual-setup"
-)
-
-
[email protected](scope="module")
-def skill_source() -> str:
- return (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
-
-
[email protected](scope="module")
-def frontmatter(skill_source) -> dict:
- m = re.search(r"^---\n(.*?)\n---", skill_source, re.DOTALL)
- assert m, "SKILL.md missing YAML frontmatter"
- return yaml.safe_load(m.group(1))
-
-
-def test_skill_dir_exists() -> None:
- assert SKILL_DIR.is_dir(), f"missing skill dir: {SKILL_DIR}"
-
-
-def test_description_under_60_chars(frontmatter) -> None:
- desc = frontmatter["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars (limit ≤60): {desc!r}"
-
-
-def test_has_required_frontmatter_fields(frontmatter) -> None:
- for field in ("name", "description", "version", "license"):
- assert field in frontmatter, f"missing required field: {field}"
-
-
-def test_credits_contributor(frontmatter) -> None:
- assert "shl0ms" in str(frontmatter.get("author", "")), (
- "author must credit the human contributor first"
- )
-
-
-def test_uses_first_class_provider_not_custom_provider(skill_source) -> None:
- # The legacy setup configured Actual as providers.actual.* custom entries,
- # which now collides with the built-in provider of the same name.
- assert "--provider actual" in skill_source
- assert "hermes config set providers.actual.api " not in skill_source
- assert "key_env" not in skill_source
-
-
-def test_opencode_reference_exists() -> None:
- assert (SKILL_DIR / "references" / "opencode.md").is_file()
diff --git a/tests/skills/test_agent_merge_conflict_arbiter_skill.py b/tests/skills/test_agent_merge_conflict_arbiter_skill.py
deleted file mode 100644
index 7a648cef666..00000000000
--- a/tests/skills/test_agent_merge_conflict_arbiter_skill.py
+++ /dev/null
@@ -1,102 +0,0 @@
-"""Contract checks for the optional agent-merge-conflict-arbiter skill asset.
-
-Reads only the SKILL.md markdown asset — no .py source reads, no network.
-"""
-import re
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-SKILL_PATH = (
- REPO_ROOT
- / "optional-skills"
- / "autonomous-ai-agents"
- / "agent-merge-conflict-arbiter"
- / "SKILL.md"
-)
-
-REQUIRED_SECTIONS = [
- "## When to Use",
- "## Prerequisites",
- "## How to Run",
- "## Quick Reference",
- "## Procedure",
- "## Pitfalls",
- "## Verification",
-]
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---"), "SKILL.md must open with frontmatter"
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm_text = content[3 : m.start() + 3]
- body = content[m.end() + 3 :]
- fm = {}
- for line in fm_text.splitlines():
- km = re.match(r"^(\w[\w-]*):\s*(.*)$", line)
- if km:
- fm[km.group(1)] = km.group(2).strip().strip('"')
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "agent-merge-conflict-arbiter"
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith("."), "description must end with a period"
- assert desc.count(".") == 1, "description must be one sentence"
-
-
-def test_required_sections_present_in_order():
- _, body = _frontmatter_and_body()
- positions = []
- for section in REQUIRED_SECTIONS:
- idx = body.find(section)
- assert idx != -1, f"missing section: {section}"
- positions.append(idx)
- assert positions == sorted(positions), "sections out of required order"
-
-
-def test_body_size_within_bundled_norms():
- content = SKILL_PATH.read_text(encoding="utf-8")
- lines = content.count("\n") + 1
- assert 80 <= lines <= 260, f"SKILL.md is {lines} lines; expected ~100-200"
-
-
-def test_references_native_hermes_tools():
- _, body = _frontmatter_and_body()
- for tool in ("`terminal`", "`read_file`", "`patch`", "`delegate_task`"):
- assert tool in body, f"body must reference native tool {tool}"
-
-
-def test_classification_taxonomy_present():
- _, body = _frontmatter_and_body()
- for cls in (
- "disjoint-intent",
- "same-question-different-answer",
- "superseded",
- ):
- assert cls in body, f"missing hunk class: {cls}"
-
-
-def test_impartiality_contract_stated():
- _, body = _frontmatter_and_body()
- assert "never favor" in body.lower()
- assert "drive-by" in body.lower()
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
diff --git a/tests/skills/test_auteur_skill.py b/tests/skills/test_auteur_skill.py
deleted file mode 100644
index 0ad596c2a38..00000000000
--- a/tests/skills/test_auteur_skill.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""Tests for the auteur optional skill (ported from agiwhitelist/auteur, MIT).
-
-Frontmatter shape, description length and related_skills resolution are
-covered repo-wide by tests/skills/test_authoring_standards.py; this file only
-holds the two invariants specific to the port.
-"""
-import re
-from pathlib import Path
-
-SKILL_DIR = Path(__file__).resolve().parents[2] / "optional-skills" / "creative" / "auteur"
-SKILL_MD = SKILL_DIR / "SKILL.md"
-
-
-def test_mentioned_paths_exist_or_annotated():
- """Every references/scripts/templates path mentioned in SKILL.md exists on
- disk, or its line carries an 'upstream' / 'not vendored' annotation (the
- port deliberately drops upstream's README gallery and CLI assets)."""
- pattern = re.compile(r"(references|scripts|templates)/[A-Za-z0-9._-]+")
- missing = []
- for line in SKILL_MD.read_text(encoding="utf-8").splitlines():
- for m in pattern.finditer(line):
- rel = m.group(0).rstrip(".")
- if (SKILL_DIR / rel).exists():
- continue
- low = line.lower()
- if "upstream" in low or "not vendored" in low:
- continue
- missing.append(rel)
- assert not missing, f"paths mentioned but absent and unannotated: {missing}"
-
-
-def test_no_upstream_harness_residue():
- """Upstream ships as a plugin for another agent harness; its plugin-only
- frontmatter keys and harness name must not leak into the Hermes port."""
- text = SKILL_MD.read_text(encoding="utf-8").lower()
- for token in ("claude", "allowed-tools", "argument-hint"):
- assert token not in text, f"residual '{token}' in SKILL.md"
diff --git a/tests/skills/test_authoring_standards.py b/tests/skills/test_authoring_standards.py
index 40bd10cbc79..86d1ade1004 100644
--- a/tests/skills/test_authoring_standards.py
+++ b/tests/skills/test_authoring_standards.py
@@ -177,7 +177,3 @@ def test_shell_snippets_paste_safe(p):
)
-def test_grandfather_entries_still_needed():
- """A grandfather entry whose violation is fixed must be removed."""
- for rel in GRANDFATHER:
- assert (REPO / rel / "SKILL.md").exists(), f"stale grandfather entry: {rel}"
diff --git a/tests/skills/test_box_skill.py b/tests/skills/test_box_skill.py
deleted file mode 100644
index 8239a72704e..00000000000
--- a/tests/skills/test_box_skill.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""Durable integration contracts for the bundled Box productivity skill."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-from urllib.parse import unquote
-
-import pytest
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-SKILL_DIR = REPO_ROOT / "skills" / "productivity" / "box"
-SKILL_MD = SKILL_DIR / "SKILL.md"
-
-
-def _parse_frontmatter(content: str) -> dict:
- from agent.skill_utils import parse_frontmatter
-
- frontmatter, _ = parse_frontmatter(content)
- return frontmatter
-
-
-def _local_markdown_targets(path: Path) -> set[Path]:
- targets: set[Path] = set()
- for raw_target in re.findall(r"\[[^]]+\]\(([^)]+)\)", path.read_text(encoding="utf-8")):
- target = raw_target.split("#", maxsplit=1)[0].strip("<>")
- if not target or "://" in target or target.startswith("mailto:"):
- continue
- targets.add((path.parent / unquote(target)).resolve())
- return targets
-
-
[email protected](scope="module")
-def skill_text() -> str:
- return SKILL_MD.read_text(encoding="utf-8")
-
-
[email protected](scope="module")
-def frontmatter(skill_text: str) -> dict:
- return _parse_frontmatter(skill_text)
-
-
-def test_skill_frontmatter_is_valid_and_discoverable(frontmatter: dict):
- assert frontmatter.get("name") == "box"
- description = frontmatter.get("description")
- assert isinstance(description, str) and description.strip()
- assert len(description) <= 60
- assert description.endswith(".")
- assert frontmatter.get("license") == "MIT"
- assert "Chris Kim" in str(frontmatter.get("author"))
- assert "iskysun96" in str(frontmatter.get("author"))
-
- platforms = frontmatter.get("platforms")
- assert isinstance(platforms, list)
- assert {"linux", "macos", "windows"}.issubset(platforms)
-
-
-def test_box_command_is_declared_without_universal_credential_gate(frontmatter: dict):
- prerequisites = frontmatter.get("prerequisites") or {}
- assert "box" in prerequisites.get("commands", [])
- assert not prerequisites.get("env_vars")
-
-def test_all_local_links_resolve_inside_the_skill():
- markdown_files = list(SKILL_DIR.rglob("*.md"))
- for source in markdown_files:
- for target in _local_markdown_targets(source):
- assert target.is_file(), f"broken link in {source.relative_to(SKILL_DIR)}: {target}"
- assert target.is_relative_to(SKILL_DIR.resolve()), (
- f"local link in {source.relative_to(SKILL_DIR)} escapes the skill: {target}"
- )
-
-
-def test_every_reference_is_reachable_from_skill_entrypoint():
- entrypoint_targets = _local_markdown_targets(SKILL_MD)
- reference_files = set((SKILL_DIR / "references").glob("*.md"))
- assert reference_files <= entrypoint_targets
diff --git a/tests/skills/test_comfyui_skill.py b/tests/skills/test_comfyui_skill.py
index 7141ee92345..d900347d6f8 100644
--- a/tests/skills/test_comfyui_skill.py
+++ b/tests/skills/test_comfyui_skill.py
@@ -13,7 +13,6 @@ import sys
import textwrap
from pathlib import Path
-import pytest
REPO = Path(__file__).resolve().parent.parent.parent
SCRIPTS = REPO / "optional-skills" / "creative" / "comfyui" / "scripts"
@@ -38,11 +37,6 @@ _ENCODING_SENSITIVE_READS = [
]
[email protected]("rel_path,expected", _ENCODING_SENSITIVE_READS)
-def test_readers_are_locale_independent(rel_path, expected):
- """Every text read of a user-supplied or system file pins its codec."""
- source = (SCRIPTS / rel_path).read_text(encoding="utf-8")
- assert expected in source, f"{rel_path}: locale-dependent read of a UTF-8 payload"
def _run_under_c_locale(snippet: str) -> subprocess.CompletedProcess:
diff --git a/tests/skills/test_competitor_news_monitor_skill.py b/tests/skills/test_competitor_news_monitor_skill.py
deleted file mode 100644
index 101851e2e6c..00000000000
--- a/tests/skills/test_competitor_news_monitor_skill.py
+++ /dev/null
@@ -1,111 +0,0 @@
-"""Tests for the competitor-news-monitor skill and competitor-watch blueprint."""
-import re
-from pathlib import Path
-
-import yaml
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-SKILL_PATH = (
- REPO_ROOT / "skills" / "research" / "competitor-news-monitor" / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "competitor-news-monitor"
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent")
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(REPO_ROOT.glob(f"skills/*/{name}/SKILL.md"))
- + list(REPO_ROOT.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(REPO_ROOT.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_no_phantom_skill_references():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "change-monitor-and-notify" not in content, "phantom skill ref must be gone"
-
-
-def test_setup_tick_split():
- _, body = _frontmatter_and_body()
- assert "Setup (foreground, once)" in body
- assert "Tick (each scheduled run)" in body
- assert "cronjob(action=" in body, "must wire scheduling through the cronjob tool"
-
-
-def test_coverage_honesty_discipline():
- _, body = _frontmatter_and_body()
- assert "unknown coverage" in body, "source failure != no news"
- assert "cutoff advance" in body.replace("advances", "advance").replace(
- "advanced", "advance"
- ), "cutoff must only advance on success"
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 5
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
-
-
-def test_competitor_watch_blueprint_registered():
- from cron.blueprint_catalog import CATALOG
-
- bp = next((b for b in CATALOG if b.key == "competitor-watch"), None)
- assert bp is not None, "competitor-watch blueprint missing from catalog"
- assert "competitor-news-monitor" in bp.skills
- slot_names = {s.name for s in bp.slots}
- assert {"companies", "categories", "time", "recurrence", "deliver"} <= slot_names
- assert "[SILENT]" in bp.prompt_template
- assert "{companies}" in bp.prompt_template and "{categories}" in bp.prompt_template
-
-
-def test_every_blueprint_skill_resolves_in_repo():
- from cron.blueprint_catalog import CATALOG
-
- for bp in CATALOG:
- for skill_name in bp.skills:
- hits = list(REPO_ROOT.glob(f"skills/*/{skill_name}/SKILL.md")) + list(
- REPO_ROOT.glob(f"skills/*/*/{skill_name}/SKILL.md")
- )
- assert hits, f"blueprint {bp.key!r} loads nonexistent skill {skill_name!r}"
diff --git a/tests/skills/test_darwinian_evolver_skill.py b/tests/skills/test_darwinian_evolver_skill.py
deleted file mode 100644
index 14a447ffef6..00000000000
--- a/tests/skills/test_darwinian_evolver_skill.py
+++ /dev/null
@@ -1,81 +0,0 @@
-"""
-Smoke tests for the darwinian-evolver optional skill.
-
-We can't actually run the evolution loop in CI (it needs network + a paid LLM),
-so these tests verify:
- - SKILL.md frontmatter conforms to the hardline format
- - shipped scripts parse as valid Python
- - the scripts reference the right env var / module paths
-"""
-from __future__ import annotations
-
-import ast
-import re
-from pathlib import Path
-
-import pytest
-import yaml
-
-SKILL_DIR = Path(__file__).resolve().parents[2] / "optional-skills" / "research" / "darwinian-evolver"
-
-
[email protected](scope="module")
-def frontmatter() -> dict:
- src = (SKILL_DIR / "SKILL.md").read_text()
- m = re.search(r"^---\n(.*?)\n---", src, re.DOTALL)
- assert m, "SKILL.md missing YAML frontmatter"
- return yaml.safe_load(m.group(1))
-
-
-def test_skill_dir_exists() -> None:
- assert SKILL_DIR.is_dir(), f"missing skill dir: {SKILL_DIR}"
-
-
-
-
-def test_description_under_60_chars(frontmatter) -> None:
- desc = frontmatter["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars (hardline ≤60): {desc!r}"
-
-
-
-
-def test_platforms_excludes_windows(frontmatter) -> None:
- # Upstream uses func_timeout (POSIX signals) and uv subprocess pipelines; the
- # skill is gated [linux, macos]. If we ever port to Windows, update this test
- # to assert ["linux", "macos", "windows"].
- assert "windows" not in frontmatter["platforms"]
- assert set(frontmatter["platforms"]) >= {"linux", "macos"}
-
-
-def test_author_credits_contributor(frontmatter) -> None:
- author = frontmatter["author"]
- assert "Bihruze" in author, f"author should credit the original contributor: {author!r}"
-
-
-
-
- "path",
- [
- "scripts/parrot_openrouter.py",
- "scripts/show_snapshot.py",
- "templates/custom_problem_template.py",
- ],
-)
-def test_shipped_scripts_parse(path: str) -> None:
- src = (SKILL_DIR / path).read_text()
- ast.parse(src) # raises SyntaxError on broken Python
-
-
-def test_parrot_script_uses_openrouter() -> None:
- src = (SKILL_DIR / "scripts" / "parrot_openrouter.py").read_text()
- assert "OPENROUTER_API_KEY" in src, "parrot driver should read OPENROUTER_API_KEY"
- assert "openrouter.ai/api/v1" in src, "parrot driver should target OpenRouter"
- assert "EVOLVER_MODEL" in src, "model should be overridable via EVOLVER_MODEL"
-
-
-
-
-
-
diff --git a/tests/skills/test_decision_questionnaire_skill.py b/tests/skills/test_decision_questionnaire_skill.py
deleted file mode 100644
index 94a11bd5f29..00000000000
--- a/tests/skills/test_decision_questionnaire_skill.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""Tests for optional-skills/productivity/decision-questionnaire."""
-
-import re
-from pathlib import Path
-
-import pytest
-import yaml
-
-SKILL_MD = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "productivity"
- / "decision-questionnaire"
- / "SKILL.md"
-)
-
-
-def _frontmatter():
- text = SKILL_MD.read_text(encoding="utf-8")
- m = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)
- assert m, "SKILL.md missing YAML frontmatter"
- return yaml.safe_load(m.group(1))
-
-
-class TestFrontmatter:
- def test_name_matches_directory(self):
- assert _frontmatter()["name"] == "decision-questionnaire"
-
- def test_description_length_and_period(self):
- desc = _frontmatter()["description"]
- assert len(desc) <= 60
- assert desc.endswith(".")
-
- def test_license_and_platforms(self):
- fm = _frontmatter()
- assert fm["license"] == "MIT"
- assert set(fm["platforms"]) == {"linux", "macos", "windows"}
-
-
-class TestBody:
- def _body(self):
- return SKILL_MD.read_text(encoding="utf-8")
-
- def test_template_sections_present(self):
- body = self._body()
- for section in ("## Context", "## How to answer", "## Anything else?"):
- assert section in body, f"template missing {section}"
-
- def test_output_filename_convention(self):
- assert "decision-questionnaire-<slug>.md" in self._body()
-
- def test_interview_the_send_principle(self):
- assert "Interview the Send" in self._body()
-
- def test_no_upstream_harness_residue(self):
- lower = self._body().lower()
- for token in ("claude", "slash command", "disable-model-invocation"):
- assert token not in lower, f"upstream residue: {token}"
-
-
-if __name__ == "__main__":
- raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/skills/test_document_to_action_items_skill.py b/tests/skills/test_document_to_action_items_skill.py
deleted file mode 100644
index 376b732e872..00000000000
--- a/tests/skills/test_document_to_action_items_skill.py
+++ /dev/null
@@ -1,81 +0,0 @@
-"""Tests for the document-to-action-items optional skill."""
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_PATH = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "productivity"
- / "document-to-action-items"
- / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "document-to-action-items"
- hermes = fm["metadata"]["hermes"]
- assert hermes["tags"]
- assert "related_skills" in hermes
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent"), "human contributor must be credited first"
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = list(repo_root.glob(f"skills/*/{name}/SKILL.md")) + list(
- repo_root.glob(f"optional-skills/*/{name}/SKILL.md")
- ) + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_body_structure_and_size():
- _, body = _frontmatter_and_body()
- for section in ("## When to Use", "## Procedure", "## Pitfalls", "## Verification"):
- assert section in body, f"missing section: {section}"
- assert len(SKILL_PATH.read_text(encoding="utf-8")) <= 100_000
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
- assert not re.search(r"[A-Z]:\\\\Users", content)
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 5
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
diff --git a/tests/skills/test_email_inbox_triage_skill.py b/tests/skills/test_email_inbox_triage_skill.py
deleted file mode 100644
index d86761d7524..00000000000
--- a/tests/skills/test_email_inbox_triage_skill.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""Tests for the email-inbox-triage bundled skill."""
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_PATH = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "email"
- / "email-inbox-triage"
- / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "email-inbox-triage"
- hermes = fm["metadata"]["hermes"]
- assert hermes["tags"]
- assert "related_skills" in hermes
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent"), "human contributor must be credited first"
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(repo_root.glob(f"skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_body_structure_and_size():
- _, body = _frontmatter_and_body()
- for section in ("## When to Use", "## Procedure", "## Pitfalls", "## Verification"):
- assert section in body, f"missing section: {section}"
- assert len(SKILL_PATH.read_text(encoding="utf-8")) <= 100_000
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
- assert not re.search(r"[A-Z]:\\\\Users", content)
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 5
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
-
-
-def test_mutation_boundary_is_default_safe():
- _, body = _frontmatter_and_body()
- assert "read + draft" in body, "scope step must default to read+draft, not send/delete"
- assert "does not imply permission" in body
-
-
-def test_voice_calibration_is_evidence_based():
- """Drafting must calibrate against the user's own sent replies,
- with an explicit fallback when the Sent folder is unavailable."""
- _, body = _frontmatter_and_body()
- assert "Calibrate the user's voice" in body
- assert "sent replies" in body.lower()
- assert "fall back to matching the incoming thread's register" in body
- assert "generic-professional" in body
diff --git a/tests/skills/test_evidence_store.py b/tests/skills/test_evidence_store.py
index 7d6cadc32f6..6b3c28b4b88 100644
--- a/tests/skills/test_evidence_store.py
+++ b/tests/skills/test_evidence_store.py
@@ -12,14 +12,6 @@ spec.loader.exec_module(evidence_store)
EvidenceStore = evidence_store.EvidenceStore
-def test_evidence_store_init(tmp_path):
- store_file = tmp_path / "test_evidence.json"
- store = EvidenceStore(str(store_file))
- assert store.filepath == str(store_file)
- assert len(store.data["evidence"]) == 0
- assert "metadata" in store.data
- assert store.data["metadata"]["version"] == "2.0"
- assert "chain_of_custody" in store.data
def test_evidence_store_add(tmp_path):
diff --git a/tests/skills/test_fetch_transcript.py b/tests/skills/test_fetch_transcript.py
index b114a4e5de2..bb5e7286aca 100644
--- a/tests/skills/test_fetch_transcript.py
+++ b/tests/skills/test_fetch_transcript.py
@@ -2,9 +2,7 @@
import sys
from pathlib import Path
-from unittest import mock
-import pytest
SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "skills" / "media" / "youtube-content" / "scripts"
sys.path.insert(0, str(SCRIPTS_DIR))
@@ -42,15 +40,4 @@ class TestFormatTimestamp:
-class TestPyprojectDeclaresYoutubeExtra:
- def test_youtube_extra_declared_in_pyproject(self):
- """youtube-transcript-api must be listed in pyproject.toml [youtube] extra (issue #22243)."""
- import tomllib
- pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
- with pyproject_path.open("rb") as f:
- data = tomllib.load(f)
- extras = data.get("project", {}).get("optional-dependencies", {})
- assert "youtube" in extras, "Missing [youtube] extra in pyproject.toml"
- youtube_deps = " ".join(extras["youtube"])
- assert "youtube-transcript-api" in youtube_deps
diff --git a/tests/skills/test_github_credential_token.py b/tests/skills/test_github_credential_token.py
index 1944aba17fb..29062137a45 100644
--- a/tests/skills/test_github_credential_token.py
+++ b/tests/skills/test_github_credential_token.py
@@ -9,13 +9,6 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
HELPER = REPO_ROOT / "skills/software-development/github/scripts/git-credential-token.py"
-LEGACY_SED = r"sed 's|https://[^:]*:\([^@]*\)@.*|\1|'"
-SHIPPED_TREES = (
- REPO_ROOT / "skills/software-development/github",
- REPO_ROOT / "website/docs/user-guide/skills/bundled/software-development",
- REPO_ROOT
- / "website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/skills/bundled/software-development",
-)
def _extract(path: Path) -> subprocess.CompletedProcess[str]:
@@ -89,13 +82,3 @@ def test_rejects_ambiguous_lookalike_or_malformed_credentials(tmp_path, credenti
assert result.returncode == 1
assert result.stdout == ""
assert result.stderr == ""
-
-
-def test_bundled_github_skills_and_docs_do_not_ship_legacy_sed_url_regex():
- offenders = []
- for tree in SHIPPED_TREES:
- for path in tree.rglob("*"):
- if path.suffix in {".md", ".sh", ".py"} and LEGACY_SED in path.read_text(encoding="utf-8"):
- offenders.append(str(path.relative_to(REPO_ROOT)))
-
- assert offenders == []
diff --git a/tests/skills/test_github_skill.py b/tests/skills/test_github_skill.py
deleted file mode 100644
index 8beba787e60..00000000000
--- a/tests/skills/test_github_skill.py
+++ /dev/null
@@ -1,130 +0,0 @@
-"""Tests for the github merged skill (formerly six github-* skills).
-
-The issue-to-pr workflow (originally the github-issue-to-pr skill,
-author benbarclay) now lives complete in references/issue-to-pr.md of the
-merged software-development/github skill. Frontmatter contracts apply to
-the merged SKILL.md; the content pins that guarded the issue-to-pr
-disciplines now check the reference body.
-"""
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_DIR = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "software-development"
- / "github"
-)
-SKILL_PATH = SKILL_DIR / "SKILL.md"
-ISSUE_TO_PR_REF = SKILL_DIR / "references" / "issue-to-pr.md"
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_all_workflow_references_exist():
- for ref in (
- "auth.md",
- "issues.md",
- "pr-workflow.md",
- "issue-to-pr.md",
- "code-review.md",
- "repo-management.md",
- ):
- assert (SKILL_DIR / "references" / ref).is_file(), f"missing reference: {ref}"
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "github"
- hermes = fm["metadata"]["hermes"]
- assert hermes["tags"]
- assert "related_skills" in hermes
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent"), "human contributor must be credited first"
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(repo_root.glob(f"skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_body_routes_every_workflow():
- _, body = _frontmatter_and_body()
- for ref in (
- "references/auth.md",
- "references/issues.md",
- "references/pr-workflow.md",
- "references/issue-to-pr.md",
- "references/code-review.md",
- "references/repo-management.md",
- ):
- assert ref in body, f"routing table missing: {ref}"
- assert len(SKILL_PATH.read_text(encoding="utf-8")) <= 100_000
-
-
-def test_no_machine_local_paths():
- for p in (SKILL_PATH, ISSUE_TO_PR_REF):
- content = p.read_text(encoding="utf-8")
- assert "/home/" not in content
- assert not re.search(r"[A-Z]:\\\\Users", content)
-
-
-def test_issue_to_pr_steps_have_completion_criteria():
- body = ISSUE_TO_PR_REF.read_text(encoding="utf-8")
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## |\Z)", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 6
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
-
-
-def test_issue_to_pr_core_disciplines_present():
- """The learnings folded in from maintainer practice must survive edits."""
- body = ISSUE_TO_PR_REF.read_text(encoding="utf-8")
- assert "--comments" in body, "must read the full issue thread"
- assert "pr list --search" in body, "must sweep for duplicate PRs before coding"
- assert re.search(r"git log -p -S", body), "must check design intent via history"
- assert "sabotage" in body.lower() or "FAILS" in body, "must prove the regression test bites"
- assert "sibling" in body, "must fix the class, not the site"
- assert "dispatches CI" in body, "must open the PR immediately after work exists"
-
-
-def test_issue_to_pr_not_a_router():
- """Reference steps must carry their own procedure, not route elsewhere."""
- body = ISSUE_TO_PR_REF.read_text(encoding="utf-8")
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## |\Z)", body, re.MULTILINE | re.DOTALL)
- routing = [s for s in steps if re.match(r"^### \d+\.[^\n]*\n+Load `", s)]
- assert len(routing) == 0, "steps must not open by delegating to another skill"
diff --git a/tests/skills/test_google_workspace_credential_files.py b/tests/skills/test_google_workspace_credential_files.py
index 9138c08fa45..250110013da 100644
--- a/tests/skills/test_google_workspace_credential_files.py
+++ b/tests/skills/test_google_workspace_credential_files.py
@@ -28,19 +28,6 @@ def _parse_frontmatter(content: str) -> dict:
class TestGoogleWorkspaceCredentialFiles:
- def test_required_credential_files_present_in_skill_md(self):
- content = SKILL_MD.read_text(encoding="utf-8")
- fm = _parse_frontmatter(content)
- entries = fm.get("required_credential_files")
- assert entries, "required_credential_files missing from google-workspace SKILL.md"
- assert isinstance(entries, list), "required_credential_files must be a list"
- paths = {
- (e["path"] if isinstance(e, dict) else e)
- for e in entries
- }
- assert _EXPECTED_PATHS <= paths, (
- f"Missing entries in required_credential_files: {_EXPECTED_PATHS - paths}"
- )
def test_entries_are_registered_when_files_exist(self, tmp_path):
hermes_home = tmp_path / ".hermes"
diff --git a/tests/skills/test_google_workspace_daily_brief_reference.py b/tests/skills/test_google_workspace_daily_brief_reference.py
deleted file mode 100644
index f7302f3dd06..00000000000
--- a/tests/skills/test_google_workspace_daily_brief_reference.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""Tests for the google-workspace daily-brief reference."""
-import re
-from pathlib import Path
-
-GWS_DIR = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "productivity"
- / "google-workspace"
-)
-REF_PATH = GWS_DIR / "references" / "daily-brief.md"
-SKILL_PATH = GWS_DIR / "SKILL.md"
-
-
-def test_reference_exists():
- assert REF_PATH.is_file()
-
-
-def test_skill_md_points_at_reference():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "references/daily-brief.md" in content, "SKILL.md must list the reference"
- refs_section = content.split("## References", 1)[1].split("##", 1)[0]
- assert "daily-brief" in refs_section
-
-
-def test_reference_carries_load_trigger():
- content = REF_PATH.read_text(encoding="utf-8")
- assert "morning brief" in content.lower(), "reference must state when to load it"
-
-
-def test_reference_credits_contributor():
- content = REF_PATH.read_text(encoding="utf-8")
- assert "benbarclay" in content
-
-
-def test_steps_have_completion_criteria():
- content = REF_PATH.read_text(encoding="utf-8")
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", content, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 5
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
-
-
-def test_core_disciplines_present():
- content = REF_PATH.read_text(encoding="utf-8")
- assert "half-open window" in content or "[day_start, next_day_start)" in content
- assert "no preparation found" in content
- assert "not authorization to mutate" in content
-
-
-def test_no_machine_local_paths():
- content = REF_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
-
-
-def test_no_standalone_daily_brief_skill():
- """The brief ships as a reference, not a sibling skill."""
- repo_root = GWS_DIR.parents[2]
- assert not (repo_root / "skills" / "productivity" / "google-workspace-daily-brief").exists()
diff --git a/tests/skills/test_google_workspace_setup.py b/tests/skills/test_google_workspace_setup.py
index 385a68fb6c6..ef57e43d83b 100644
--- a/tests/skills/test_google_workspace_setup.py
+++ b/tests/skills/test_google_workspace_setup.py
@@ -28,14 +28,13 @@ def setup_module():
def test_stale_google_transitives_are_reported_missing(setup_module, monkeypatch):
- installed = {
- "google-api-python-client": "2.194.0",
- "google-auth": "2.55.0",
- "google-auth-oauthlib": "1.3.1",
- "google-auth-httplib2": "0.3.1",
- "httplib2": "0.31.2",
- "pyasn1": "0.6.3",
- }
+ """Absent or version-drifted packages are reported; exact matches are not."""
+ specs = list(setup_module.REQUIRED_PACKAGES)
+ assert len(specs) >= 3
+ installed = {spec.partition("==")[0]: spec.partition("==")[2] for spec in specs}
+ stale, missing = specs[0], specs[1]
+ installed[stale.partition("==")[0]] = "0.0.0-stale"
+ del installed[missing.partition("==")[0]]
def fake_version(name):
try:
@@ -45,11 +44,7 @@ def test_stale_google_transitives_are_reported_missing(setup_module, monkeypatch
monkeypatch.setattr(setup_module, "_distribution_version", fake_version)
- assert setup_module._missing_required_packages() == [
- "google-auth==2.55.1",
- "httplib2==0.32.0",
- "pyasn1==0.6.4",
- ]
+ assert setup_module._missing_required_packages() == [stale, missing]
def test_installer_repairs_stale_transitives(setup_module, monkeypatch):
diff --git a/tests/skills/test_google_workspace_setup_deps.py b/tests/skills/test_google_workspace_setup_deps.py
index bf776f28f7c..24d312805b6 100644
--- a/tests/skills/test_google_workspace_setup_deps.py
+++ b/tests/skills/test_google_workspace_setup_deps.py
@@ -94,63 +94,7 @@ class TestGoogleWorkspaceSetupDepsPins:
f" Full REQUIRED_PACKAGES: {packages}"
)
- def test_setup_py_pins_match_pyproject_toml(self):
- """httplib2 pin in setup.py must match pyproject.toml google extra."""
- required_packages = _parse_setup_py_required_packages()
- pyproject_packages = _parse_pyproject_google_extra()
-
- required_pins = _extract_pins(required_packages)
- pyproject_pins = _extract_pins(pyproject_packages)
-
- for pkg in ("httplib2", "google-api-python-client", "google-auth-oauthlib", "google-auth-httplib2"):
- setup_ver = required_pins.get(pkg)
- toml_ver = pyproject_pins.get(pkg)
- if setup_ver is None and toml_ver is None:
- continue # neither path pins it, skip
- assert toml_ver is not None, (
- f"{pkg} is pinned in setup.py ({setup_ver}) but NOT in pyproject.toml google extra.\n"
- f" setup.py: {required_pins}\n"
- f" pyproject.toml google: {pyproject_pins}"
- )
- assert setup_ver is not None, (
- f"{pkg} is pinned in pyproject.toml ({toml_ver}) but NOT in setup.py.\n"
- f" pyproject.toml google: {pyproject_pins}\n"
- f" setup.py: {required_pins}"
- )
- assert setup_ver == toml_ver, (
- f"{pkg} pin mismatch: setup.py has {setup_ver}, pyproject.toml has {toml_ver}.\n"
- f" setup.py: {required_pins}\n"
- f" pyproject.toml google: {pyproject_pins}"
- )
- def test_setup_py_pins_match_lazy_deps(self):
- """httplib2 pin in setup.py must match tools/lazy_deps.py skill.google_workspace."""
- required_packages = _parse_setup_py_required_packages()
- lazy_packages = _parse_lazy_deps_google_workspace()
-
- required_pins = _extract_pins(required_packages)
- lazy_pins = _extract_pins(lazy_packages)
-
- for pkg in ("httplib2", "google-api-python-client", "google-auth-oauthlib", "google-auth-httplib2"):
- setup_ver = required_pins.get(pkg)
- lazy_ver = lazy_pins.get(pkg)
- if setup_ver is None and lazy_ver is None:
- continue
- assert lazy_ver is not None, (
- f"{pkg} is pinned in setup.py ({setup_ver}) but NOT in lazy_deps.py.\n"
- f" setup.py: {required_pins}\n"
- f" lazy_deps.py: {lazy_pins}"
- )
- assert setup_ver is not None, (
- f"{pkg} is pinned in lazy_deps.py ({lazy_ver}) but NOT in setup.py.\n"
- f" lazy_deps.py: {lazy_pins}\n"
- f" setup.py: {required_pins}"
- )
- assert setup_ver == lazy_ver, (
- f"{pkg} pin mismatch: setup.py has {setup_ver}, lazy_deps.py has {lazy_ver}.\n"
- f" setup.py: {required_pins}\n"
- f" lazy_deps.py: {lazy_pins}"
- )
def test_all_google_packages_are_pinned_in_all_paths(self):
"""Every google workspace package that is version-pinned in any path must appear in all three."""
diff --git a/tests/skills/test_grounded_citations_skill.py b/tests/skills/test_grounded_citations_skill.py
index 1dd1dd01a63..29689e2df71 100644
--- a/tests/skills/test_grounded_citations_skill.py
+++ b/tests/skills/test_grounded_citations_skill.py
@@ -1,7 +1,6 @@
"""Tests for the grounded-citations bundled skill.
-Covers the SKILL.md authoring standards (frontmatter shape, ≤60-char
-description) and the behavior of ``scripts/sources.py`` — the citation ledger
+Covers the behavior of ``scripts/sources.py`` — the citation ledger
that assigns stable ``url -> [n]`` ids, renders Sources blocks, and verifies a
draft's citations. The verify path is the load-bearing piece: it is what
catches a hallucinated or renumbered citation before delivery.
@@ -11,24 +10,14 @@ from __future__ import annotations
import importlib.util
import json
-import re
from pathlib import Path
import pytest
-import yaml
SKILL_DIR = Path(__file__).resolve().parents[2] / "skills" / "research" / "grounded-citations"
SCRIPT = SKILL_DIR / "scripts" / "sources.py"
[email protected](scope="module")
-def frontmatter() -> dict:
- src = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
- m = re.search(r"^---\n(.*?)\n---", src, re.DOTALL)
- assert m, "SKILL.md missing YAML frontmatter"
- return yaml.safe_load(m.group(1))
-
-
@pytest.fixture(scope="module")
def sources_mod():
spec = importlib.util.spec_from_file_location("gc_sources", SCRIPT)
@@ -43,44 +32,13 @@ def ledger(tmp_path: Path) -> Path:
return tmp_path / "ledger.json"
-# ---------------------------------------------------------------------------
-# Authoring standards
-# ---------------------------------------------------------------------------
-
-def test_skill_files_present() -> None:
- assert (SKILL_DIR / "SKILL.md").is_file()
- assert SCRIPT.is_file()
- assert (SKILL_DIR / "references" / "citation-formats.md").is_file()
- assert (SKILL_DIR / "references" / "grounding-rationale.md").is_file()
-def test_description_within_limit(frontmatter: dict) -> None:
- desc = frontmatter["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars (limit 60): {desc!r}"
- assert desc.endswith(".")
-def test_required_frontmatter_fields(frontmatter: dict) -> None:
- assert frontmatter["name"] == "grounded-citations"
- for field in ("version", "author", "license", "platforms"):
- assert frontmatter.get(field), f"missing frontmatter field: {field}"
- assert frontmatter["metadata"]["hermes"]["category"] == "research"
-def test_skill_body_has_modern_sections() -> None:
- body = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
- for heading in (
- "## When to Use",
- "## Prerequisites",
- "## How to Run",
- "## Quick Reference",
- "## Procedure",
- "## Pitfalls",
- "## Verification",
- ):
- assert heading in body, f"SKILL.md missing section: {heading}"
-
# ---------------------------------------------------------------------------
# Ledger identity
@@ -574,20 +532,6 @@ def test_render_replace_in_appends_when_no_block_exists(sources_mod, tmp_path: P
# ---------------------------------------------------------------------------
-def test_stats_line_is_info_not_warn_on_success(sources_mod, tmp_path: Path, capsys) -> None:
- ledger = tmp_path / "st.json"
- args = ["--ledger", str(ledger)]
- sources_mod.main(args + ["add", "https://a.example"])
- draft = tmp_path / "d.md"
- draft.write_text(
- "A claim resting on the first source.[1]\n\nSources:\n[1] https://a.example\n",
- encoding="utf-8",
- )
- capsys.readouterr()
- assert sources_mod.main(args + ["verify", str(draft)]) == 0
- out = capsys.readouterr().out
- assert "info: stats:" in out
- assert "warn: stats:" not in out
def test_stats_reports_provenance_total_matching_coverage(sources_mod, ledger: Path, tmp_path: Path) -> None:
diff --git a/tests/skills/test_har_derived_api_client_skill.py b/tests/skills/test_har_derived_api_client_skill.py
index f2f1fb18172..2b432e9873a 100644
--- a/tests/skills/test_har_derived_api_client_skill.py
+++ b/tests/skills/test_har_derived_api_client_skill.py
@@ -1,19 +1,14 @@
"""Tests for the har-derived-api-client optional skill.
-Two layers, both stdlib + pytest, no network:
- 1. Structural / frontmatter contract on SKILL.md (matches the maintainer
- review checklist for optional skills).
- 2. Behavioral: run the real har_to_client.py logic against a synthetic HAR
- fixture and assert it derives the endpoint, collapses id path segments,
- filters static assets, and surfaces the User-Agent replay hint.
+Runs the real har_to_client.py logic against a synthetic HAR fixture and
+asserts it derives the endpoint, collapses id path segments, filters static
+assets, and surfaces the User-Agent replay hint. Stdlib + pytest, no network.
"""
import importlib.util
import json
-import re
from pathlib import Path
-import pytest
SKILL_DIR = (
Path(__file__).resolve().parents[2]
@@ -21,17 +16,9 @@ SKILL_DIR = (
/ "web-development"
/ "har-derived-api-client"
)
-SKILL_MD = SKILL_DIR / "SKILL.md"
-CAPTURE = SKILL_DIR / "scripts" / "har_capture.py"
-CAPTURE_CDP = SKILL_DIR / "scripts" / "har_capture_cdp.py"
DERIVE = SKILL_DIR / "scripts" / "har_to_client.py"
[email protected](scope="module")
-def skill_text() -> str:
- return SKILL_MD.read_text(encoding="utf-8")
-
-
def _load_module(path: Path, name: str):
spec = importlib.util.spec_from_file_location(name, path)
assert spec and spec.loader
@@ -40,40 +27,12 @@ def _load_module(path: Path, name: str):
return mod
-# --- structural contract ---------------------------------------------------
-
-
-def test_skill_files_exist():
- assert SKILL_MD.is_file()
- assert CAPTURE.is_file()
- assert CAPTURE_CDP.is_file()
- assert DERIVE.is_file()
-def test_frontmatter_present(skill_text: str):
- assert skill_text.startswith("---\n")
- assert skill_text.count("---") >= 2
-def test_description_under_sixty_chars(skill_text: str):
- m = re.search(r"^description: (.*)$", skill_text, re.MULTILINE)
- assert m, "no description field"
- desc = m.group(1).strip()
- assert len(desc) <= 60, f"description is {len(desc)} chars (>60): {desc!r}"
- assert desc.endswith("."), "description should end with a period"
-def test_required_sections_present(skill_text: str):
- for heading in (
- "## When to Use",
- "## Prerequisites",
- "## How to Run",
- "## Quick Reference",
- "## Procedure",
- "## Pitfalls",
- "## Verification",
- ):
- assert heading in skill_text, f"missing section: {heading}"
# --- behavioral: derivation logic -----------------------------------------
@@ -152,29 +111,7 @@ def test_path_template_collapses_ids():
assert mod.path_template("/v1/items/abc/x") == "/v1/items/abc/x"
-def test_capture_actions_parse_ok():
- # har_capture imports playwright at module top; only assert the file is
- # syntactically valid and exposes run_action without importing playwright.
- src = CAPTURE.read_text(encoding="utf-8")
- compile(src, str(CAPTURE), "exec")
- assert "def run_action(" in src
- assert 'record_har_content="embed"' in src
-
-
-def test_cdp_capture_is_valid_and_attaches_not_launches():
- # Covers the CDP pathway (cloud backends / /browser connect). Syntax-check
- # without importing playwright, and assert it attaches (connect_over_cdp)
- # and does NOT close a browser it doesn't own.
- src = CAPTURE_CDP.read_text(encoding="utf-8")
- compile(src, str(CAPTURE_CDP), "exec")
- assert "connect_over_cdp(" in src
- assert 'page.on("request"' in src and 'page.on("response"' in src
- # must not tear down a browser it merely attached to
- assert "browser.close()" not in src
-
-
-def test_skill_documents_all_browser_pathways(skill_text: str):
- # The skill must route every Hermes browser backend to the right capturer.
- for token in ("Browserbase", "Browser-Use", "Firecrawl", "browser connect",
- "har_capture_cdp.py", "connect_over_cdp"):
- assert token in skill_text, f"pathway coverage missing: {token}"
+
+
+
+
diff --git a/tests/skills/test_hermes_agent_skill.py b/tests/skills/test_hermes_agent_skill.py
deleted file mode 100644
index a98910a9968..00000000000
--- a/tests/skills/test_hermes_agent_skill.py
+++ /dev/null
@@ -1,69 +0,0 @@
-"""The `hermes-agent` skill is what a running Hermes knows about itself.
-
-`website/` is never packaged, so an installed Hermes has no local copy of the
-user guide; skills ARE synced into `$HERMES_HOME/skills/`. The skill therefore
-does not try to restate the product — it routes to the published `llms.txt`,
-which is generated from the docs tree on every build and so can never be behind
-the feature set. These tests keep that routing honest: the index has to be where
-the skill says it is, and every reference has to be reachable, otherwise a
-shipped feature is invisible and the agent answers "Hermes can't do that."
-"""
-
-from __future__ import annotations
-
-import importlib.util
-import re
-from pathlib import Path
-
-import pytest
-
-REPO = Path(__file__).resolve().parents[2]
-SKILL_DIR = REPO / "skills" / "autonomous-ai-agents" / "hermes-agent"
-SKILL_MD = SKILL_DIR / "SKILL.md"
-GENERATOR = REPO / "website" / "scripts" / "generate-llms-txt.py"
-
-
[email protected](scope="module")
-def skill_text() -> str:
- return SKILL_MD.read_text(encoding="utf-8")
-
-
-def test_every_referenced_file_exists(skill_text):
- """Routing a question to a file that isn't there is a dead end."""
- targets = set(re.findall(r"`((?:references|templates)/[^`]+)`", skill_text))
-
- assert targets, "the skill's routing table no longer references any files"
- for target in sorted(targets):
- assert (SKILL_DIR / target).exists(), f"SKILL.md routes to missing {target}"
-
-
-def test_every_reference_is_reachable_from_the_skill(skill_text):
- """An unrouted reference is one the agent will never think to open.
-
- This is the failure that produced the original complaint: content can exist
- and still be invisible because nothing points at it.
- """
- on_disk = {f"references/{path.name}" for path in (SKILL_DIR / "references").glob("*.md")}
- routed = set(re.findall(r"`(references/[^`]+)`", skill_text))
-
- assert not (on_disk - routed), (
- f"reference files no reader will ever reach: {sorted(on_disk - routed)} — "
- "add a routing-table row in SKILL.md"
- )
-
-
-def test_unknown_features_route_to_the_published_index(skill_text):
- """The catch-all is what makes coverage of the whole product possible."""
- assert "/docs/llms.txt" in skill_text
- # web_extract can be disabled; terminal never is.
- assert "curl" in skill_text, "no way to reach the index without web tools"
-
-
-def test_the_index_is_published_where_the_skill_says_it_is(skill_text):
- """A skill pointing at a URL nobody generates is worse than no routing."""
- spec = importlib.util.spec_from_file_location("generate_llms_txt", GENERATOR)
- assert spec is not None and spec.loader is not None
- gen = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(gen)
-
- assert f"{gen.SITE_BASE}/llms.txt" in skill_text
diff --git a/tests/skills/test_ip_as_logo_skill.py b/tests/skills/test_ip_as_logo_skill.py
deleted file mode 100644
index 239361f0aae..00000000000
--- a/tests/skills/test_ip_as_logo_skill.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""Tests for the ip-as-logo optional skill."""
-
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_PATH = (
- Path(__file__).resolve().parents[2] / "optional-skills" / "creative" / "ip-as-logo" / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- return yaml.safe_load(content[3 : m.start() + 3]), content[m.end() + 3 :]
-
-
-def test_frontmatter_fields_and_section_order():
- fm, body = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "ip-as-logo"
- assert fm["metadata"]["hermes"]["category"] == "creative"
- headings = re.findall(r"^## (.+)$", body, re.MULTILINE)
- expected = ["When to Use", "Prerequisites", "Procedure"]
- assert [h for h in headings if h in expected] == expected, headings
- assert headings[-1] == "Verification"
-
-
-def test_generation_routes_through_native_tool():
- """The upstream skill targeted another agent's image pipeline; the port must
- route through Hermes' `image_generate` and carry no residue of that harness."""
- _, body = _frontmatter_and_body()
- assert "`image_generate`" in body
- assert 'aspect_ratio="square"' in body
- assert not re.search(r"\bImageGen\b|\bCodex\b|\bClaude\b", body)
diff --git a/tests/skills/test_live_dashboard_skill.py b/tests/skills/test_live_dashboard_skill.py
index aa9ede91b90..6338453d04d 100644
--- a/tests/skills/test_live_dashboard_skill.py
+++ b/tests/skills/test_live_dashboard_skill.py
@@ -1,9 +1,6 @@
"""Tests for the live-dashboard optional skill."""
-import re
from pathlib import Path
-import yaml
-
SKILL_PATH = (
Path(__file__).resolve().parents[2]
/ "optional-skills"
@@ -13,60 +10,6 @@ SKILL_PATH = (
)
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "live-dashboard"
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(repo_root.glob(f"skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_procedure_is_structured_setup_tick_show():
- """The skill splits into setup / scheduled tick / render phases, each phase is a
- numbered-step procedure, and every step states a completion criterion."""
- _, body = _frontmatter_and_body()
- phases = re.findall(r"^## Procedure — (.+)$", body, re.MULTILINE)
- assert len(phases) == 3, phases
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 7
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
- for heading in ("## When to Use", "## Prerequisites", "## Pitfalls", "## Verification"):
- assert heading in body, heading
-
-
-def test_tools_wired_and_home_not_hardcoded():
- """Scheduling goes through `cronjob`, desktop rendering through `desktop_preview`,
- no-change ticks stay silent, and the Hermes home path is resolved, never assumed."""
- _, body = _frontmatter_and_body()
- assert re.search(r"cronjob\(action=\"create\"", body)
- assert re.search(r"desktop_preview\(action=\"open\"", body)
- assert "[SILENT]" in body
- assert "dashboard.json" in body
- assert "~/.hermes" not in body
-
-
def test_frontmatter_blueprint_is_a_valid_installed_blueprint():
"""The install-time suggestion rides the skills-pipeline blueprint block, not a
hard-wired catalog entry (an optional skill may not be installed)."""
@@ -77,4 +20,4 @@ def test_frontmatter_blueprint_is_a_valid_installed_blueprint():
job = blueprint_to_job_spec(spec)
assert job["skills"] == ["live-dashboard"]
assert len(job["schedule"].split()) == 5, f"invalid cron expr: {job['schedule']}"
- assert "[SILENT]" in job["prompt"] and "~/.hermes" not in job["prompt"]
\ No newline at end of file
+ assert "[SILENT]" in job["prompt"] and "~/.hermes" not in job["prompt"]
diff --git a/tests/skills/test_mcp_oauth_remote_gateway_skill.py b/tests/skills/test_mcp_oauth_remote_gateway_skill.py
index 88f4c48e6fc..69cc931d15a 100644
--- a/tests/skills/test_mcp_oauth_remote_gateway_skill.py
+++ b/tests/skills/test_mcp_oauth_remote_gateway_skill.py
@@ -2,7 +2,7 @@
Covers the diagnose-oauth-mcp.py decision tree (TOKEN_OK / REFRESH_FIXED /
SESSION_REVOKED / REFRESH_DEAD), the HERMES_HOME resolution fallback, the
-atomic --write persistence path, and SKILL.md frontmatter invariants.
+and the atomic --write persistence path.
No live network calls — urllib is mocked throughout.
"""
from __future__ import annotations
@@ -10,13 +10,11 @@ from __future__ import annotations
import importlib.util
import io
import json
-import re
import sys
import urllib.error
from pathlib import Path
from unittest.mock import patch
-import pytest
SKILL_DIR = (
Path(__file__).resolve().parents[2]
@@ -25,7 +23,6 @@ SKILL_DIR = (
/ "mcp-oauth-remote-gateway"
)
SCRIPT_PATH = SKILL_DIR / "scripts" / "diagnose-oauth-mcp.py"
-SKILL_MD = SKILL_DIR / "SKILL.md"
def load_module():
@@ -144,12 +141,3 @@ def test_requests_send_httpx_user_agent(tmp_path):
assert req.get_header("User-agent") == mod.UA
-def test_skill_md_frontmatter_invariants():
- yaml = pytest.importorskip("yaml")
- content = SKILL_MD.read_text()
- assert content.startswith("---\n")
- fm = yaml.safe_load(re.search(r"^---\n(.*?)\n---", content, re.DOTALL).group(1))
- assert len(fm["description"]) <= 60
- assert fm["description"].endswith(".")
- assert "platforms" in fm and len(fm["platforms"]) >= 1
- assert fm["author"].split(",")[0].strip() != "Hermes Agent" # human credited first
diff --git a/tests/skills/test_meeting_action_items_skill.py b/tests/skills/test_meeting_action_items_skill.py
deleted file mode 100644
index 54514ccac56..00000000000
--- a/tests/skills/test_meeting_action_items_skill.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""Tests for the meeting-action-items bundled skill."""
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_PATH = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "productivity"
- / "meeting-action-items"
- / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "meeting-action-items"
- hermes = fm["metadata"]["hermes"]
- assert hermes["tags"]
- assert "related_skills" in hermes
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent"), "human contributor must be credited first"
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(repo_root.glob(f"skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_no_phantom_connectors_in_prose():
- """Prose must not name tracker connectors that don't exist as skills."""
- _, body = _frontmatter_and_body()
- assert not re.search(r"\bLinear\b", body), "no phantom 'Linear' connector references"
-
-
-def test_body_structure_and_size():
- _, body = _frontmatter_and_body()
- for section in ("## When to Use", "## Procedure", "## Pitfalls", "## Verification"):
- assert section in body, f"missing section: {section}"
- assert len(SKILL_PATH.read_text(encoding="utf-8")) <= 100_000
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
- assert not re.search(r"[A-Z]:\\\\Users", content)
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 5
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
-
-
-def test_core_disciplines_present():
- _, body = _frontmatter_and_body()
- assert "never invent" in body, "due-date invention ban must be present"
- assert "before creating anything" in body, "reconcile-before-create must be present"
- assert "`unresolved`" in body, "missing owners/dates stay visibly unresolved"
diff --git a/tests/skills/test_office_document_skills.py b/tests/skills/test_office_document_skills.py
deleted file mode 100644
index 8b145ac1519..00000000000
--- a/tests/skills/test_office_document_skills.py
+++ /dev/null
@@ -1,149 +0,0 @@
-"""Invariant tests for the bundled office/document skills.
-
-Covers skills/productivity/{docx,xlsx,pdf,powerpoint} — the clean-room
-MIT office document suite. Tests assert contracts (frontmatter shape,
-referenced scripts exist, script CLI conventions, UTF-8-explicit I/O),
-not snapshots of skill content.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-import yaml
-
-REPO = Path(__file__).resolve().parent.parent.parent
-SKILLS = REPO / "skills"
-
-OFFICE_SKILLS = ["docx", "xlsx", "pdf", "powerpoint"]
-
-
-def _skill_dir(name: str) -> Path:
- return SKILLS / "productivity" / name
-
-
-def _frontmatter(skill_md: Path) -> dict:
- text = skill_md.read_text(encoding="utf-8")
- match = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)
- assert match, f"{skill_md} has no YAML frontmatter"
- return yaml.safe_load(match.group(1))
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_skill_exists_with_frontmatter(name):
- skill_md = _skill_dir(name) / "SKILL.md"
- assert skill_md.exists(), f"missing {skill_md}"
- fm = _frontmatter(skill_md)
- assert fm["name"] == name
- assert fm["description"].strip()
- assert len(fm["description"]) <= 60, (
- f"{name}: description is {len(fm['description'])} chars (max 60)"
- )
- assert fm["description"].rstrip('"').endswith(".")
- platforms = fm.get("platforms")
- assert platforms, f"{name}: missing platforms gating"
- assert set(platforms) <= {"linux", "macos", "windows"}
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_mit_licensed_clean_room(name):
- """The office suite is the clean-room rewrite: MIT, no Anthropic
- license text, no proprietary license markers anywhere in the dir."""
- skill_dir = _skill_dir(name)
- fm = _frontmatter(skill_dir / "SKILL.md")
- assert str(fm.get("license", "")).strip() == "MIT", (
- f"{name}: license must be MIT, got {fm.get('license')!r}"
- )
- assert not (skill_dir / "LICENSE.txt").exists(), (
- f"{name}: legacy LICENSE.txt present — clean-room dirs ship LICENSE (MIT)"
- )
- license_file = skill_dir / "LICENSE"
- assert license_file.exists(), f"{name}: missing MIT LICENSE file"
- text = license_file.read_text(encoding="utf-8")
- assert "MIT License" in text
- assert "Anthropic" not in text
- for path in skill_dir.rglob("*"):
- if path.is_file() and path.suffix in (".md", ".py"):
- content = path.read_text(encoding="utf-8", errors="replace")
- assert "Anthropic" not in content, (
- f"{name}: {path.relative_to(skill_dir)} references Anthropic — "
- "clean-room provenance violation"
- )
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_referenced_scripts_exist(name):
- """Every scripts/... path mentioned in SKILL.md must exist on disk."""
- skill_dir = _skill_dir(name)
- body = (skill_dir / "SKILL.md").read_text(encoding="utf-8")
- refs = set(re.findall(r"scripts/[\w./-]+\.py", body))
- assert refs, f"{name}: SKILL.md references no helper scripts"
- for ref in refs:
- assert (skill_dir / ref).exists(), f"{name}: SKILL.md references missing {ref}"
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_all_shipped_scripts_are_documented(name):
- """Every shipped scripts/*.py is mentioned in SKILL.md (no dead cargo).
- Shared/internal modules (underscore-prefixed or *_common.py) are exempt."""
- skill_dir = _skill_dir(name)
- body = (skill_dir / "SKILL.md").read_text(encoding="utf-8")
- for script in (skill_dir / "scripts").glob("*.py"):
- if script.name.startswith("_") or script.stem.endswith("_common"):
- continue
- assert script.name in body, (
- f"{name}: scripts/{script.name} is shipped but never mentioned in SKILL.md"
- )
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_scripts_use_explicit_utf8_text_io(name):
- """No locale-default text-mode I/O in helper scripts: every text-mode
- open() must pass encoding=. Binary-mode opens are exempt. This is the
- class of bug that mojibake'd form fills on cp1251/GBK/cp932 hosts."""
- skill_dir = _skill_dir(name)
- offenders = []
- for script in (skill_dir / "scripts").rglob("*.py"):
- content = script.read_text(encoding="utf-8")
- for m in re.finditer(r"(?<![\w.])open\(([^)]*)\)", content):
- args = m.group(1)
- if re.search(r"['\"][rwaxt+]*b[rwaxt+]*['\"]", args):
- continue # binary mode
- if "encoding" not in args:
- line = content[: m.start()].count("\n") + 1
- offenders.append(f"{script.relative_to(skill_dir)}:{line}: open({args})")
- assert not offenders, (
- f"{name}: text-mode open() without explicit encoding:\n" + "\n".join(offenders)
- )
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_scripts_are_argparse_clis(name):
- """Helper scripts are argparse CLIs: importable arg parsing + a main
- guard, so `python scripts/x.py --help` works everywhere."""
- skill_dir = _skill_dir(name)
- for script in (skill_dir / "scripts").glob("*.py"):
- if script.name.startswith("_") or script.stem.endswith("_common"):
- continue
- content = script.read_text(encoding="utf-8")
- assert "argparse" in content, f"{name}: scripts/{script.name} is not an argparse CLI"
- assert '__name__' in content, f"{name}: scripts/{script.name} lacks a __main__ guard"
-
-
[email protected]("name", OFFICE_SKILLS)
-def test_skill_has_tests(name):
- """Each office skill ships its own e2e pytest suite."""
- tests_dir = _skill_dir(name) / "tests"
- assert tests_dir.is_dir(), f"{name}: missing tests/ directory"
- assert list(tests_dir.glob("test_*.py")), f"{name}: no test files in tests/"
-
-
-def test_docs_pages_generated():
- """Each bundled office skill has a generated docs-site page."""
- docs_dir = REPO / "website" / "docs" / "user-guide" / "skills" / "bundled" / "productivity"
- for name in OFFICE_SKILLS:
- assert (docs_dir / f"productivity-{name}.md").exists(), (
- f"missing generated docs page for {name}; run website/scripts/generate-skill-docs.py"
- )
diff --git a/tests/skills/test_openclaw_migration.py b/tests/skills/test_openclaw_migration.py
index bfd69cc2d64..734727a2481 100644
--- a/tests/skills/test_openclaw_migration.py
+++ b/tests/skills/test_openclaw_migration.py
@@ -624,56 +624,6 @@ def test_rebrand_text_replaces_openclaw_variants():
-# ── migrate_model_config: alias resolution (issue #16745) ──────────────────
-
-def _run_model_migration(tmp_path: Path, openclaw_json: dict) -> dict:
- """Helper: run just migrate_model_config on an openclaw.json and return
- the parsed destination config.yaml."""
- import yaml
-
- mod = load_module()
- source = tmp_path / ".openclaw"
- target = tmp_path / ".hermes"
- source.mkdir(parents=True)
- target.mkdir(parents=True)
- (source / "openclaw.json").write_text(json.dumps(openclaw_json), encoding="utf-8")
-
- migrator = mod.Migrator(
- source_root=source,
- target_root=target,
- execute=True,
- workspace_target=None,
- overwrite=True,
- migrate_secrets=False,
- output_dir=target / "migration-report",
- )
- migrator.migrate_model_config()
-
- cfg_path = target / "config.yaml"
- if not cfg_path.exists():
- return {}
- return yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}
-
-
-def _extract_model(parsed: dict) -> str | None:
- model = parsed.get("model")
- if isinstance(model, dict):
- return model.get("default")
- return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
# ── non-UTF-8 tolerance (issue #8901) ───────────────────────────────────────
diff --git a/tests/skills/test_openclaw_migration_hardening.py b/tests/skills/test_openclaw_migration_hardening.py
index 9ad7b9a8e94..3688ab531d5 100644
--- a/tests/skills/test_openclaw_migration_hardening.py
+++ b/tests/skills/test_openclaw_migration_hardening.py
@@ -188,17 +188,6 @@ def test_provider_keys_skipped_warning_when_secrets_disabled(tmp_path):
# ───────────────────────────────────────────────────────────────────────
# Blocked-by-earlier-conflict sequencing
# ───────────────────────────────────────────────────────────────────────
-def test_config_apply_block_flips_on_config_yaml_conflict(tmp_path):
- mod = _load()
- migrator = _make_minimal_migrator(mod, tmp_path, execute=True)
- assert migrator._config_apply_blocked is False
- migrator.record(
- "model-config",
- source=None,
- destination=migrator.target_root / "config.yaml",
- status=mod.STATUS_CONFLICT,
- )
- assert migrator._config_apply_blocked is True
@@ -306,18 +295,5 @@ def test_json_mode_redacts_secrets_in_output(tmp_path):
# ───────────────────────────────────────────────────────────────────────
-def test_record_honors_sensitive_flag(tmp_path):
- mod = _load()
- migrator = _make_minimal_migrator(mod, tmp_path)
- migrator.record("x", None, None, "migrated", sensitive=True)
- assert migrator.items[0].sensitive is True
-def test_status_constants_match_historical_strings():
- """Downstream consumers (claw.py, tests, docs) depend on these string values."""
- mod = _load()
- assert mod.STATUS_MIGRATED == "migrated"
- assert mod.STATUS_SKIPPED == "skipped"
- assert mod.STATUS_CONFLICT == "conflict"
- assert mod.STATUS_ERROR == "error"
- assert mod.STATUS_ARCHIVED == "archived"
diff --git a/tests/skills/test_pinecone_research_skill.py b/tests/skills/test_pinecone_research_skill.py
deleted file mode 100644
index 6bf920841e5..00000000000
--- a/tests/skills/test_pinecone_research_skill.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""
-Smoke tests for the pinecone-research optional skill.
-
-Validates:
- - SKILL.md frontmatter conforms to the ≤60-char description standard
- - The skill name is distinct from the existing mlops/pinecone skill
- - Frontmatter has required fields
-"""
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-import yaml
-
-SKILL_DIR = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "research"
- / "pinecone-research"
-)
-
-MLOPS_PINECONE_DIR = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "mlops"
- / "pinecone"
-)
-
-
[email protected](scope="module")
-def frontmatter() -> dict:
- src = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
- m = re.search(r"^---\n(.*?)\n---", src, re.DOTALL)
- assert m, "SKILL.md missing YAML frontmatter"
- return yaml.safe_load(m.group(1))
-
-
-def test_skill_dir_exists() -> None:
- assert SKILL_DIR.is_dir(), f"missing skill dir: {SKILL_DIR}"
-
-
-
-
-def test_description_under_60_chars(frontmatter) -> None:
- desc = frontmatter["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars (limit ≤60): {desc!r}"
-
-
-
-
-
-
-def test_has_required_frontmatter_fields(frontmatter) -> None:
- for field in ("name", "description", "version", "license"):
- assert field in frontmatter, f"missing required field: {field}"
-
-
-
-
- "path",
- [
- "scripts/rag_pipeline.py",
- "scripts/memory_manager.py",
- ],
-)
-def test_shipped_scripts_parse(path: str) -> None:
- """Shipped scripts must be valid Python (ast.parse raises SyntaxError otherwise)."""
- import ast
-
- src = (SKILL_DIR / path).read_text(encoding="utf-8")
- ast.parse(src) # raises SyntaxError on broken Python
-
-
-def test_scripts_use_pinecone_client() -> None:
- """Both scripts should reference the Pinecone SDK."""
- for script in ("scripts/rag_pipeline.py", "scripts/memory_manager.py"):
- src = (SKILL_DIR / script).read_text(encoding="utf-8")
- assert "PINECONE_API_KEY" in src, f"{script} should read PINECONE_API_KEY"
- assert "Pinecone" in src, f"{script} should import/use Pinecone client"
diff --git a/tests/skills/test_product_price_monitor_skill.py b/tests/skills/test_product_price_monitor_skill.py
index 4151c242fb5..81e0e54de2a 100644
--- a/tests/skills/test_product_price_monitor_skill.py
+++ b/tests/skills/test_product_price_monitor_skill.py
@@ -1,108 +1,4 @@
-"""Tests for the product-price-monitor skill and its price-watch blueprint."""
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_PATH = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "productivity"
- / "product-price-monitor"
- / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "product-price-monitor"
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent")
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(repo_root.glob(f"skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_no_phantom_connectors_in_prose():
- _, body = _frontmatter_and_body()
- assert "flight-research" not in body, "no phantom 'flight-research' skill references"
-
-
-def test_setup_tick_split():
- """The skill must separate one-time setup from the recurring cron tick."""
- _, body = _frontmatter_and_body()
- assert "Setup (foreground, once)" in body
- assert "Tick (each scheduled run)" in body
- assert "cronjob(action=" in body, "must wire scheduling through the cronjob tool"
- assert "Do not schedule until one foreground fetch works" in body
-
-
-def test_state_discipline_present():
- _, body = _frontmatter_and_body()
- assert "never overwrite the last good observation" in body
- assert "fingerprint" in body
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 5
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert not re.search(r"/home/(?!.*price-watches)", content)
- assert "/home/bb" not in content
-
-
-def test_price_watch_blueprint_registered():
- from cron.blueprint_catalog import CATALOG
-
- bp = next((b for b in CATALOG if b.key == "price-watch"), None)
- assert bp is not None, "price-watch blueprint missing from catalog"
- assert "product-price-monitor" in bp.skills, "blueprint must load the skill"
- slot_names = {s.name for s in bp.slots}
- assert {"item", "condition", "interval_h", "deliver"} <= slot_names
- assert "[SILENT]" in bp.prompt_template, "silent path must be explicit"
- assert "{item}" in bp.prompt_template and "{condition}" in bp.prompt_template
+"""Tests for the product-price-monitor skill's price-watch blueprint."""
def test_price_watch_blueprint_schedule_resolves():
diff --git a/tests/skills/test_property_listings_skill.py b/tests/skills/test_property_listings_skill.py
index 76833c474e5..e49dcefd0e0 100644
--- a/tests/skills/test_property_listings_skill.py
+++ b/tests/skills/test_property_listings_skill.py
@@ -2,17 +2,12 @@
import json
from pathlib import Path
-from agent.prompt_builder import PLATFORM_HINTS
from tools.skills_hub_official import OptionalSkillSource
ROOT = Path(__file__).resolve().parents[2]
-def test_property_recipe_is_not_paid_for_by_unrelated_desktop_sessions():
- hint = PLATFORM_HINTS["desktop"]
- assert "```listing" not in hint
- assert "MEDIA:" in hint and "::preview" in hint
def test_optional_catalog_fetch_preserves_a_usable_property_recipe(tmp_path, monkeypatch):
diff --git a/tests/skills/test_publish_site_skill.py b/tests/skills/test_publish_site_skill.py
deleted file mode 100644
index 7cfc900065a..00000000000
--- a/tests/skills/test_publish_site_skill.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""Tests for the optional-skills/web-development/publish-site skill.
-
-Structural + internal-consistency checks only (stdlib + pytest, no network).
-"""
-
-import re
-from pathlib import Path
-
-import pytest
-
-REPO = Path(__file__).resolve().parents[2]
-SKILL_DIR = REPO / "optional-skills" / "web-development" / "publish-site"
-SKILL_MD = SKILL_DIR / "SKILL.md"
-
-VALID_PLATFORMS = {"linux", "macos", "windows"}
-
-
[email protected](scope="module")
-def skill_text() -> str:
- return SKILL_MD.read_text(encoding="utf-8")
-
-
[email protected](scope="module")
-def frontmatter(skill_text: str) -> dict:
- """Parse the YAML frontmatter with stdlib only (flat key: value fields)."""
- m = re.match(r"^---\n(.*?)\n---\n", skill_text, re.DOTALL)
- assert m, "SKILL.md must open with '---' delimited YAML frontmatter"
- fm: dict[str, str] = {}
- for line in m.group(1).splitlines():
- if line.startswith((" ", "\t")) or ":" not in line:
- continue # nested metadata keys — not needed here
- key, _, value = line.partition(":")
- fm[key.strip()] = value.strip()
- return fm
-
-
-def test_skill_file_exists():
- assert SKILL_MD.is_file(), f"missing {SKILL_MD}"
-
-
-def test_frontmatter_parses(frontmatter: dict):
- assert frontmatter.get("name") == "publish-site"
- assert frontmatter.get("version"), "version field required"
- assert frontmatter.get("license") == "MIT"
- assert "Hermes Agent" in frontmatter.get("author", "")
-
-
-def test_description_length_and_period(frontmatter: dict):
- desc = frontmatter.get("description", "").strip().strip('"')
- assert desc, "no description field"
- assert len(desc) <= 60, f"description is {len(desc)} chars (>60): {desc!r}"
- assert desc.endswith("."), "description must end with a period"
-
-
-def test_platforms_list_valid(frontmatter: dict):
- raw = frontmatter.get("platforms", "")
- platforms = [p.strip() for p in raw.strip("[]").split(",") if p.strip()]
- assert platforms, "platforms list must be non-empty"
- assert set(platforms) <= VALID_PLATFORMS, f"invalid platforms: {platforms}"
- # gh/wrangler/netlify are all cross-platform — the skill keeps all three.
- assert set(platforms) == VALID_PLATFORMS
-
-
-def test_required_sections_present(skill_text: str):
- for heading in (
- "## When to Use",
- "## Prerequisites",
- "## How to Run",
- "## Quick Reference",
- "## Procedure",
- "## Pitfalls",
- "## Verification",
- ):
- assert heading in skill_text, f"missing section: {heading}"
-
-
-def test_no_dangling_skill_view_references(skill_text: str):
- """Every skill_view(name='...') reference must target a shipped skill."""
- targets = re.findall(r"skill_view\(\s*name\s*=\s*['\"]([^'\"]+)['\"]", skill_text)
- for name in targets:
- hits = list((REPO / "skills").glob(f"**/{name}/SKILL.md")) + list(
- (REPO / "optional-skills").glob(f"**/{name}/SKILL.md")
- )
- assert hits, f"skill_view reference to non-shipped skill: {name}"
-
-
-def test_referenced_sibling_skills_ship(skill_text: str):
- """Prose-referenced companion skills must exist in the shipped trees."""
- for name in ("cloudflare-temporary-deploy",):
- if name in skill_text:
- hits = list((REPO / "skills").glob(f"**/{name}/SKILL.md")) + list(
- (REPO / "optional-skills").glob(f"**/{name}/SKILL.md")
- )
- assert hits, f"referenced skill does not ship: {name}"
-
-
-def test_provider_ladder_documented(skill_text: str):
- """All three rungs of the provider ladder with their deploy commands."""
- assert "gh repo create" in skill_text
- assert "gh-pages" in skill_text
- assert "wrangler@latest pages deploy" in skill_text
- assert "netlify deploy --prod" in skill_text
-
-
-def test_version_before_deploy_discipline(skill_text: str):
- assert "git tag" in skill_text, "deploys must be tagged"
- assert "Never deploy uncommitted files" in skill_text
-
-
-def test_rollback_documented(skill_text: str):
- assert "Rollback" in skill_text
- assert re.search(r"git checkout deploy-", skill_text), "rollback must redeploy a previous tag"
-
-
-def test_secrets_never_in_repo(skill_text: str):
- assert "NEVER commit secrets" in skill_text
- assert ".gitignore" in skill_text
-
-
-def test_spa_404_pitfall_documented(skill_text: str):
- assert "404.html" in skill_text
- assert "_redirects" in skill_text
-
-
-def test_verification_uses_real_http_check(skill_text: str):
- assert "%{http_code}" in skill_text
- assert "200" in skill_text
- assert "deploy log alone" in skill_text
-
-
-def test_preview_before_deploy(skill_text: str):
- assert "http.server" in skill_text
- assert "cloudflared tunnel --url" in skill_text
- assert "trycloudflare.com" in skill_text
-
-
-def test_category_description_exists():
- desc = REPO / "optional-skills" / "web-development" / "DESCRIPTION.md"
- assert desc.is_file(), "optional web-development category needs a DESCRIPTION.md"
-
-
-if __name__ == "__main__":
- raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/skills/test_scrollcraft_skill.py b/tests/skills/test_scrollcraft_skill.py
deleted file mode 100644
index 6a88660ba55..00000000000
--- a/tests/skills/test_scrollcraft_skill.py
+++ /dev/null
@@ -1,88 +0,0 @@
-"""Tests for the scrollcraft optional skill (ported from nateherkai/scroll-craft)."""
-
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_DIR = Path(__file__).resolve().parents[2] / "optional-skills/web-development/scrollcraft"
-SKILL_MD = SKILL_DIR / "SKILL.md"
-
-
-def _frontmatter() -> dict:
- text = SKILL_MD.read_text(encoding="utf-8")
- match = re.match(r"\A---\n(.*?)\n---\n", text, re.DOTALL)
- assert match, "SKILL.md must start with YAML frontmatter"
- data = yaml.safe_load(match.group(1))
- assert isinstance(data, dict)
- return data
-
-
-def test_frontmatter_parses():
- fm = _frontmatter()
- assert fm["name"] == "scrollcraft"
-
-
-def test_description_length_and_period():
- desc = _frontmatter()["description"]
- assert isinstance(desc, str)
- assert len(desc) <= 60, f"description is {len(desc)} chars"
- assert desc.endswith(".")
-
-
-def test_platforms_present():
- fm = _frontmatter()
- assert "platforms" in fm
- assert isinstance(fm["platforms"], list) and fm["platforms"]
-
-
-def test_license_is_mit():
- assert _frontmatter()["license"] == "MIT"
-
-
-def test_license_file_exists():
- lic = SKILL_DIR / "LICENSE.txt"
- assert lic.is_file()
- assert "MIT License" in lic.read_text(encoding="utf-8")
-
-
-def test_mentioned_paths_exist_or_marked_upstream():
- """Every vendored-tree relative path mentioned in SKILL.md exists on disk,
- or its line is marked as upstream / not vendored."""
- path_re = re.compile(
- r"(?:references|engine|scripts|templates)/[\w.-]+\.(?:md|html|mjs|css|js)"
- )
- for line in SKILL_MD.read_text(encoding="utf-8").splitlines():
- for rel in path_re.findall(line):
- if (SKILL_DIR / rel).is_file():
- continue
- low = line.lower()
- assert "upstream" in low or "not vendored" in low, (
- f"SKILL.md mentions missing path {rel!r} without an "
- f"upstream/not-vendored marker on the same line: {line!r}"
- )
-
-
-def test_no_foreign_agent_residue():
- """Prose files carry no upstream-agent-specific residue."""
- residue = re.compile(r"claude|allowed-tools|AskUserQuestion", re.IGNORECASE)
- prose = [SKILL_MD] + sorted((SKILL_DIR / "references").glob("*.md"))
- for path in prose:
- for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
- assert not residue.search(line), f"{path.name}:{lineno}: {line!r}"
-
-
-def test_scripts_present_and_nonempty():
- scripts_dir = SKILL_DIR / "scripts"
- mjs = sorted(scripts_dir.glob("*.mjs"))
- expected = {
- "doctor.mjs",
- "kie.mjs",
- "serve.mjs",
- "shoot.mjs",
- "workspace.mjs",
- "worldflight-assert.mjs",
- }
- assert {p.name for p in mjs} == expected
- for p in mjs:
- assert p.stat().st_size > 0, f"{p.name} is empty"
diff --git a/tests/skills/test_sdlc_review_skill.py b/tests/skills/test_sdlc_review_skill.py
deleted file mode 100644
index 901e6b3ba48..00000000000
--- a/tests/skills/test_sdlc_review_skill.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Contract tests for the bundled SDLC review skill."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-
-SKILL_MD = (
- Path(__file__).resolve().parents[2]
- / "skills"
- / "devops"
- / "sdlc-review"
- / "SKILL.md"
-)
-REQUIRED_SECTIONS = [
- "## When to Use",
- "## Prerequisites",
- "## How to Run",
- "## Quick Reference",
- "## Review Lenses",
- "## Procedure",
- "## Pitfalls",
- "## Verification",
-]
-REVIEW_ACTIONS = {
- "kanban_show",
- "kanban_comment",
- "kanban_complete",
- "kanban_request_changes",
- "kanban_block",
-}
-
-
[email protected](scope="module")
-def skill_text() -> str:
- return SKILL_MD.read_text(encoding="utf-8")
-
-
-def _frontmatter_value(text: str, key: str) -> str:
- match = re.search(rf"^{re.escape(key)}:\s*(.+)$", text, re.MULTILINE)
- assert match, f"missing frontmatter field: {key}"
- return match.group(1).strip()
-
-
-def test_frontmatter_meets_hardline_standard(skill_text: str) -> None:
- assert skill_text.startswith("---\n")
- assert _frontmatter_value(skill_text, "name") == "sdlc-review"
-
- description = _frontmatter_value(skill_text, "description")
- assert len(description) <= 60
- assert description.endswith(".")
-
- for field in ("version", "author", "license", "platforms"):
- assert _frontmatter_value(skill_text, field)
- assert not _frontmatter_value(skill_text, "author").startswith("Hermes Agent")
-
-
-def test_body_uses_required_modern_section_order(skill_text: str) -> None:
- assert "# SDLC Review Skill" in skill_text
- positions = [skill_text.index(section) for section in REQUIRED_SECTIONS]
- assert positions == sorted(positions)
-
-
[email protected]("tool_name", sorted(REVIEW_ACTIONS))
-def test_skill_documents_native_review_actions(
- skill_text: str,
- tool_name: str,
-) -> None:
- assert f"`{tool_name}`" in skill_text
-
-
-def test_verdicts_route_through_distinct_terminal_actions(skill_text: str) -> None:
- quick_reference = skill_text.split("## Quick Reference", 1)[1].split(
- "## Review Lenses", 1
- )[0]
- assert "Approve" in quick_reference and "`kanban_complete`" in quick_reference
- assert "Request changes" in quick_reference
- assert "`kanban_request_changes`" in quick_reference
- assert "Escalate" in quick_reference and "`kanban_block`" in quick_reference
-
-
-def test_review_lenses_vary_per_round(skill_text: str) -> None:
- lenses = skill_text.split("## Review Lenses", 1)[1].split("## Procedure", 1)[0]
- # Round derivation must key off history the reviewer actually sees.
- assert "`changes_requested`" in lenses
- assert "Prior attempts on this task" in lenses
- # One distinct lens per round.
- for lens in ("Artifact", "Execution", "Contract"):
- assert lens in lenses
- # Execution lens must direct empirical verification via the terminal.
- assert "`terminal`" in lenses
- # Fan-out note: parallel reviewers get different briefs.
- assert "`delegate_task`" in lenses
diff --git a/tests/skills/test_setup_wizard_generator_skill.py b/tests/skills/test_setup_wizard_generator_skill.py
deleted file mode 100644
index 81ba0559a8a..00000000000
--- a/tests/skills/test_setup_wizard_generator_skill.py
+++ /dev/null
@@ -1,87 +0,0 @@
-"""Tests for optional-skills/devops/setup-wizard-generator (template integrity)."""
-
-import re
-import subprocess
-from pathlib import Path
-
-import pytest
-import yaml
-
-SKILL_DIR = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "devops"
- / "setup-wizard-generator"
-)
-SKILL_MD = SKILL_DIR / "SKILL.md"
-TEMPLATE = SKILL_DIR / "templates" / "template.sh"
-
-
-class TestFrontmatter:
- def _fm(self):
- text = SKILL_MD.read_text(encoding="utf-8")
- m = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)
- assert m, "SKILL.md missing YAML frontmatter"
- return yaml.safe_load(m.group(1))
-
- def test_name_matches_directory(self):
- assert self._fm()["name"] == "setup-wizard-generator"
-
- def test_description_length(self):
- assert len(self._fm()["description"]) <= 60
-
- def test_license_and_platforms(self):
- fm = self._fm()
- assert fm["license"] == "MIT"
- assert "linux" in fm["platforms"]
-
-
-class TestTemplate:
- def test_template_exists(self):
- assert TEMPLATE.is_file()
-
- def test_bash_syntax(self):
- proc = subprocess.run(
- ["bash", "-n", str(TEMPLATE)], capture_output=True, text=True
- )
- assert proc.returncode == 0, proc.stderr
-
- def test_stages_marker_present(self):
- text = TEMPLATE.read_text(encoding="utf-8")
- assert "STAGES" in text, "authoring marker missing"
-
- def test_library_helpers_defined(self):
- text = TEMPLATE.read_text(encoding="utf-8")
- for helper in (
- "stage()",
- "say()",
- "step()",
- "open_url()",
- "write_env()",
- "set_secret()",
- "finish()",
- ):
- assert helper in text, f"missing library helper {helper}"
-
- def test_ask_secret_defined(self):
- # secret entry must exist (hidden input path)
- assert "ask_secret" in TEMPLATE.read_text(encoding="utf-8")
-
- def test_total_stages_variable(self):
- assert re.search(
- r"^TOTAL_STAGES=", TEMPLATE.read_text(encoding="utf-8"), re.MULTILINE
- )
-
-
-class TestSkillBody:
- def test_references_template_path(self):
- assert "templates/template.sh" in SKILL_MD.read_text(encoding="utf-8")
-
- def test_no_upstream_harness_residue(self):
- text = SKILL_MD.read_text(encoding="utf-8").lower()
- for token in ("claude", "/wizard", "slash command"):
- assert token not in text, f"upstream residue: {token}"
-
-
-if __name__ == "__main__":
- raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/skills/test_skill_platform_gates.py b/tests/skills/test_skill_platform_gates.py
deleted file mode 100644
index 0a8bf068231..00000000000
--- a/tests/skills/test_skill_platform_gates.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""Platform gates of optional skills whose bodies are bound to one OS family.
-
-Front-matter ``platforms`` feeds skill selection, so a declared platform the
-body cannot run on gets the skill offered and failing at step one. Asserts on
-the declared data through the real frontmatter parser (``agent.skill_utils``)
-instead of faking the host OS (tests/conftest.py host-marker policy).
-"""
-from pathlib import Path
-
-import pytest
-
-from agent.skill_utils import PLATFORM_MAP, parse_frontmatter
-
-REPO = Path(__file__).resolve().parents[2]
-
-
- ("skill", "platform", "why"),
- [
- ("optional-skills/creative/heartmula", "windows", ". .venv/bin/activate"),
- ("optional-skills/mlops/tensorrt-llm", "macos", "Requires CUDA"),
- ],
-)
-def test_os_bound_skill_is_not_offered_on_the_wrong_platform(skill, platform, why):
- fm, body = parse_frontmatter((REPO / skill / "SKILL.md").read_text(encoding="utf-8"))
- assert why in body, f"{skill}: body no longer carries the OS-binding step; re-evaluate its platforms"
- declared = fm.get("platforms")
- assert declared, f"{skill}: an OS-bound body needs an explicit platforms list"
- declared = {PLATFORM_MAP.get(str(p).lower().strip(), str(p).lower().strip()) for p in declared}
- assert PLATFORM_MAP.get(platform, platform) not in declared, (
- f"{skill} declares a platform its body cannot run on: {platform}"
- )
diff --git a/tests/skills/test_social_media_content_calendar_skill.py b/tests/skills/test_social_media_content_calendar_skill.py
deleted file mode 100644
index 01c45aaafe9..00000000000
--- a/tests/skills/test_social_media_content_calendar_skill.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Tests for the social-media-content-calendar optional skill."""
-import re
-from pathlib import Path
-
-import yaml
-
-SKILL_PATH = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "creative"
- / "social-media-content-calendar"
- / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "social-media-content-calendar"
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent")
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- repo_root = SKILL_PATH.parents[3]
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(repo_root.glob(f"skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_no_phantom_skill_references():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "image-generation-workflow" not in content, "phantom skill ref must be gone"
-
-
-def test_honest_handoff_language():
- _, body = _frontmatter_and_body()
- assert "handed-off, not published" in body or "handed-off slots" in body, (
- "platforms without connectors must end at handoff, not claimed publication"
- )
-
-
-def test_body_structure_and_size():
- _, body = _frontmatter_and_body()
- for section in ("## When to Use", "## Procedure", "## Pitfalls", "## Verification"):
- assert section in body, f"missing section: {section}"
- assert len(SKILL_PATH.read_text(encoding="utf-8")) <= 100_000
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 6
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
diff --git a/tests/skills/test_tldraw_offline_skill.py b/tests/skills/test_tldraw_offline_skill.py
deleted file mode 100644
index fe986fe5d54..00000000000
--- a/tests/skills/test_tldraw_offline_skill.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""Tests for the tldraw-offline optional skill.
-
-Structural + internal-consistency checks only (stdlib + pytest, no network).
-The skill's runtime claims were validated live against the real tldraw offline
-app (headless) and its bundled script-context.d.ts; scripts/validate_shapes.mjs
-re-checks the shape schema against the tldraw SDK.
-"""
-
-import re
-from pathlib import Path
-
-import pytest
-
-SKILL_DIR = (
- Path(__file__).resolve().parents[2]
- / "optional-skills"
- / "creative"
- / "tldraw-offline"
-)
-SKILL_MD = SKILL_DIR / "SKILL.md"
-MAIN_JS = SKILL_DIR / "scripts" / "main.js"
-
-
[email protected](scope="module")
-def skill_text() -> str:
- return SKILL_MD.read_text(encoding="utf-8")
-
-
[email protected](scope="module")
-def main_js() -> str:
- return MAIN_JS.read_text(encoding="utf-8")
-
-
-def test_skill_file_exists():
- assert SKILL_MD.is_file(), f"missing {SKILL_MD}"
-
-
-def test_frontmatter_present(skill_text: str):
- assert skill_text.startswith("---\n"), "SKILL.md must open with YAML frontmatter"
- assert skill_text.count("---") >= 2, "frontmatter must be delimited by two '---'"
-
-
-
-
-def test_required_sections_present(skill_text: str):
- for heading in (
- "## When to Use",
- "## Prerequisites",
- "## How to Run",
- "## Quick Reference",
- "## Procedure",
- "## Pitfalls",
- "## Verification",
- ):
- assert heading in skill_text, f"missing section: {heading}"
-
-
-
-
-def test_counter_example_is_interactive_and_safe():
- """The counter.js example must show the verified interactive-UI pattern:
- ctx contract, pointer_down handling, and REQUIRED signal-based cleanup
- (whose absence causes the double-fire bug found live)."""
- counter = (SKILL_DIR / "scripts" / "counter.js").read_text(encoding="utf-8")
- assert "export default function ({ editor, helpers, signal })" in counter
- assert "pointer_down" in counter
- assert "editor.on('event'" in counter
- # the cleanup that prevents the click-doubling leak
- assert "signal.addEventListener('abort'" in counter
- assert "editor.off('event'" in counter
- # state kept in meta, rendered as label
- assert "meta" in counter and "count" in counter
-
-
-
-
-
-
-
-
-
-
-def test_uses_richtext_not_bare_string(skill_text: str):
- assert "toRichText" in skill_text
- assert "richText" in skill_text
-
-
-
-
-def test_main_js_matches_verified_contract(main_js: str):
- # main.js must use the real contract learned from the running app.
- assert "export default function ({ editor, helpers, signal })" in main_js
- # primitives imported from tldraw, not used as globals
- assert "from 'tldraw'" in main_js
- assert "createShapeId" in main_js and "toRichText" in main_js
- # idempotent furniture
- assert "createShapeIfMissing" in main_js
- # batched writes
- assert "editor.run(" in main_js
- # reactive + REQUIRED signal cleanup
- assert "editor.store.listen" in main_js
- assert "signal.addEventListener('abort'" in main_js
- # script-owned writes kept out of undo
- assert "history: 'ignore'" in main_js
-
-
-
-
-def test_platforms_declared(skill_text: str):
- m = re.search(r"^platforms: (.*)$", skill_text, re.MULTILINE)
- assert m, "platforms field required (cross-platform desktop app)"
- for os_name in ("linux", "macos", "windows"):
- assert os_name in m.group(1)
diff --git a/tests/skills/test_unbroker_skill.py b/tests/skills/test_unbroker_skill.py
index dfa60681f40..b6ca4fdb9db 100644
--- a/tests/skills/test_unbroker_skill.py
+++ b/tests/skills/test_unbroker_skill.py
@@ -31,26 +31,19 @@ import autopilot # noqa: E402
import contextlib as _ctx # noqa: E402
import io as _io # noqa: E402
import json as _json # noqa: E402
-import smtplib as _smtplib # noqa: E402
import time as _time # noqa: E402
import badbool # noqa: E402
import brokers # noqa: E402
-import cdp # noqa: E402
import config # noqa: E402
-import crypto # noqa: E402
import dossier # noqa: E402
-import email_modes # noqa: E402
import emailer # noqa: E402
import pdd # noqa: E402
import legal # noqa: E402
import ledger # noqa: E402
-import paths # noqa: E402
-import registry # noqa: E402
import report # noqa: E402
import storage # noqa: E402
import tiers # noqa: E402
-import vectors # noqa: E402
_AGE = bool(shutil.which("age") and shutil.which("age-keygen"))
@@ -134,16 +127,6 @@ def test_seed_broker_db_loads_and_is_well_formed():
-def test_blocked_pass_records_and_cluster_coverage():
- # Records added from the blocked-tail pass load, resolve, and dedupe correctly.
- ids = {b["id"] for b in brokers.load_all()}
- assert {"addresses", "socialcatfish"} <= ids
- # addresses.com is a PeopleConnect/Intelius front-end -> covered by the intelius cluster (deduped).
- assert "addresses" in brokers.clusters().get("intelius", [])
- for bid in ("addresses", "socialcatfish"):
- b = brokers.get(bid)
- assert tiers.select_tier(b) in {"T0", "T1", "T2", "T3"}
- assert b["optout"]["method"]
# --- tier selection -----------------------------------------------------------
@@ -613,36 +596,6 @@ def test_human_tasks_digest_markdown():
# --- CA data broker registry (coverage breadth: DROP + email lane) ---------------------------
-def _registry_csv():
- """Mimic the CA registry CSV: junk row 0, label row 1 (with the real NBSP), data rows."""
- import csv as _csv
- import io as _io
- buf = _io.StringIO()
- w = _csv.writer(buf)
- w.writerow(["", "junk header the site hides", "", "", "", ""])
- w.writerow(["Data broker\xa0name:", "Doing Business As (DBA), if applicable:",
- "Data broker primary website:", "Data broker primary contact email address:",
- "Data broker's primary website that contains details on how consumers can exercise "
- "their CA Consumer Privacy Act rights, including how to delete their personal information:",
- "The data broker or any of its subsidiaries is regulated by the federal Fair Credit "
- "Reporting Act (FCRA):"])
- w.writerow(["Acme Data LLC", "AcmeDBA", "https://acme.example",
- "[email protected]", "https://acme.example/ccpa", "No"])
- w.writerow(["Credit Bureau Co", "", "https://cbc.example",
- "[email protected]", "https://cbc.example/rights", "Yes"])
- return buf.getvalue()
-
-
-
-
-
-
-
-
-
-
-
-
# --- hardening: locking / rate-limit / retry / idempotency / freshness / metrics ------------
def test_storage_lock_mutual_exclusion_and_stale_break():
@@ -667,46 +620,6 @@ def test_storage_lock_mutual_exclusion_and_stale_break():
-class _FlakySMTP:
- attempts = 0
-
- def __init__(self, host, port, timeout=None):
- pass
-
- def __enter__(self):
- _FlakySMTP.attempts += 1
- if _FlakySMTP.attempts < 3:
- raise _smtplib.SMTPServerDisconnected("transient")
- return self
-
- def __exit__(self, *a):
- return False
-
- def ehlo(self):
- pass
-
- def starttls(self):
- pass
-
- def login(self, u, p):
- pass
-
- def send_message(self, m):
- _FlakySMTP.sent = m
-
-
-class _AuthFailSMTP(_FlakySMTP):
- def __enter__(self):
- return self
-
- def login(self, u, p):
- raise _smtplib.SMTPAuthenticationError(535, b"bad creds")
-
-
-
-
-
-
def _run(argv) -> dict:
buf = _io.StringIO()
with _ctx.redirect_stdout(buf):
diff --git a/tests/skills/test_weekly_review_planning_skill.py b/tests/skills/test_weekly_review_planning_skill.py
index 4fc5fd98b5b..21d497e835c 100644
--- a/tests/skills/test_weekly_review_planning_skill.py
+++ b/tests/skills/test_weekly_review_planning_skill.py
@@ -1,78 +1,7 @@
-"""Tests for the weekly-review-planning skill and blueprint->skill wiring."""
-import re
+"""Invariant: every skill a cron blueprint loads ships as a bundled skill."""
from pathlib import Path
-import yaml
-
REPO_ROOT = Path(__file__).resolve().parents[2]
-SKILL_PATH = (
- REPO_ROOT / "skills" / "productivity" / "weekly-review-planning" / "SKILL.md"
-)
-
-
-def _frontmatter_and_body():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert content.startswith("---")
- m = re.search(r"\n---\s*\n", content[3:])
- assert m, "frontmatter must close with ---"
- fm = yaml.safe_load(content[3 : m.start() + 3])
- body = content[m.end() + 3 :]
- return fm, body
-
-
-def test_skill_file_exists():
- assert SKILL_PATH.is_file()
-
-
-def test_frontmatter_required_fields():
- fm, _ = _frontmatter_and_body()
- for field in ("name", "description", "version", "author", "license", "platforms"):
- assert field in fm, f"missing frontmatter field: {field}"
- assert fm["name"] == "weekly-review-planning"
-
-
-def test_description_hardline():
- fm, _ = _frontmatter_and_body()
- desc = fm["description"]
- assert len(desc) <= 60, f"description is {len(desc)} chars; hardline is 60"
- assert desc.endswith(".")
-
-
-def test_author_credits_human_first():
- fm, _ = _frontmatter_and_body()
- assert not fm["author"].startswith("Hermes Agent")
- assert "benbarclay" in fm["author"]
-
-
-def test_related_skills_resolve_in_repo():
- fm, _ = _frontmatter_and_body()
- for name in fm["metadata"]["hermes"]["related_skills"]:
- hits = (
- list(REPO_ROOT.glob(f"skills/*/{name}/SKILL.md"))
- + list(REPO_ROOT.glob(f"optional-skills/*/{name}/SKILL.md"))
- + list(REPO_ROOT.glob(f"skills/*/*/{name}/SKILL.md"))
- )
- assert hits, f"related_skills entry does not resolve in-repo: {name}"
-
-
-def test_body_structure_and_size():
- _, body = _frontmatter_and_body()
- for section in ("## When to Use", "## Procedure", "## Pitfalls", "## Verification"):
- assert section in body, f"missing section: {section}"
- assert len(SKILL_PATH.read_text(encoding="utf-8")) <= 100_000
-
-
-def test_no_machine_local_paths():
- content = SKILL_PATH.read_text(encoding="utf-8")
- assert "/home/" not in content
-
-
-def test_steps_have_completion_criteria():
- _, body = _frontmatter_and_body()
- steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)
- assert len(steps) >= 6
- for step in steps:
- assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"
def _skill_dir_exists(name: str) -> bool:
@@ -82,14 +11,6 @@ def _skill_dir_exists(name: str) -> bool:
)
-def test_blueprint_loads_this_skill():
- from cron.blueprint_catalog import CATALOG
-
- bp = next(b for b in CATALOG if b.key == "weekly-review")
- assert "weekly-review-planning" in bp.skills
- assert "weekly-review-planning" in bp.prompt_template
-
-
def test_every_blueprint_skill_resolves_in_repo():
"""Invariant: any skill a blueprint loads must exist as a bundled skill."""
from cron.blueprint_catalog import CATALOG
@@ -99,21 +20,3 @@ def test_every_blueprint_skill_resolves_in_repo():
assert _skill_dir_exists(skill_name), (
f"blueprint {bp.key!r} loads nonexistent skill {skill_name!r}"
)
-
-
-def test_task_skill_blueprints_are_wired():
- """The recurring-task blueprints must load their procedure skills."""
- from cron.blueprint_catalog import CATALOG
-
- expected = {
- "morning-brief": "google-workspace",
- "important-mail": "email-inbox-triage",
- "weekly-review": "weekly-review-planning",
- "price-watch": "product-price-monitor",
- }
- by_key = {b.key: b for b in CATALOG}
- for key, skill_name in expected.items():
- assert key in by_key, f"blueprint {key!r} missing from catalog"
- assert skill_name in by_key[key].skills, (
- f"blueprint {key!r} must load skill {skill_name!r}"
- )
diff --git a/tests/skills/test_xurl_article_ingestion_docs.py b/tests/skills/test_xurl_article_ingestion_docs.py
deleted file mode 100644
index 6364b928977..00000000000
--- a/tests/skills/test_xurl_article_ingestion_docs.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-SKILL_MD = REPO_ROOT / "skills" / "social-media" / "xurl" / "SKILL.md"
-DOC_MD = (
- REPO_ROOT
- / "website"
- / "docs"
- / "user-guide"
- / "skills"
- / "bundled"
- / "social-media"
- / "social-media-xurl.md"
-)
-
-
-def test_xurl_article_ingestion_uses_raw_api_mode():
- skill_text = SKILL_MD.read_text(encoding="utf-8")
- docs_text = DOC_MD.read_text(encoding="utf-8")
-
- for text in (skill_text, docs_text):
- assert "For X Articles, use raw API mode" in text
- assert "`xurl read`" in text
- assert "do not put `read` before a `/2/tweets/...`" in text
- assert "tweet.fields=created_at,lang,public_metrics" in text
- assert "referenced_tweets,article" in text
- assert "data.article.plain_text" in text
- assert "read '/2/tweets/" not in text
diff --git a/tests/skills/test_xurl_x_search_routing.py b/tests/skills/test_xurl_x_search_routing.py
deleted file mode 100644
index 0699b841f91..00000000000
--- a/tests/skills/test_xurl_x_search_routing.py
+++ /dev/null
@@ -1,87 +0,0 @@
-"""Behavioral contract for xurl / x_search routing guidance.
-
-These tests assert structural invariants (required topics + placement of the
-routing guidance), not frozen prose snapshots.
-
-Placement contract (July 2026):
-- The xurl SKILL must NOT name `x_search` (or any other credential-gated
- surface): the skill loads even when that tool isn't registered, so it must
- describe its own search distinctively in its own terms (raw, engageable
- post objects as the authenticated account).
-- Cross-surface routing guidance lives where both surfaces are known to
- exist together: the x_search feature docs, the toolset description, and
- the tools-config setup note.
-"""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-XURL_SKILL = REPO_ROOT / "skills" / "social-media" / "xurl" / "SKILL.md"
-X_SEARCH_DOC = REPO_ROOT / "website" / "docs" / "user-guide" / "features" / "x-search.md"
-
-
-def _read(path: Path) -> str:
- return path.read_text(encoding="utf-8")
-
-
-def _contains_any(text: str, *needles: str) -> bool:
- lowered = text.lower()
- return any(n.lower() in lowered for n in needles)
-
-
-def test_xurl_skill_never_names_credential_gated_surfaces():
- """The skill must be self-contained: no cross-references to tools that
- may not be registered (x_search is check_fn-gated on xAI credentials)."""
- lowered = _read(XURL_SKILL).lower()
- assert "x_search" not in lowered
- assert "web_search" not in lowered
-
-
-def test_xurl_skill_search_is_distinct_standalone():
- """Search must be described so an agent can route correctly even when
- another X search surface exists — raw engageable posts, authenticated."""
- text = _read(XURL_SKILL)
- assert _contains_any(text, "raw post")
- assert _contains_any(text, "authenticated")
- assert _contains_any(text, "engage", "engageable")
- # Distinguish from synthesized-answer surfaces in xurl's own terms.
- assert _contains_any(text, "summarized answer", "summary of a topic")
-
-
-
-
-def test_x_search_doc_separates_discovery_from_account_actions():
- text = _read(X_SEARCH_DOC)
- lowered = text.lower()
-
- assert "x_search" in lowered
- assert "xurl" in lowered
- # Explicit comparison section or equivalent boundary language.
- assert _contains_any(text, "vs `xurl`", "vs xurl", "two different x surfaces")
- assert _contains_any(text, "read-only public", "public x discovery")
- assert _contains_any(
- text,
- "posting",
- "replying",
- "liking",
- "dm",
- "media upload",
- "deleting",
- )
- assert _contains_any(
- text,
- "authenticated",
- "exact or authenticated",
- "account actions",
- "state-changing",
- )
- # Write confirmation must come from xurl / X API, not x_search.
- assert _contains_any(
- text,
- "confirmed by `xurl`",
- "xurl` output",
- "x api response",
- "never evidence",
- )
- assert _contains_any(text, "switch to the `xurl`", "switch to `xurl`", "xurl skill")
diff --git a/tests/test_atomic_replace_symlinks.py b/tests/test_atomic_replace_symlinks.py
index 797d2b3a12d..c67fdd236f3 100644
--- a/tests/test_atomic_replace_symlinks.py
+++ b/tests/test_atomic_replace_symlinks.py
@@ -313,6 +313,7 @@ def fast_replace_retries(monkeypatch: pytest.MonkeyPatch) -> None:
# ── cross-platform: the retry/fallback state machine ──────────────────────
@pytest.mark.parametrize("winerror", [5, 32, 33])
def test_contended_rename_retries_then_rewrites_in_place(
tmp_path: Path,
@@ -339,7 +340,6 @@ def test_contended_rename_retries_then_rewrites_in_place(
raise _sharing_error(winerror)
monkeypatch.setattr("utils.os.replace", always_contended)
- monkeypatch.setattr("utils._IS_WINDOWS", True)
assert Path(atomic_replace(tmp, target)) == target
assert len(attempts) == 1 + utils_mod._REPLACE_RETRY_ATTEMPTS
@@ -347,6 +347,7 @@ def test_contended_rename_retries_then_rewrites_in_place(
assert not tmp.exists()
def test_contended_rename_retry_wins_keeps_write_atomic(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None
) -> None:
@@ -369,7 +370,6 @@ def test_contended_rename_retry_wins_keeps_write_atomic(
raise AssertionError("no fallback may run when a retry succeeds")
monkeypatch.setattr("utils.os.replace", contended_twice)
- monkeypatch.setattr("utils._IS_WINDOWS", True)
monkeypatch.setattr("utils._rewrite_in_place", forbid)
monkeypatch.setattr("utils.shutil.copyfile", forbid)
@@ -379,6 +379,7 @@ def test_contended_rename_retry_wins_keeps_write_atomic(
assert not tmp.exists()
def test_genuine_denial_propagates_after_budget(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None
) -> None:
@@ -392,7 +393,6 @@ def test_genuine_denial_propagates_after_budget(
monkeypatch.setattr(
"utils.os.replace", MagicMock(side_effect=_sharing_error(5))
)
- monkeypatch.setattr("utils._IS_WINDOWS", True)
denial = PermissionError(errno.EACCES, "access is denied")
@@ -409,6 +409,7 @@ def test_genuine_denial_propagates_after_budget(
assert tmp.exists(), "the pending write must survive for the caller"
def test_contended_retry_switching_to_exdev_uses_copy_fallback(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None
) -> None:
@@ -422,7 +423,6 @@ def test_contended_retry_switching_to_exdev_uses_copy_fallback(
side_effect=[_sharing_error(5), OSError(errno.EXDEV, "cross-device")]
)
monkeypatch.setattr("utils.os.replace", replace)
- monkeypatch.setattr("utils._IS_WINDOWS", True)
def forbid_rewrite(*_a: object, **_k: object) -> None:
raise AssertionError("EXDEV must use the copy fallback, not a rewrite")
@@ -446,7 +446,6 @@ def test_non_contended_oserror_propagates_without_retry(
replace = MagicMock(side_effect=OSError(errno.ENOSPC, "no space"))
monkeypatch.setattr("utils.os.replace", replace)
- monkeypatch.setattr("utils._IS_WINDOWS", True)
with pytest.raises(OSError) as excinfo:
atomic_replace(tmp, target)
@@ -507,6 +506,7 @@ def test_in_place_rewrite_never_exposes_a_truncated_file(
assert observed == [5000]
@pytest.mark.require_symlinks
def test_symlinked_target_survives_a_contended_rename(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None
@@ -522,7 +522,6 @@ def test_symlinked_target_survives_a_contended_rename(
monkeypatch.setattr(
"utils.os.replace", MagicMock(side_effect=_sharing_error(5))
)
- monkeypatch.setattr("utils._IS_WINDOWS", True)
assert Path(atomic_replace(tmp, link)) == real
assert link.is_symlink(), "symlink must survive the rewrite fallback"
diff --git a/tests/test_batch_runner_checkpoint.py b/tests/test_batch_runner_checkpoint.py
index 899d35afe4f..81caef8384c 100644
--- a/tests/test_batch_runner_checkpoint.py
+++ b/tests/test_batch_runner_checkpoint.py
@@ -2,7 +2,6 @@
import json
from pathlib import Path
-from threading import Lock
import pytest
@@ -39,13 +38,6 @@ class TestSaveCheckpoint:
assert result["run_name"] == "test"
assert result["completed_prompts"] == [1, 2, 3]
- def test_adds_last_updated(self, runner):
- data = {"run_name": "test", "completed_prompts": []}
- runner._save_checkpoint(data)
-
- result = json.loads(runner.checkpoint_file.read_text())
- assert "last_updated" in result
- assert result["last_updated"] is not None
def test_overwrites_previous_checkpoint(self, runner):
runner._save_checkpoint({"run_name": "test", "completed_prompts": [1]})
@@ -54,13 +46,6 @@ class TestSaveCheckpoint:
result = json.loads(runner.checkpoint_file.read_text())
assert result["completed_prompts"] == [1, 2, 3]
- def test_with_lock(self, runner):
- lock = Lock()
- data = {"run_name": "test", "completed_prompts": [42]}
- runner._save_checkpoint(data, lock=lock)
-
- result = json.loads(runner.checkpoint_file.read_text())
- assert result["completed_prompts"] == [42]
def test_creates_parent_dirs(self, tmp_path):
@@ -101,51 +86,6 @@ class TestLoadCheckpoint:
assert isinstance(result, dict)
-class TestResumePreservesProgress:
- """Verify that initializing a run with resume=True loads prior checkpoint."""
-
- def test_completed_prompts_loaded_from_checkpoint(self, runner):
- # Simulate a prior run that completed prompts 0-4
- prior = {
- "run_name": "test_run",
- "completed_prompts": [0, 1, 2, 3, 4],
- "batch_stats": {"0": {"processed": 5}},
- "last_updated": "2026-01-01T00:00:00",
- }
- runner.checkpoint_file.write_text(json.dumps(prior))
-
- # Load checkpoint like run() does
- checkpoint_data = runner._load_checkpoint()
- if checkpoint_data.get("run_name") != runner.run_name:
- checkpoint_data = {
- "run_name": runner.run_name,
- "completed_prompts": [],
- "batch_stats": {},
- "last_updated": None,
- }
-
- completed_set = set(checkpoint_data.get("completed_prompts", []))
- assert completed_set == {0, 1, 2, 3, 4}
-
- def test_different_run_name_starts_fresh(self, runner):
- prior = {
- "run_name": "different_run",
- "completed_prompts": [0, 1, 2],
- "batch_stats": {},
- }
- runner.checkpoint_file.write_text(json.dumps(prior))
-
- checkpoint_data = runner._load_checkpoint()
- if checkpoint_data.get("run_name") != runner.run_name:
- checkpoint_data = {
- "run_name": runner.run_name,
- "completed_prompts": [],
- "batch_stats": {},
- "last_updated": None,
- }
-
- assert checkpoint_data["completed_prompts"] == []
- assert checkpoint_data["run_name"] == "test_run"
class TestBatchWorkerResumeBehavior:
@@ -226,65 +166,3 @@ class TestBatchWorkerResumeBehavior:
assert skipped_indices == [0]
-class TestFinalCheckpointNoDuplicates:
- """Regression: the final checkpoint must not contain duplicate prompt
- indices.
-
- Before PR #15161, `run()` populated `completed_prompts_set` incrementally
- as each batch completed, then at the end built `all_completed_prompts =
- list(completed_prompts_set)` AND extended it again with every batch's
- `completed_prompts` — double-counting every index.
- """
-
- def _simulate_final_aggregation_fixed(self, batch_results):
- """Mirror the fixed code path in batch_runner.run()."""
- completed_prompts_set = set()
- for result in batch_results:
- completed_prompts_set.update(result.get("completed_prompts", []))
- # This is what the fixed code now writes to the checkpoint:
- return sorted(completed_prompts_set)
-
- def test_no_duplicates_in_final_list(self):
- batch_results = [
- {"completed_prompts": [0, 1, 2]},
- {"completed_prompts": [3, 4]},
- {"completed_prompts": [5]},
- ]
- final = self._simulate_final_aggregation_fixed(batch_results)
- assert final == [0, 1, 2, 3, 4, 5]
- assert len(final) == len(set(final)) # no duplicates
-
- def test_persisted_checkpoint_has_unique_prompts(self, runner):
- """Write what run()'s fixed aggregation produces to disk; the file
- must load back with no duplicate indices."""
- batch_results = [
- {"completed_prompts": [0, 1]},
- {"completed_prompts": [2, 3]},
- ]
- final = self._simulate_final_aggregation_fixed(batch_results)
- runner._save_checkpoint({
- "run_name": runner.run_name,
- "completed_prompts": final,
- "batch_stats": {},
- })
- loaded = json.loads(runner.checkpoint_file.read_text())
- cp = loaded["completed_prompts"]
- assert cp == sorted(set(cp))
- assert len(cp) == 4
-
- def test_old_buggy_pattern_would_have_duplicates(self):
- """Document the bug this PR fixes: the old code shape produced
- duplicates. Kept as a sanity anchor so a future refactor that
- re-introduces the pattern is immediately visible."""
- completed_prompts_set = set()
- results = []
- for batch in ({"completed_prompts": [0, 1, 2]},
- {"completed_prompts": [3, 4]}):
- completed_prompts_set.update(batch["completed_prompts"])
- results.append(batch)
- # Buggy aggregation (pre-fix):
- buggy = list(completed_prompts_set)
- for br in results:
- buggy.extend(br.get("completed_prompts", []))
- # Every index appears twice
- assert len(buggy) == 2 * len(set(buggy))
diff --git a/tests/test_batch_runner_discard_resume.py b/tests/test_batch_runner_discard_resume.py
index 2b2dd982ec6..541f9463be1 100644
--- a/tests/test_batch_runner_discard_resume.py
+++ b/tests/test_batch_runner_discard_resume.py
@@ -15,7 +15,6 @@ import batch_runner
from batch_runner import (
BatchRunner,
_entry_prompt_text,
- _process_batch_worker,
)
@@ -37,19 +36,6 @@ def _discarded_result():
}
-def test_discard_writes_tombstone_row(tmp_path, monkeypatch):
- monkeypatch.setattr(
- "batch_runner._process_single_prompt", lambda *a, **kw: _discarded_result()
- )
-
- _process_batch_worker((1, [(0, {"prompt": "hi"})], tmp_path, set(), {"verbose": False}))
-
- batch_file = tmp_path / "batch_1.jsonl"
- rows = [json.loads(line) for line in batch_file.read_text(encoding="utf-8").splitlines() if line.strip()]
- assert len(rows) == 1
- assert rows[0]["discarded"] == "no_reasoning"
- assert rows[0]["prompt_index"] == 0
- assert rows[0]["prompt"] == "hi"
# ─────────────────────────────────────────────────────────────────────
diff --git a/tests/test_batch_runner_exit_code.py b/tests/test_batch_runner_exit_code.py
deleted file mode 100644
index 7329c4622c1..00000000000
--- a/tests/test_batch_runner_exit_code.py
+++ /dev/null
@@ -1,64 +0,0 @@
-"""Regression tests for batch_runner process exit codes.
-
-Python Fire serializes the return value of the wrapped function but does not
-use it as the process exit code. Before the fix, all of ``main``'s error paths
-returned ``0`` because a bare ``return`` or ``return 1`` was treated as the
-function result, not a non-zero exit status.
-"""
-
-import subprocess
-import sys
-from pathlib import Path
-
-import pytest
-
-
-REPO_ROOT = Path(__file__).parent.parent
-PYTHON = sys.executable
-
-
-def _run(*args):
- return subprocess.run(
- [PYTHON, "batch_runner.py", *args],
- cwd=REPO_ROOT,
- text=True,
- capture_output=True,
- )
-
-
-def test_missing_dataset_file_exits_nonzero():
- result = _run("--run_name=test")
- assert result.returncode == 1
- assert "--dataset_file is required" in result.stdout
-
-
-def test_invalid_batch_size_exits_nonzero():
- result = _run("--dataset_file=/tmp/data.jsonl", "--batch_size=-1", "--run_name=test")
- assert result.returncode == 1
- assert "--batch_size must be a positive integer" in result.stdout
-
-
-def test_invalid_reasoning_effort_exits_nonzero():
- result = _run(
- "--dataset_file=/tmp/data.jsonl",
- "--batch_size=1",
- "--run_name=test",
- "--reasoning_effort=invalid",
- )
- assert result.returncode == 1
- assert "--reasoning_effort must be one of" in result.stdout
-
-
-def test_invalid_prefill_messages_file_exits_nonzero(tmp_path):
- bad_prefill = tmp_path / "prefill.json"
- bad_prefill.write_text("not json", encoding="utf-8")
- result = _run(
- "--dataset_file=/tmp/data.jsonl",
- "--batch_size=1",
- "--run_name=test",
- f"--prefill_messages_file={bad_prefill}",
- )
- assert result.returncode == 1
- assert "Error loading prefill messages" in result.stdout
-
-
diff --git a/tests/test_credential_file_permissions.py b/tests/test_credential_file_permissions.py
index dd66b190a1e..73a98a3ad9c 100644
--- a/tests/test_credential_file_permissions.py
+++ b/tests/test_credential_file_permissions.py
@@ -59,24 +59,6 @@ class TestWarnIfCredentialFileBroadlyReadable:
)
assert caplog.text == ""
- def test_uses_provided_logger(self, tmp_path):
- f = tmp_path / "tokens.json"
- f.write_text("{}")
- f.chmod(0o644)
-
- records = []
-
- class _Sink(logging.Handler):
- def emit(self, record):
- records.append(record)
-
- log = logging.getLogger("test.credfile.sink")
- log.addHandler(_Sink())
- try:
- assert warn_if_credential_file_broadly_readable(f, log=log) is True
- finally:
- log.handlers.clear()
- assert records and "chmod 600" in records[0].getMessage()
class TestGoogleChatReadPathWarns:
diff --git a/tests/test_dispatch_session_id.py b/tests/test_dispatch_session_id.py
index 69a6e592f0a..72da90a4627 100644
--- a/tests/test_dispatch_session_id.py
+++ b/tests/test_dispatch_session_id.py
@@ -46,30 +46,4 @@ class TestSessionIdForwarding:
)
assert captured.get("session_id") == "sess-xyz"
- def test_session_id_default_is_none(self):
- """When session_id is omitted, dispatch receives None."""
- captured = {}
- with patch("model_tools.registry", _make_registry(captured)):
- from model_tools import handle_function_call
- handle_function_call(
- "web_search",
- {"query": "test"},
- task_id="t1",
- skip_pre_tool_call_hook=True,
- )
- assert "session_id" in captured
- assert captured["session_id"] is None
- def test_task_id_still_forwarded(self):
- """Existing task_id forwarding is not broken by this change."""
- captured = {}
- with patch("model_tools.registry", _make_registry(captured)):
- from model_tools import handle_function_call
- handle_function_call(
- "web_search",
- {"query": "test"},
- task_id="task-999",
- session_id="sess-1",
- skip_pre_tool_call_hook=True,
- )
- assert captured.get("task_id") == "task-999"
diff --git a/tests/test_engines_satisfiable.py b/tests/test_engines_satisfiable.py
index 8ce67810db8..06d6351e1f5 100644
--- a/tests/test_engines_satisfiable.py
+++ b/tests/test_engines_satisfiable.py
@@ -151,24 +151,6 @@ class TestEnginesAreSatisfiable:
"Hermes-managed install cannot run npm ci."
)
- def test_desktop_node_floor_is_not_stricter_than_its_toolchain(self):
- """apps/desktop must not demand more Node than its own build tools do.
-
- Vite is the real constraint (it needs `node:util.styleText`). Raising
- the desktop floor beyond it silently force-migrates every user's
- toolchain for no dependency reason.
- """
- desktop = json.loads((REPO_ROOT / "apps" / "desktop" / "package.json").read_text())
- node_range = desktop["engines"]["node"]
- # The tightest floor any dependency actually declares (react-router
- # 8.3.0 -> >=22.22.0). If this legitimately rises, the assertion
- # documents the reason for the bump rather than blocking it.
- assert _satisfies_range("22.22.0", node_range), (
- f"apps/desktop engines.node is {node_range!r}, which rejects Node "
- "22.12 — stricter than Vite requires. A desktop floor above the "
- "build toolchain's own floor replaces working user toolchains for "
- "nothing."
- )
class TestExcludedNpmBand:
@@ -274,24 +256,4 @@ class TestDeclaredFloorsClearTheLockedTree:
f"in scripts/install.ps1) or relax the dep. Violations: {violations}"
)
- def test_installer_gates_match_the_manifest_arms(self):
- """install.sh's node_satisfies_build must encode the same floors as
- engines.node — a laxer gate accepts a Node that npm then rejects."""
- node_range = _root_manifest()["engines"]["node"]
- install_sh = (REPO_ROOT / "scripts" / "install.sh").read_text()
- install_ps1 = (REPO_ROOT / "scripts" / "install.ps1").read_text()
- for arm in node_range.split("||"):
- arm = arm.strip()
- major, minor = _parse_major_minor_patch(arm.lstrip("^>="))[:2]
- if arm.startswith("^") and minor > 0:
- sh_gate = f'[ "$major" -eq {major} ] && [ "$minor" -ge {minor} ]'
- ps1_gate = f"if ($v.Major -eq {major}) {{ return ($v.Minor -ge {minor}) }}"
- assert sh_gate in install_sh, (
- f"engines.node arm {arm!r} has no matching gate in "
- f"install.sh node_satisfies_build (expected: {sh_gate})"
- )
- assert ps1_gate in install_ps1, (
- f"engines.node arm {arm!r} has no matching gate in "
- f"install.ps1 Test-NodeVersionOk (expected: {ps1_gate})"
- )
diff --git a/tests/test_fast_safe_load.py b/tests/test_fast_safe_load.py
index 875752e04b0..765694f0172 100644
--- a/tests/test_fast_safe_load.py
+++ b/tests/test_fast_safe_load.py
@@ -10,7 +10,7 @@ import io
import yaml
-from utils import fast_safe_load, _fast_yaml_loader
+from utils import fast_safe_load
_DOCS = [
@@ -33,21 +33,8 @@ def test_equivalent_to_safe_load_for_file_objects():
assert fast_safe_load(io.StringIO(doc)) == yaml.safe_load(io.StringIO(doc)), repr(doc)
-def test_empty_document_returns_none():
- # Callers rely on ``fast_safe_load(...) or {}`` — empty must be falsy.
- assert fast_safe_load("") is None
-def test_prefers_c_loader_when_available():
- loader = _fast_yaml_loader
- # If libyaml is compiled in, we must be using the C loader; otherwise the
- # pure-Python SafeLoader is an acceptable fallback. Either way it must be a
- # safe loader (never the unsafe full Loader).
- c_loader = getattr(yaml, "CSafeLoader", None)
- if c_loader is not None:
- assert loader is c_loader
- else:
- assert loader is yaml.SafeLoader
def test_rejects_arbitrary_python_objects_like_safe_load():
diff --git a/tests/test_get_tool_definitions_cache_isolation.py b/tests/test_get_tool_definitions_cache_isolation.py
index d8831044814..893a0844e4b 100644
--- a/tests/test_get_tool_definitions_cache_isolation.py
+++ b/tests/test_get_tool_definitions_cache_isolation.py
@@ -78,11 +78,6 @@ class TestQuietModeCacheIsolation:
"Eviction should keep the cache at the cap, not clear it or grow"
)
- def test_non_quiet_mode_does_not_use_cache(self):
- """Sanity: quiet_mode=False (TUI path) skips the cache entirely \u2014
- explains why the bug only hit Gateway."""
- model_tools.get_tool_definitions(quiet_mode=False)
- assert len(model_tools._tool_defs_cache) == 0
def test_concurrent_capacity_misses_evict_atomically(self, monkeypatch):
"""Two profile/toolset misses at capacity cannot race on eviction."""
diff --git a/tests/test_hermes_bootstrap.py b/tests/test_hermes_bootstrap.py
index c1ea9aaec7a..cca2a0fcc92 100644
--- a/tests/test_hermes_bootstrap.py
+++ b/tests/test_hermes_bootstrap.py
@@ -148,16 +148,6 @@ class TestPosixNoOp:
-class TestIdempotence:
- """Calling apply_windows_utf8_bootstrap() multiple times must be safe."""
-
- def test_second_call_returns_false(self):
- hb = _fresh_import()
- # First call already happened at import time.
- result = hb.apply_windows_utf8_bootstrap()
- assert result is False, (
- "Second call should return False (idempotent no-op)"
- )
@@ -339,13 +329,6 @@ class TestHardenImportPath:
class TestSuppressPlatformVerConsole:
"""suppress_platform_ver_console: stub applied on Windows, no-op on POSIX."""
- @pytest.mark.linux_only
- def test_noop_on_posix(self):
- import platform
- hb = _fresh_import()
- original = getattr(platform, "_syscmd_ver", None)
- hb.suppress_platform_ver_console()
- assert getattr(platform, "_syscmd_ver", None) is original
@pytest.mark.windows_only
def test_stub_applied_when_windows(self):
diff --git a/tests/test_hermes_constants.py b/tests/test_hermes_constants.py
index 02daf50301e..6254802a320 100644
--- a/tests/test_hermes_constants.py
+++ b/tests/test_hermes_constants.py
@@ -11,7 +11,6 @@ import hermes_constants
from hermes_platform.host import runtime as host_runtime
from hermes_platform.host import facts as host_facts
from hermes_constants import (
- VALID_REASONING_EFFORTS,
agent_browser_runnable,
find_hermes_node_executable,
find_node_executable,
@@ -79,61 +78,6 @@ class TestGetDefaultHermesRoot:
assert get_default_hermes_root() == local_appdata / "hermes"
- def test_result_memoised_until_env_or_home_changes(self, tmp_path, monkeypatch):
- """Repeated calls reuse the memo; HERMES_HOME / home changes invalidate.
-
- get_default_hermes_root() resolves HERMES_HOME against the native
- home (~80us of path resolution) and is called at 31+ sites — every
- _load_global_auth_store() (per provider row in the /model picker),
- kanban, backup, gateway, update. The memo is keyed on
- (native home, HERMES_HOME) compared for free each call.
- """
- # HERMES_HOME set to a Docker-profile path: every call resolves the
- # env path against the native home (the ~80us work the memo skips).
- docker_root = tmp_path / "opt" / "data"
- profile = docker_root / "profiles" / "coder"
- profile.mkdir(parents=True)
- monkeypatch.setenv("HERMES_HOME", str(profile))
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
-
- # Probe the expensive inner work: the memo check itself calls
- # _get_platform_default_hermes_home() on every call (even hits), so
- # count Path.resolve on the env path instead — only the actual
- # resolution branch pays it.
- resolve_calls = {"n": 0}
- orig_resolve = Path.resolve
-
- def counting_resolve(self, *a, **k):
- resolve_calls["n"] += 1
- return orig_resolve(self, *a, **k)
-
- monkeypatch.setattr(Path, "resolve", counting_resolve)
- # raising=False: on pre-fix code the memo attribute doesn't exist
- # (that IS the fix); the reset is a no-op there so the measured-work
- # assertion below fails genuinely instead of erroring.
- monkeypatch.setattr(
- hermes_constants, "_default_hermes_root_memo", None, raising=False
- )
-
- first = get_default_hermes_root()
- first_count = resolve_calls["n"]
- for _ in range(10):
- get_default_hermes_root()
- assert resolve_calls["n"] == first_count, (
- "repeated calls must be memo hits (no path resolution on hits), "
- f"resolve went {first_count} -> {resolve_calls['n']}"
- )
- assert first == docker_root
-
- # HERMES_HOME change invalidates the memo (fresh resolution).
- other_profile = docker_root / "profiles" / "writer"
- other_profile.mkdir(parents=True)
- monkeypatch.setenv("HERMES_HOME", str(other_profile))
- before = resolve_calls["n"]
- assert get_default_hermes_root() == docker_root
- assert resolve_calls["n"] > before, (
- "HERMES_HOME change must force a fresh resolution"
- )
@@ -419,13 +363,6 @@ class TestIsContainer:
assert host_runtime._root_mount_has_marker(str(container), markers) is True
assert host_runtime._root_mount_has_marker(str(tmp_path / "missing"), markers) is False
- def test_caches_result(self, monkeypatch):
- """Second call uses cached value without re-probing."""
- monkeypatch.setattr(host_runtime, "_container_detected", True)
- assert is_container() is True
- # Even if we make os.path.exists return False, cached value wins
- monkeypatch.setattr(os.path, "exists", lambda p: False)
- assert is_container() is True
class TestParseReasoningEffort:
@@ -449,15 +386,6 @@ class TestParseReasoningEffort:
"""Unrecognized strings fall back to the caller default (None)."""
assert parse_reasoning_effort(value) is None
- def test_known_supported_levels_are_documented(self):
- """Guard against silently dropping a documented level.
-
- The docstring promises "minimal", "low", "medium", "high", "xhigh",
- "max", "ultra". If someone removes one from VALID_REASONING_EFFORTS without
- updating the docstring, this test will fail and force the call out.
- """
- documented = {"minimal", "low", "medium", "high", "xhigh", "max", "ultra"}
- assert documented.issubset(set(VALID_REASONING_EFFORTS))
class TestResolvePerModelReasoningEffort:
@@ -597,11 +525,6 @@ class TestResolveReasoningConfig:
class TestReasoningOverridesDefaultConfig:
"""Tests for the agent.reasoning_overrides default config key (Task 2)."""
- def test_default_config_has_reasoning_overrides_key(self):
- """DEFAULT_CONFIG['agent'] contains 'reasoning_overrides' as an empty dict."""
- from hermes_cli.config import DEFAULT_CONFIG
- assert "reasoning_overrides" in DEFAULT_CONFIG["agent"]
- assert DEFAULT_CONFIG["agent"]["reasoning_overrides"] == {}
def test_spelling_tolerant_lookup_works_with_user_config(self):
@@ -757,23 +680,6 @@ class TestAgentBrowserRunnable:
- def test_version_probe_uses_windows_hide_flags(self, tmp_path, monkeypatch):
- good = self._stub(tmp_path, "agent-browser", "#!/bin/sh\necho hi\n")
- captured = []
-
- def fake_run(cmd, **kwargs):
- captured.append((cmd, kwargs))
- return SimpleNamespace(returncode=0)
-
- import hermes_cli._subprocess_compat as subprocess_compat
- import subprocess as subprocess_mod
-
- monkeypatch.setattr(subprocess_compat, "windows_hide_flags", lambda: 0x08000000)
- monkeypatch.setattr(subprocess_mod, "run", fake_run)
-
- assert agent_browser_runnable(str(good)) is True
- assert captured[0][0] == [str(good), "--version"]
- assert captured[0][1]["creationflags"] == 0x08000000
@@ -869,14 +775,13 @@ class TestWslPathTranslation:
assert hermes_constants.translate_cwd_for_wsl_backend("/home/alex") == "/home/alex"
class TestManagedNodeTreeInUse:
"""managed_node_tree_in_use() detects processes executing from the tree."""
def _install_fake_psutil(self, monkeypatch, procs):
import sys
- from types import SimpleNamespace
- monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
fake = SimpleNamespace(
process_iter=lambda fields: [
SimpleNamespace(info=info) for info in procs
@@ -884,11 +789,6 @@ class TestManagedNodeTreeInUse:
)
monkeypatch.setitem(sys.modules, "psutil", fake)
- def test_always_false_off_windows(self, tmp_path, monkeypatch):
- monkeypatch.setattr(hermes_constants.sys, "platform", "darwin")
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- assert hermes_constants.managed_node_tree_in_use() is False
-
def test_exe_under_node_dir_counts(self, tmp_path, monkeypatch):
home = tmp_path / "hermes"
(home / "node").mkdir(parents=True)
@@ -927,13 +827,20 @@ class TestManagedNodeTreeInUse:
def test_missing_psutil_is_false(self, tmp_path, monkeypatch):
import sys
- monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
# None in sys.modules makes `import psutil` raise ImportError.
monkeypatch.setitem(sys.modules, "psutil", None)
assert hermes_constants.managed_node_tree_in_use() is False
+def test_managed_node_tree_never_in_use_off_windows(tmp_path, monkeypatch):
+ """The psutil scan is Windows-only; POSIX hosts can swap the tree freely."""
+ (tmp_path / "node").mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ assert hermes_constants.managed_node_tree_in_use() is False
+
+
class _FakeUrlResponse:
def __init__(self, payload: bytes):
self._payload = payload
@@ -961,6 +868,7 @@ def _make_node_zip(major: int) -> tuple[str, bytes]:
return name, buf.getvalue()
class TestWindowsHealStageSwap:
"""_heal_managed_node_windows() must never destroy the live tree before
its replacement is fully staged, and must defer (return None) when the
@@ -971,7 +879,6 @@ class TestWindowsHealStageSwap:
):
import urllib.request
- monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
# Pin the native architecture to the x64 archive served by the fake index.
monkeypatch.setattr(host_facts, "native_arch", lambda: "amd64")
monkeypatch.setenv("HERMES_HOME", str(home))
@@ -1198,6 +1105,7 @@ class TestWindowsHealStageSwap:
assert fresh_backup.exists()
class TestHealAttemptFlagSemantics:
"""An in-use deferral must not record the once-per-process heal attempt,
so a later call can retry once the tree is free (#80926)."""
@@ -1206,7 +1114,6 @@ class TestHealAttemptFlagSemantics:
home = tmp_path / "hermes"
(home / "node").mkdir(parents=True)
(home / "node" / "node.exe").write_text("x", encoding="utf-8")
- monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)
calls = {"n": 0}
@@ -1227,7 +1134,6 @@ class TestHealAttemptFlagSemantics:
home = tmp_path / "hermes"
(home / "node").mkdir(parents=True)
(home / "node" / "node.exe").write_text("x", encoding="utf-8")
- monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)
calls = {"n": 0}
diff --git a/tests/test_hermes_home_key_cache.py b/tests/test_hermes_home_key_cache.py
index f421c188f82..e2ab6945716 100644
--- a/tests/test_hermes_home_key_cache.py
+++ b/tests/test_hermes_home_key_cache.py
@@ -55,18 +55,9 @@ class TestSameAnswerAsBefore:
(tmp_path / "real").mkdir()
assert hc.hermes_home_key(tmp_path / "real") == _uncached(tmp_path / "real")
- def test_second_call_returns_the_same_string(self, tmp_path):
- (tmp_path / "real").mkdir()
- first = hc.hermes_home_key(str(tmp_path / "real"))
- second = hc.hermes_home_key(str(tmp_path / "real"))
- assert first == second == _uncached(str(tmp_path / "real"))
class TestWhatGetsRemembered:
- def test_an_existing_path_is_remembered(self, tmp_path):
- (tmp_path / "real").mkdir()
- hc.hermes_home_key(str(tmp_path / "real"))
- assert len(hc._HOME_KEY_CACHE) == 1
def test_a_missing_path_is_not_remembered(self, tmp_path):
# The answer can change once the directory is created, for example
@@ -85,18 +76,7 @@ class TestWhatGetsRemembered:
# the first one was never stored.
assert before == after
- def test_different_paths_get_their_own_entries(self, tmp_path):
- for name in ("a", "b", "c"):
- (tmp_path / name).mkdir()
- hc.hermes_home_key(str(tmp_path / name))
- assert len(hc._HOME_KEY_CACHE) == 3
- def test_reset_clears_everything(self, tmp_path):
- (tmp_path / "real").mkdir()
- hc.hermes_home_key(str(tmp_path / "real"))
- assert hc._HOME_KEY_CACHE
- hc.reset_hermes_home_key_cache()
- assert hc._HOME_KEY_CACHE == {}
class TestHomeChanges:
diff --git a/tests/test_hermes_home_profile_warning.py b/tests/test_hermes_home_profile_warning.py
index 977010e0eea..3b665ded22b 100644
--- a/tests/test_hermes_home_profile_warning.py
+++ b/tests/test_hermes_home_profile_warning.py
@@ -55,7 +55,6 @@ class TestGetHermesHomeProfileWarning:
err = capsys.readouterr().err
assert err.count("HERMES_HOME fallback") == 1
assert "'coder'" in err
- assert "#18594" in err
# 3. One-shot: second and third calls don't re-warn
fresh_constants.get_hermes_home()
diff --git a/tests/test_hermes_logging.py b/tests/test_hermes_logging.py
index 7254170876a..7bb6b4aef1a 100644
--- a/tests/test_hermes_logging.py
+++ b/tests/test_hermes_logging.py
@@ -4,7 +4,6 @@ import logging
import os
import stat
import sys
-import threading
from pathlib import Path
from unittest.mock import patch
@@ -73,24 +72,12 @@ class TestSetupLogging:
assert log_dir == hermes_home / "logs"
assert log_dir.is_dir()
- def test_creates_agent_log_handler(self, hermes_home):
- hermes_logging.setup_logging(hermes_home=hermes_home)
- root = logging.getLogger()
-
- agent_handlers = [
- h for h in hermes_logging._queued_file_handlers
- if isinstance(h, RotatingFileHandler)
- and "agent.log" in getattr(h, "baseFilename", "")
- ]
- assert len(agent_handlers) == 1
- assert agent_handlers[0].level == logging.INFO
def test_idempotent_no_duplicate_handlers(self, hermes_home):
hermes_logging.setup_logging(hermes_home=hermes_home)
hermes_logging.setup_logging(hermes_home=hermes_home) # second call — should be no-op
- root = logging.getLogger()
agent_handlers = [
h for h in hermes_logging._queued_file_handlers
if isinstance(h, RotatingFileHandler)
@@ -273,7 +260,6 @@ class TestSetupLogging:
hermes_logging.setup_logging(hermes_home=hermes_home, log_level="WARNING")
- root = logging.getLogger()
agent_handlers = [
h for h in hermes_logging._queued_file_handlers
if isinstance(h, RotatingFileHandler)
@@ -286,27 +272,7 @@ class TestSetupLogging:
class TestGatewayMode:
"""setup_logging(mode='gateway') creates a filtered gateway.log."""
- def test_gateway_log_created(self, hermes_home):
- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gateway")
- root = logging.getLogger()
-
- gw_handlers = [
- h for h in hermes_logging._queued_file_handlers
- if isinstance(h, RotatingFileHandler)
- and "gateway.log" in getattr(h, "baseFilename", "")
- ]
- assert len(gw_handlers) == 1
-
- def test_gateway_log_not_created_in_cli_mode(self, hermes_home):
- hermes_logging.setup_logging(hermes_home=hermes_home, mode="cli")
- root = logging.getLogger()
- gw_handlers = [
- h for h in hermes_logging._queued_file_handlers
- if isinstance(h, RotatingFileHandler)
- and "gateway.log" in getattr(h, "baseFilename", "")
- ]
- assert len(gw_handlers) == 0
@@ -346,16 +312,6 @@ class TestGatewayMode:
class TestGuiMode:
"""setup_logging(mode='gui') creates a filtered gui.log."""
- def test_gui_log_created(self, hermes_home):
- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gui")
- root = logging.getLogger()
-
- gui_handlers = [
- h for h in hermes_logging._queued_file_handlers
- if isinstance(h, RotatingFileHandler)
- and "gui.log" in getattr(h, "baseFilename", "")
- ]
- assert len(gui_handlers) == 1
def test_gui_log_receives_only_gui_components(self, hermes_home):
@@ -399,23 +355,6 @@ class TestSessionContext:
-class TestComponentFilter:
- """Unit tests for _ComponentFilter."""
-
- def test_passes_matching_prefix(self):
- f = hermes_logging._ComponentFilter(("gateway",))
- record = logging.LogRecord(
- "gateway.run", logging.INFO, "", 0, "msg", (), None
- )
- assert f.filter(record) is True
-
-
- def test_blocks_non_matching(self):
- f = hermes_logging._ComponentFilter(("gateway",))
- record = logging.LogRecord(
- "tools.terminal_tool", logging.INFO, "", 0, "msg", (), None
- )
- assert f.filter(record) is False
@@ -466,29 +405,6 @@ class TestAddRotatingHandler:
assert len(rotating_handlers) == 1
# Clean up
- def test_no_session_filter_on_handler(self, tmp_path):
- """Handlers rely on record factory, not per-handler _SessionFilter."""
- log_path = tmp_path / "no_session_filter.log"
- logger = logging.getLogger("_test_no_session_filter")
- formatter = logging.Formatter("%(session_tag)s%(message)s")
-
- hermes_logging._add_rotating_handler(
- log_path,
- level=logging.INFO, max_bytes=1024, backup_count=1,
- formatter=formatter,
- )
-
- handlers = [h for h in hermes_logging._queued_file_handlers if isinstance(h, RotatingFileHandler)]
- assert len(handlers) == 1
- # No _SessionFilter on the handler — record factory handles it
- assert len(handlers[0].filters) == 0
-
- # But session_tag still works (via record factory)
- hermes_logging.set_session_context("factory_test")
- logger.info("test msg")
- hermes_logging.flush_log_queue()
- content = log_path.read_text()
- assert "[factory_test]" in content
# Clean up
def test_managed_mode_initial_open_sets_group_writable(self, tmp_path):
@@ -727,7 +643,6 @@ class TestExternalRotationRecovery:
def test_eio_from_file_handler_names_the_path_once_then_recovers(tmp_path, capsys):
"""A failing log destination is named once (no per-record traceback) and writes resume
once the file is reachable again."""
- import io
class _SickStream(io.TextIOBase):
def writable(self):
@@ -762,7 +677,6 @@ def test_eio_from_file_handler_names_the_path_once_then_recovers(tmp_path, capsy
def test_eio_after_successful_reopen_still_names_the_path_once(tmp_path, capsys):
"""The reported case: open() succeeds but every write/seek/flush raises EIO. Reopening must
not re-arm the notice, or a stuck device prints the path once per record."""
- import io
class _SickStream(io.TextIOBase):
def writable(self):
@@ -797,7 +711,6 @@ class TestSafeStderr:
def test_wraps_non_utf8_stderr(self, monkeypatch):
"""On non-UTF-8 systems (e.g. Windows cp949), wraps stderr with UTF-8."""
- import io
class FakeStderr:
"""Simulates a Windows stderr with legacy encoding."""
@@ -818,57 +731,5 @@ class TestSafeStderr:
assert result.encoding == "utf-8"
assert result.errors == "replace"
- def test_handler_emits_unicode_without_crash(self, tmp_path):
- """StreamHandler with _safe_stderr can emit Unicode messages."""
- import io
- # Create a stderr-like stream with ASCII encoding
- class AsciiStream:
- encoding = "ascii"
- buffer = io.BytesIO()
-
- def write(self, s):
- self.buffer.write(s.encode("ascii", errors="replace"))
- def flush(self):
- pass
-
- # Without the fix, this would crash on cp949/ASCII stderr.
- # With the wrapper, the em-dash is replaced with '?'
- handler = logging.StreamHandler(
- io.TextIOWrapper(
- io.BytesIO(),
- encoding="utf-8",
- errors="replace",
- )
- )
- handler.setFormatter(logging.Formatter("%(message)s"))
- logger = logging.getLogger("_test_unicode")
- logger.addHandler(handler)
- logger.setLevel(logging.DEBUG)
- try:
- # Em-dash U+2014 — the exact character from the bug report
- logger.info("Session hygiene: 400 messages — auto-compressing")
- finally:
- logger.removeHandler(handler)
-
-
-class TestAsyncQueueLogging:
- """File logging runs through a QueueListener so emits never block on the
- cross-process rotation lock (Windows event-loop-stall fix)."""
-
- def test_file_handlers_not_on_root(self, hermes_home):
- hermes_logging.setup_logging(hermes_home=hermes_home)
- root = logging.getLogger()
- # Rotating file handlers live on the async listener, never on root.
- assert not any(isinstance(h, RotatingFileHandler) for h in root.handlers)
- # Exactly one queue handler funnels records to the listener.
- queue_handlers = [
- h for h in root.handlers if getattr(h, "_hermes_queue", False)
- ]
- assert len(queue_handlers) == 1
- # The real file handlers are discoverable via the accessor.
- assert any(
- "agent.log" in getattr(h, "baseFilename", "")
- for h in hermes_logging._queued_file_handlers
- )
diff --git a/tests/test_ipv4_preference.py b/tests/test_ipv4_preference.py
index fd8ce8c45c8..d850c3c2f9f 100644
--- a/tests/test_ipv4_preference.py
+++ b/tests/test_ipv4_preference.py
@@ -24,13 +24,6 @@ class TestApplyIPv4Preference:
socket.getaddrinfo = self._original
- def test_patches_getaddrinfo_when_forced(self):
- """Patches socket.getaddrinfo when force=True."""
- from hermes_constants import apply_ipv4_preference
- original = socket.getaddrinfo
- apply_ipv4_preference(force=True)
- assert socket.getaddrinfo is not original
- assert getattr(socket.getaddrinfo, "_hermes_ipv4_patched", False) is True
def test_double_patch_is_safe(self):
"""Calling apply twice doesn't double-wrap."""
@@ -45,7 +38,6 @@ class TestApplyIPv4Preference:
from hermes_constants import apply_ipv4_preference
calls = []
- original = socket.getaddrinfo
def mock_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
calls.append(family)
@@ -63,7 +55,6 @@ class TestApplyIPv4Preference:
from hermes_constants import apply_ipv4_preference
calls = []
- original = socket.getaddrinfo
def mock_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
calls.append(family)
diff --git a/tests/test_live_system_guard_self_test.py b/tests/test_live_system_guard_self_test.py
index 448389ea73a..9229b0ed8ae 100644
--- a/tests/test_live_system_guard_self_test.py
+++ b/tests/test_live_system_guard_self_test.py
@@ -94,13 +94,6 @@ def test_fail_closed_probe_reports_guard_active():
assert _live_system_guard_is_active() is True
-def test_fail_closed_probe_classifies_raw_builtin_as_unguarded():
- """The probe's discriminator, exercised against real objects: a raw C
- builtin the guard never touches (``os.getpid``) is exactly what an
- unguarded ``os.kill`` looks like and must read as 'guard not active', while
- the loaded guard's ``os.kill`` is a plain Python function."""
- assert isinstance(os.getpid, types.BuiltinFunctionType)
- assert not isinstance(os.kill, types.BuiltinFunctionType)
# ──────────────────── kill primitives ─────────────────────────
@@ -155,9 +148,6 @@ def test_subprocess_run_bash_c_systemctl_blocked():
subprocess.run(["bash", "-c", "systemctl --user restart hermes-gateway"])
-def test_subprocess_run_sh_c_systemctl_blocked():
- with pytest.raises(RuntimeError, match="live-system guard"):
- subprocess.run(["sh", "-c", "systemctl --user stop hermes-gateway"])
def test_subprocess_run_setsid_systemctl_blocked():
@@ -260,9 +250,6 @@ def test_subprocess_pkill_hermes_blocked():
subprocess.run(["pkill", "-f", "hermes"])
-def test_subprocess_pkill_hermes_gateway_blocked():
- with pytest.raises(RuntimeError, match="live-system guard"):
- subprocess.run(["pkill", "-f", "hermes-gateway"])
def test_subprocess_pkill_python_dash_f_blocked():
diff --git a/tests/test_managed_runtime_resolution.py b/tests/test_managed_runtime_resolution.py
index 9440da66913..66a548c5711 100644
--- a/tests/test_managed_runtime_resolution.py
+++ b/tests/test_managed_runtime_resolution.py
@@ -31,7 +31,6 @@ import json
import os
from pathlib import Path
-import pytest
REPO_ROOT = Path(__file__).resolve().parents[1]
MODULE_MARKER = "<module>"
@@ -246,7 +245,8 @@ def _is_packaging_copy(top_level: str) -> bool:
return (candidate / "PKG-INFO").exists()
-def _findings() -> list[tuple[str, str, int]]:
[email protected]_cache(maxsize=None)
+def _findings() -> tuple[tuple[str, str, int], ...]:
"""Return (relpath, command, lineno) for every bare managed lookup."""
found: list[tuple[str, str, int]] = []
for path in _source_files():
@@ -263,10 +263,11 @@ def _findings() -> list[tuple[str, str, int]]:
rel = path.relative_to(REPO_ROOT).as_posix()
for command, lineno in _iter_which_calls(tree):
found.append((rel, command, lineno))
- return found
+ return tuple(found)
-def _resolution_sites() -> set[tuple[str, str, str]]:
[email protected]_cache(maxsize=None)
+def _resolution_sites() -> frozenset[tuple[str, str, str]]:
"""Return (path, symbol, kind) for the resolution sites under review."""
sites: set[tuple[str, str, str]] = set()
for path in _source_files():
@@ -283,7 +284,7 @@ def _resolution_sites() -> set[tuple[str, str, str]]:
continue
visitor = _ResolutionSiteVisitor(tree)
sites.update((rel, symbol, kind) for symbol, kind in visitor.sites)
- return sites
+ return frozenset(sites)
def _resolution_allowlist() -> set[tuple[str, str, str]]:
@@ -353,25 +354,5 @@ def test_allowlist_has_no_stale_entries():
)
- "helper",
- [
- "find_node_executable",
- "find_hermes_node_executable",
- "iter_hermes_node_dirs",
- "with_hermes_node_path",
- ],
-)
-def test_managed_node_helpers_exist(helper):
- """The alternatives this guard points contributors at must be importable."""
- import hermes_constants
-
- assert callable(getattr(hermes_constants, helper))
-
-def test_managed_uv_helpers_exist():
- from hermes_cli.managed_uv import ensure_uv, managed_uv_path, resolve_uv
- assert callable(resolve_uv)
- assert callable(ensure_uv)
- assert managed_uv_path().parent.name == "bin"
diff --git a/tests/test_mcp_serve.py b/tests/test_mcp_serve.py
index a1f2c20bd22..232f73e8500 100644
--- a/tests/test_mcp_serve.py
+++ b/tests/test_mcp_serve.py
@@ -272,16 +272,6 @@ def fake_mcp_server(populated_sessions_dir, mock_session_db, monkeypatch):
# 1. UNIT TESTS — helpers, extraction, attachments
# ---------------------------------------------------------------------------
-class TestImports:
- def test_import_module(self):
- import mcp_serve
- assert hasattr(mcp_serve, "create_mcp_server")
- assert hasattr(mcp_serve, "run_mcp_server")
- assert hasattr(mcp_serve, "EventBridge")
-
- def test_mcp_available_flag(self):
- import mcp_serve
- assert isinstance(mcp_serve._MCP_SERVER_AVAILABLE, bool)
class TestHelpers:
@@ -389,11 +379,6 @@ class TestAttachmentExtraction:
# ---------------------------------------------------------------------------
class TestEventBridge:
- def test_create(self):
- from mcp_serve import EventBridge
- b = EventBridge()
- assert b._cursor == 0
- assert b._queue == []
def test_enqueue_and_poll(self):
from mcp_serve import EventBridge, QueueEvent
@@ -414,20 +399,7 @@ class TestEventBridge:
assert len(r["events"]) == 2
assert r["events"][0]["session_key"] == "s3"
- def test_session_filter(self):
- from mcp_serve import EventBridge, QueueEvent
- b = EventBridge()
- b._enqueue(QueueEvent(cursor=0, type="message", session_key="a"))
- b._enqueue(QueueEvent(cursor=0, type="message", session_key="b"))
- b._enqueue(QueueEvent(cursor=0, type="message", session_key="a"))
- r = b.poll_events(after_cursor=0, session_key="a")
- assert len(r["events"]) == 2
- def test_poll_empty(self):
- from mcp_serve import EventBridge
- r = EventBridge().poll_events(after_cursor=0)
- assert r["events"] == []
- assert r["next_cursor"] == 0
def test_poll_limit(self):
from mcp_serve import EventBridge, QueueEvent
@@ -775,14 +747,6 @@ class TestE2EEventsWait:
assert result["event"] is not None
assert result["event"]["content"] == "waiting for this"
- def test_wait_caps_timeout(self, mcp_server_e2e, _event_loop):
- """Timeout should be capped at 300000ms (5 min)."""
- from mcp_serve import QueueEvent
- server, bridge = mcp_server_e2e
- bridge._enqueue(QueueEvent(cursor=0, type="message", session_key="t"))
- # Even with huge timeout, should return immediately since event exists
- result = _run_tool(server, "events_wait", {"timeout_ms": 999999})
- assert result["event"] is not None
class TestMCPToolParameterCoercion:
def test_conversations_list_coerces_string_limit(self, fake_mcp_server, _event_loop):
@@ -834,18 +798,6 @@ class TestE2EMessagesSend:
result = _run_tool(server, "messages_send", {"target": "", "message": "hi"})
assert "error" in result
- def test_send_delegates_to_tool(self, mcp_server_e2e, _event_loop, monkeypatch):
- server, _ = mcp_server_e2e
- mock = MagicMock(return_value=json.dumps({"success": True, "platform": "telegram"}))
- monkeypatch.setattr("tools.send_message_tool.send_message_tool", mock)
-
- result = _run_tool(server, "messages_send",
- {"target": "telegram:123456", "message": "Hello!"})
- assert result["success"] is True
- mock.assert_called_once()
- call_args = mock.call_args[0][0]
- assert call_args["action"] == "send"
- assert call_args["target"] == "telegram:123456"
class TestE2EChannelsList:
@@ -962,18 +914,6 @@ class TestE2EPermissions:
# ---------------------------------------------------------------------------
class TestToolRegistration:
- def test_all_tools_registered(self, mcp_server_e2e, _event_loop):
- server, _ = mcp_server_e2e
- tools = server._tool_manager.list_tools()
- tool_names = {t.name for t in tools}
-
- expected = {
- "conversations_list", "conversation_get", "messages_read",
- "attachments_fetch", "events_poll", "events_wait",
- "messages_send", "channels_list",
- "permissions_list_open", "permissions_respond",
- }
- assert expected == tool_names, f"Missing: {expected - tool_names}, Extra: {tool_names - expected}"
def test_tools_have_descriptions(self, mcp_server_e2e, _event_loop):
server, _ = mcp_server_e2e
@@ -986,18 +926,7 @@ class TestToolRegistration:
# ---------------------------------------------------------------------------
class TestServerCreation:
- @pytest.mark.usefixtures("require_mcp_2_sdk")
- def test_create_server(self, populated_sessions_dir, monkeypatch):
- import mcp_serve
- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: populated_sessions_dir)
- assert mcp_serve.create_mcp_server() is not None
- @pytest.mark.usefixtures("require_mcp_2_sdk")
- def test_create_with_bridge(self, populated_sessions_dir, monkeypatch):
- import mcp_serve
- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: populated_sessions_dir)
- bridge = mcp_serve.EventBridge()
- assert mcp_serve.create_mcp_server(event_bridge=bridge) is not None
def test_create_without_mcp_sdk(self, monkeypatch):
import mcp_serve
@@ -1016,30 +945,7 @@ class TestRunMcpServer:
class TestCliIntegration:
- def test_parse_serve(self):
- import argparse
- parser = argparse.ArgumentParser()
- subs = parser.add_subparsers(dest="command")
- mcp_p = subs.add_parser("mcp")
- mcp_sub = mcp_p.add_subparsers(dest="mcp_action")
- serve_p = mcp_sub.add_parser("serve")
- serve_p.add_argument("-v", "--verbose", action="store_true")
-
- args = parser.parse_args(["mcp", "serve"])
- assert args.mcp_action == "serve"
- assert args.verbose is False
-
- def test_parse_serve_verbose(self):
- import argparse
- parser = argparse.ArgumentParser()
- subs = parser.add_subparsers(dest="command")
- mcp_p = subs.add_parser("mcp")
- mcp_sub = mcp_p.add_subparsers(dest="mcp_action")
- serve_p = mcp_sub.add_parser("serve")
- serve_p.add_argument("-v", "--verbose", action="store_true")
- args = parser.parse_args(["mcp", "serve", "--verbose"])
- assert args.verbose is True
def test_dispatcher_routes_serve(self, monkeypatch, tmp_path):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -1058,11 +964,6 @@ class TestCliIntegration:
# ---------------------------------------------------------------------------
class TestEdgeCases:
- def test_empty_sessions_json(self, sessions_dir, monkeypatch):
- (sessions_dir / "sessions.json").write_text("{}")
- import mcp_serve
- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)
- assert mcp_serve._load_sessions_index() == {}
def test_sessions_without_origin(self, sessions_dir, monkeypatch):
data = {"agent:main:telegram:dm:111": {
@@ -1077,16 +978,7 @@ class TestEdgeCases:
entries = mcp_serve._load_sessions_index()
assert entries["agent:main:telegram:dm:111"]["platform"] == "telegram"
- def test_bridge_start_stop(self):
- from mcp_serve import EventBridge
- b = EventBridge()
- assert not b._running
- b._running = True
- b.stop()
- assert not b._running
- def test_truncation(self):
- assert len(("x" * 5000)[:2000]) == 2000
# ---------------------------------------------------------------------------
@@ -1419,7 +1311,3 @@ class TestEventBridgePollE2E:
assert events[0]["session_key"] == "agent:main:telegram:dm:fresh"
assert events[0]["content"] == "hello after baseline"
- def test_poll_interval_is_200ms(self):
- """Verify the poll interval constant."""
- from mcp_serve import POLL_INTERVAL
- assert POLL_INTERVAL == 0.2
diff --git a/tests/test_mini_swe_runner.py b/tests/test_mini_swe_runner.py
index 16ef2628610..ae5e974a56e 100644
--- a/tests/test_mini_swe_runner.py
+++ b/tests/test_mini_swe_runner.py
@@ -32,29 +32,3 @@ def test_run_task_kimi_omits_temperature():
assert "temperature" not in client.chat.completions.create.call_args.kwargs
-def test_run_task_public_moonshot_kimi_k2_5_omits_temperature():
- """kimi-k2.5 on the public Moonshot API should not get a forced temperature."""
- with patch("openai.OpenAI") as mock_openai:
- client = MagicMock()
- client.base_url = "https://api.moonshot.ai/v1"
- client.chat.completions.create.return_value = SimpleNamespace(
- choices=[SimpleNamespace(message=SimpleNamespace(content="done", tool_calls=[]))]
- )
- mock_openai.return_value = client
-
- from mini_swe_runner import MiniSWERunner
-
- runner = MiniSWERunner(
- model="kimi-k2.5",
- base_url="https://api.moonshot.ai/v1",
- api_key="test-key",
- env_type="local",
- max_iterations=1,
- )
- runner._create_env = MagicMock()
- runner._cleanup_env = MagicMock()
-
- result = runner.run_task("2+2")
-
- assert result["completed"] is True
- assert "temperature" not in client.chat.completions.create.call_args.kwargs
diff --git a/tests/test_model_tools_async_bridge.py b/tests/test_model_tools_async_bridge.py
index 54fce36d2e1..76a56d01315 100644
--- a/tests/test_model_tools_async_bridge.py
+++ b/tests/test_model_tools_async_bridge.py
@@ -47,28 +47,7 @@ async def _create_and_return_transport():
class TestRunAsyncLoopLifecycle:
"""Verify _run_async() keeps the event loop alive after returning."""
- def test_loop_not_closed_after_run_async(self):
- """The loop used by _run_async must still be open after the call."""
- from model_tools import _run_async
-
- loop = _run_async(_get_current_loop())
-
- assert not loop.is_closed(), (
- "_run_async() closed the event loop — cached async clients will "
- "crash with 'Event loop is closed' on GC (issue #2104)"
- )
-
- def test_same_loop_reused_across_calls(self):
- """Consecutive _run_async calls should reuse the same loop."""
- from model_tools import _run_async
- loop1 = _run_async(_get_current_loop())
- loop2 = _run_async(_get_current_loop())
-
- assert loop1 is loop2, (
- "_run_async() created a new loop on the second call — cached "
- "async clients from the first call would be orphaned"
- )
def test_cached_transport_survives_between_calls(self):
"""A transport/future created in call 1 must be valid in call 2."""
@@ -87,24 +66,6 @@ class TestRunAsyncLoopLifecycle:
class TestRunAsyncWorkerThread:
"""Verify worker threads get persistent per-thread loops (delegate_task fix)."""
- def test_worker_thread_loop_not_closed(self):
- """A worker thread's loop must stay open after _run_async returns,
- so cached httpx/AsyncOpenAI clients don't crash on GC."""
- from concurrent.futures import ThreadPoolExecutor
- from model_tools import _run_async
-
- def _run_on_worker():
- loop = _run_async(_get_current_loop())
- still_open = not loop.is_closed()
- return loop, still_open
-
- with ThreadPoolExecutor(max_workers=1) as pool:
- loop, still_open = pool.submit(_run_on_worker).result()
-
- assert still_open, (
- "Worker thread's event loop was closed after _run_async — "
- "cached async clients will crash with 'Event loop is closed'"
- )
def test_worker_thread_reuses_loop_across_calls(self):
"""Multiple _run_async calls on the same worker thread should
@@ -352,49 +313,6 @@ class TestVisionDispatchLoopSafety:
verify the event loop stays alive afterwards — the exact scenario
from issue #2104."""
- def test_vision_dispatch_keeps_loop_alive(self, tmp_path):
- """After dispatching vision_analyze via the registry, the event
- loop must remain open so cached async clients don't crash on GC."""
- from model_tools import _get_tool_loop
- from tools.registry import registry
-
- fake_response = _mock_vision_response()
-
- with (
- patch(
- "tools.vision_tools.async_call_llm",
- new_callable=AsyncMock,
- return_value=fake_response,
- ),
- patch(
- "tools.vision_tools._download_image",
- new_callable=AsyncMock,
- side_effect=lambda url, dest, **kw: _write_fake_image(dest),
- ),
- patch(
- "tools.vision_tools._validate_image_url_async",
- new_callable=AsyncMock,
- return_value=True,
- ),
- patch(
- "tools.vision_tools._image_to_base64_data_url",
- return_value="data:image/jpeg;base64,abc",
- ),
- ):
- result_json = registry.dispatch(
- "vision_analyze",
- {"image_url": "https://example.com/cat.png", "question": "What is this?"},
- )
-
- result = json.loads(result_json)
- assert result.get("success") is True, f"dispatch failed: {result}"
- assert "cat" in result.get("analysis", "").lower()
-
- loop = _get_tool_loop()
- assert not loop.is_closed(), (
- "Event loop closed after vision_analyze dispatch — cached async "
- "clients will crash with 'Event loop is closed' (issue #2104)"
- )
def test_two_consecutive_vision_dispatches(self, tmp_path):
"""Two back-to-back vision_analyze dispatches must both succeed
diff --git a/tests/test_packaging_build_guard.py b/tests/test_packaging_build_guard.py
index 0b169f76ed8..eb45831b642 100644
--- a/tests/test_packaging_build_guard.py
+++ b/tests/test_packaging_build_guard.py
@@ -3,8 +3,6 @@
import os
import subprocess
import sys
-import tarfile
-import zipfile
from pathlib import Path
import pytest
@@ -63,34 +61,3 @@ def test_artifact_build_rejects_nix_development_shell_environment(kind, tmp_path
assert "Building wheels or sdists for hermes-agent is not supported" in result.stderr
- ("kind", "artifact_glob"),
- [("sdist", "hermes_agent-*.tar.gz"), ("wheel", "hermes_agent-*.whl")],
-)
-def test_artifact_build_allows_explicit_nix_package_build_marker(kind, artifact_glob, tmp_path):
- result = _build_artifact(kind, tmp_path, nix_build=True)
-
- assert result.returncode == 0, result.stderr
- artifacts = list(tmp_path.glob(artifact_glob))
- assert artifacts
-
- expected = {
- path.relative_to(PROJECT_ROOT).as_posix()
- for pattern in ("plugin.yaml", "plugin.yml")
- for path in (PROJECT_ROOT / "plugins").rglob(pattern)
- }
- assert expected, "expected bundled plugin manifests under plugins/"
-
- if kind == "wheel":
- with zipfile.ZipFile(artifacts[0]) as wheel:
- shipped = set(wheel.namelist())
- else:
- with tarfile.open(artifacts[0]) as sdist:
- shipped = {
- name.split("/", 1)[1]
- for name in sdist.getnames()
- if "/" in name
- }
-
- missing = sorted(expected - shipped)
- assert not missing, f"{kind} omits bundled plugin manifests: {missing}"
diff --git a/tests/test_packaging_metadata.py b/tests/test_packaging_metadata.py
index 1c87155d3e5..72fb5862671 100644
--- a/tests/test_packaging_metadata.py
+++ b/tests/test_packaging_metadata.py
@@ -1,4 +1,3 @@
-import ast
import re
import tomllib
from pathlib import Path
@@ -46,14 +45,6 @@ def test_packaging_declared_as_core_dependency():
)
-def test_faster_whisper_is_not_a_base_dependency():
- data = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8"))
- deps = data["project"]["dependencies"]
-
- assert not any(dep.startswith("faster-whisper") for dep in deps)
-
- voice_extra = data["project"]["optional-dependencies"]["voice"]
- assert any(dep.startswith("faster-whisper") for dep in voice_extra)
# Minimum non-vulnerable Starlette: CVE-2026-48710 ("BadHost") was fixed in
@@ -209,31 +200,6 @@ def _pyproject_pinned_specs():
return specs
-def _lazy_deps_pinned_specs():
- """Extract every string literal inside the LAZY_DEPS dict via AST.
-
- Parsing rather than importing keeps this test free of
- tools/lazy_deps.py's runtime imports and side effects.
- """
- src = (REPO_ROOT / "tools" / "lazy_deps.py").read_text(encoding="utf-8")
- tree = ast.parse(src)
- specs: list[str] = []
- for node in ast.walk(tree):
- if isinstance(node, ast.Assign):
- targets = node.targets
- elif isinstance(node, ast.AnnAssign):
- targets = [node.target]
- else:
- continue
- if not any(isinstance(t, ast.Name) and t.id == "LAZY_DEPS" for t in targets):
- continue
- for sub in ast.walk(node.value):
- if isinstance(sub, ast.Constant) and isinstance(sub.value, str):
- specs.append(sub.value)
- assert specs, "could not extract specs from LAZY_DEPS — the AST parser drifted"
- return specs
-
-
def test_pyproject_pins_are_internally_consistent():
"""No package may be exact-pinned to two different versions in pyproject.
@@ -345,35 +311,10 @@ def test_build_system_requires_wheel_for_isolated_builds():
def _lazy_deps_by_feature():
- """Parse LAZY_DEPS into {feature_name: [spec, ...]} via AST.
+ """{feature_name: [spec, ...]} from the runtime LAZY_DEPS allowlist."""
+ from tools.lazy_deps import LAZY_DEPS
- Same parse-don't-import rationale as _lazy_deps_pinned_specs, but keeps the
- feature -> specs grouping so per-feature coverage can be asserted.
- """
- src = (REPO_ROOT / "tools" / "lazy_deps.py").read_text(encoding="utf-8")
- tree = ast.parse(src)
- for node in ast.walk(tree):
- targets = (
- node.targets if isinstance(node, ast.Assign)
- else [node.target] if isinstance(node, ast.AnnAssign)
- else []
- )
- if not any(isinstance(t, ast.Name) and t.id == "LAZY_DEPS" for t in targets):
- continue
- if not isinstance(node.value, ast.Dict):
- continue
- by_feature: dict[str, list[str]] = {}
- for key, value in zip(node.value.keys, node.value.values):
- if not (isinstance(key, ast.Constant) and isinstance(key.value, str)):
- continue
- by_feature[key.value] = [
- sub.value
- for sub in ast.walk(value)
- if isinstance(sub, ast.Constant) and isinstance(sub.value, str)
- ]
- assert by_feature, "could not extract features from LAZY_DEPS — AST parser drifted"
- return by_feature
- raise AssertionError("LAZY_DEPS dict literal not found in tools/lazy_deps.py")
+ return {feature: list(specs) for feature, specs in LAZY_DEPS.items()}
# Security-critical packages whose patched floor must be enforced on EVERY
@@ -472,13 +413,3 @@ def test_termux_install_paths_never_request_uvloop():
assert "uvloop" not in _extra_closure(extras, profile), profile
-def test_all_extra_keeps_uvloop_opt_in_off_android():
- """``[all]`` still ships the libuv loop, but only where it can build."""
- project = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]
- extras = project["optional-dependencies"]
- assert "uvloop" in _extra_closure(extras, "all")
- (spec,) = extras["uvloop"]
- marker = spec.split(";", 1)[1]
- assert _distribution_name(spec) == "uvloop"
- for platform in ("win32", "cygwin", "android"):
- assert f"sys_platform != '{platform}'" in marker, marker
diff --git a/tests/test_project_metadata.py b/tests/test_project_metadata.py
index 209a9b4e851..9f5d2c1769c 100644
--- a/tests/test_project_metadata.py
+++ b/tests/test_project_metadata.py
@@ -17,31 +17,6 @@ def _load_package_data():
return tool["setuptools"]["package-data"]
-def test_matrix_extra_not_in_all():
- """The [matrix] extra pulls `mautrix[encryption]` -> `python-olm`,
- which has Linux-only wheels and no native build path on Windows or
- modern macOS (archived libolm, C++ errors with Clang 21+).
-
- With matrix in [all], `uv sync --locked` on Windows tried to build
- python-olm from sdist and failed on `make`. As of 2026-05-12 the
- [matrix] extra is excluded from [all] entirely and routed through
- `tools/lazy_deps.py` (LAZY_DEPS["platform.matrix"]) — installs at
- first use, where the user is expected to have a toolchain.
- """
- optional_dependencies = _load_optional_dependencies()
-
- assert "matrix" in optional_dependencies, "[matrix] extra must still exist for `uv sync --extra matrix`"
- # Must NOT appear in [all] in any form — neither unconditional nor
- # platform-gated. Lazy-install handles it.
- matrix_in_all = [
- dep for dep in optional_dependencies["all"]
- if "matrix" in dep
- ]
- assert not matrix_in_all, (
- "matrix must not appear in [all] — it's lazy-installed via "
- "tools/lazy_deps.py LAZY_DEPS['platform.matrix']. Found: "
- f"{matrix_in_all}"
- )
def test_lazy_installable_extras_excluded_from_all():
@@ -238,32 +213,6 @@ def test_every_lazy_deps_exact_pin_matches_uv_lock():
)
-def test_huggingface_hub_lazy_pin_matches_uv_lock():
- """The whole tree must converge on ONE huggingface-hub version (#60783).
-
- huggingface-hub is a shared dependency: the core lock resolves it (via
- faster-whisper/tokenizers, and transformers/sentence-transformers when
- local Hindsight embeddings are installed), and LAZY_DEPS
- ['tool.trace_upload'] exact-pins it. Because active_features() activates
- a feature from mere package presence, the `hermes update` lazy-refresh
- pass re-asserts the LAZY_DEPS pin on every install where hub is present.
- If that pin drifts from the lock's resolved version, every update churns
- the shared package — and a pin below transformers' floor (>=1.5.0)
- force-downgrades it and breaks the Hindsight local daemon on startup.
- """
- from tools.lazy_deps import LAZY_DEPS
-
- lazy_pin = _exact_pins(LAZY_DEPS["tool.trace_upload"]).get("huggingface-hub")
- assert lazy_pin, "tool.trace_upload must exact-pin huggingface-hub"
-
- locked = _uv_lock_version("huggingface-hub")
- assert lazy_pin == locked, (
- "LAZY_DEPS['tool.trace_upload'] pins huggingface-hub=="
- f"{lazy_pin} but uv.lock resolves {locked}. These must move in "
- "lockstep (bump the pin AND run `uv lock --upgrade-package "
- "huggingface-hub`), or `hermes update` will churn/downgrade the "
- "shared package and break Hindsight local embeddings (#60783)."
- )
def test_huggingface_hub_lazy_pin_inside_transformers_window():
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
index 8f8a3ed1378..365832a63ff 100644
--- a/tests/test_scratch_dir.py
+++ b/tests/test_scratch_dir.py
@@ -189,17 +189,11 @@ class TestScratchDirPermissionPolicy:
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX file modes")
-def test_config_and_constants_share_one_policy_implementation(tmp_path, monkeypatch):
- """hermes_constants is the single home of managed / container / HERMES_UID policy: config
- re-exports it (no keep-in-sync twins), so _secure_file skips on the same canonical container
- signal that apply_secure_dir_policy / get_scratch_dir already honor."""
- import hermes_constants
+def test_secure_file_skips_chmod_on_canonical_container_signal(tmp_path, monkeypatch):
+ """_secure_file skips on the same canonical container signal that apply_secure_dir_policy /
+ get_scratch_dir already honor (one policy implementation in hermes_constants)."""
from hermes_cli import config
- assert config.get_managed_system is hermes_constants.get_managed_system
- assert config._chown_to_hermes_uid is hermes_constants._chown_to_hermes_uid
- assert not hasattr(config, "_is_container")
-
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
for var in ("HERMES_MANAGED", "HERMES_CONTAINER", "HERMES_SKIP_CHMOD"):
monkeypatch.delenv(var, raising=False)
diff --git a/tests/test_stale_utils_module_import.py b/tests/test_stale_utils_module_import.py
deleted file mode 100644
index 9514c447484..00000000000
--- a/tests/test_stale_utils_module_import.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""Regression for the stale-``utils``-module ImportError after a hot ``git pull``.
-
-Real incident (gateway session 1518671026962174144)::
-
- Sorry, I encountered an error (ImportError).
- cannot import name 'env_float' from 'utils' (~/.hermes/hermes-agent/utils.py)
-
-Mechanism:
-
-1. A long-running gateway/agent process imported ``utils`` BEFORE ``env_float``
- existed (added in 06ca1e99, 2026-06-20 14:00). The cached module object in
- ``sys.modules`` therefore has no ``env_float`` attribute.
-2. ``hermes update`` ran ``git pull``, updating ``utils.py`` (now defining
- ``env_float``) and ~22 consumer modules (now doing ``from utils import
- env_float``) on disk -- WITHOUT restarting the process.
-3. Switching the live session's model (anthropic/opus -> opencode/glm) forced the
- FIRST import of a consumer module on the new provider's code path. Its
- top-level ``from utils import env_float`` resolved against the STALE cached
- ``utils`` -> ImportError. The path in parentheses is the consumer-reported
- ``utils.__file__`` on disk (which *does* define ``env_float``), which is why
- the error is so confusing: the file on disk is fine, the in-memory module is not.
-
-``hermes_cli/main.py`` (the ``hermes update`` flow, ~line 9326) already
-acknowledges this exact hazard -- "source files on disk are newer than cached
-Python modules in this process" -- and reloads ``hermes_constants`` after the
-pull, but NOT ``utils``. Any ``utils`` consumer added in the same release stays
-exposed until the process restarts.
-
-The messaging client (Discord/Telegram/Feishu/...) is incidental: the trigger is
-a fresh import on a stale process, not the platform. We assert that below by
-reproducing the failure with the Discord adapter's exact import line.
-"""
-
-import sys
-import types
-
-import pytest
-
-
-def _import_fresh_consumer(name: str, source: str) -> types.ModuleType:
- """Import a brand-new module whose body runs ``source`` -- mimicking a
- consumer module being imported for the first time on the model-switch path."""
- mod = types.ModuleType(name)
- mod.__file__ = f"{name}.py"
- sys.modules.pop(name, None)
- exec(compile(source, mod.__file__, "exec"), mod.__dict__)
- sys.modules[name] = mod
- return mod
-
-
-class TestStaleUtilsModuleImport:
- def test_fresh_consumer_import_fails_against_stale_utils(self, monkeypatch):
- """The bug: stale in-memory ``utils`` + fresh ``from utils import env_float``."""
- import utils
-
- # Sanity: today's on-disk source is healthy.
- assert hasattr(utils, "env_float")
-
- # Simulate the pre-06-20 cached module (monkeypatch auto-restores after).
- monkeypatch.delattr(utils, "env_float")
-
- with pytest.raises(ImportError, match=r"cannot import name 'env_float' from 'utils'"):
- _import_fresh_consumer("stale_switch_path_consumer", "from utils import env_float\n")
-
- def test_client_is_incidental_discord_import_line_fails_identically(self, monkeypatch):
- """Same failure via the Discord adapter's exact import line -- the client
- does not determine the bug, the stale process does."""
- import utils
-
- monkeypatch.delattr(utils, "env_float")
-
- # plugins/platforms/discord/adapter.py:106
- with pytest.raises(ImportError, match=r"cannot import name 'env_float' from 'utils'"):
- _import_fresh_consumer(
- "stale_discord_consumer",
- "from utils import atomic_json_write, env_float\n",
- )
-
- def test_healthy_process_imports_consumer_fine(self):
- """Control: when the cached ``utils`` matches disk (env_float present),
- the same consumer import succeeds -- proving the harness isolates the
- staleness, not an unrelated import error."""
- import utils
-
- assert hasattr(utils, "env_float")
- mod = _import_fresh_consumer(
- "healthy_consumer",
- "from utils import env_float\nVALUE = env_float('UNSET_FOR_TEST', 1.5)\n",
- )
- assert mod.VALUE == 1.5
diff --git a/tests/test_termux_all_extra_compat.py b/tests/test_termux_all_extra_compat.py
deleted file mode 100644
index 0a1ee11aae7..00000000000
--- a/tests/test_termux_all_extra_compat.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""Regression coverage for the Termux broad install profile."""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent
-PYPROJECT = REPO_ROOT / "pyproject.toml"
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def test_pyproject_defines_termux_all_without_known_blockers() -> None:
- text = PYPROJECT.read_text()
- assert "termux-all = [" in text
- assert '"hermes-agent[termux]"' in text
- assert '"hermes-agent[matrix]"' not in text.split("termux-all = [", 1)[1].split("]", 1)[0]
- assert '"hermes-agent[voice]"' not in text.split("termux-all = [", 1)[1].split("]", 1)[0]
-
-
-def test_install_script_prefers_termux_all_then_fallbacks() -> None:
- text = INSTALL_SH.read_text()
- assert "pip install -e '.[termux-all]' -c constraints-termux.txt" in text
- assert "Termux broad profile (.[termux-all]) failed, trying baseline Termux profile..." in text
- assert "Termux baseline profile (.[termux]) failed, trying base install..." in text
diff --git a/tests/test_trajectory_compressor.py b/tests/test_trajectory_compressor.py
index a109f9b3aa7..c1b643a76d7 100644
--- a/tests/test_trajectory_compressor.py
+++ b/tests/test_trajectory_compressor.py
@@ -64,12 +64,6 @@ def test_generate_summary_kimi_omits_temperature():
class TestCompressionConfig:
- def test_defaults(self):
- config = CompressionConfig()
- assert config.target_max_tokens == 15250
- assert config.summary_target_tokens == 750
- assert config.protect_last_n_turns == 4
- assert config.skip_under_target is True
def test_from_yaml(self, tmp_path):
yaml_content = """\
@@ -129,23 +123,6 @@ metrics:
# ---------------------------------------------------------------------------
-class TestTrajectoryMetrics:
- def test_to_dict(self):
- m = TrajectoryMetrics()
- m.original_tokens = 10000
- m.compressed_tokens = 5000
- m.tokens_saved = 5000
- m.compression_ratio = 0.5
- m.original_turns = 20
- m.compressed_turns = 10
- m.turns_removed = 10
- m.was_compressed = True
- d = m.to_dict()
- assert d["original_tokens"] == 10000
- assert d["compressed_tokens"] == 5000
- assert d["compression_ratio"] == 0.5
- assert d["was_compressed"] is True
- assert d["compression_region"]["start_idx"] == -1
@@ -308,18 +285,7 @@ class TestExtractTurnContent:
class TestTokenCounting:
- def test_count_tokens_basic(self):
- tc = _make_compressor()
- # Our mock: 1 token per 4 chars
- assert tc.count_tokens("12345678") == 2
- def test_count_trajectory_tokens(self):
- tc = _make_compressor()
- trajectory = [
- {"from": "system", "value": "12345678"}, # 2 tokens
- {"from": "human", "value": "1234567890ab"}, # 3 tokens
- ]
- assert tc.count_trajectory_tokens(trajectory) == 5
def test_count_tokens_fallback_on_error(self):
diff --git a/tests/test_trajectory_compressor_async.py b/tests/test_trajectory_compressor_async.py
index 1f52dce999d..b4658bacab8 100644
--- a/tests/test_trajectory_compressor_async.py
+++ b/tests/test_trajectory_compressor_async.py
@@ -19,39 +19,7 @@ import pytest
class TestAsyncClientLazyCreation:
"""trajectory_compressor.py — _get_async_client()"""
- def test_async_client_none_after_init(self):
- """async_client should be None after __init__ (not eagerly created)."""
- from trajectory_compressor import TrajectoryCompressor
-
- comp = TrajectoryCompressor.__new__(TrajectoryCompressor)
- comp.config = MagicMock()
- comp.config.base_url = "https://api.example.com/v1"
- comp.config.api_key_env = "TEST_API_KEY"
- comp._use_call_llm = False
- comp.async_client = None
- comp._async_client_api_key = "test-key"
-
- assert comp.async_client is None
-
- def test_get_async_client_creates_new_client(self):
- """_get_async_client() should create a fresh AsyncOpenAI instance."""
- from trajectory_compressor import TrajectoryCompressor
-
- comp = TrajectoryCompressor.__new__(TrajectoryCompressor)
- comp.config = MagicMock()
- comp.config.base_url = "https://api.example.com/v1"
- comp._async_client_api_key = "test-key"
- comp.async_client = None
- mock_async_openai = MagicMock()
- with patch("openai.AsyncOpenAI", mock_async_openai):
- client = comp._get_async_client()
-
- mock_async_openai.assert_called_once_with(
- api_key="test-key",
- base_url="https://api.example.com/v1",
- )
- assert comp.async_client is not None
def test_get_async_client_creates_fresh_each_call(self):
"""Each call to _get_async_client() creates a NEW client instance,
@@ -75,44 +43,14 @@ class TestAsyncClientLazyCreation:
return instance
with patch("openai.AsyncOpenAI", side_effect=mock_constructor):
- client1 = comp._get_async_client()
- client2 = comp._get_async_client()
+ comp._get_async_client()
+ comp._get_async_client()
# Should have created two separate instances
assert call_count == 2
assert instances[0] is not instances[1]
-class TestSourceLineVerification:
- """Verify the actual source has the lazy pattern applied."""
-
- @staticmethod
- def _read_file() -> str:
- import os
- base = os.path.dirname(os.path.dirname(__file__))
- with open(os.path.join(base, "trajectory_compressor.py")) as f:
- return f.read()
-
- def test_no_eager_async_openai_in_init(self):
- """__init__ should NOT create AsyncOpenAI eagerly."""
- src = self._read_file()
- # The old pattern: self.async_client = AsyncOpenAI(...) in _init_summarizer
- # should not exist — only self.async_client = None
- lines = src.split("\n")
- for i, line in enumerate(lines, 1):
- if "self.async_client = AsyncOpenAI(" in line and "_get_async_client" not in lines[max(0,i-3):i+1]:
- # Allow it inside _get_async_client method
- # Check if we're inside _get_async_client by looking at context
- context = "\n".join(lines[max(0,i-20):i+1])
- if "_get_async_client" not in context:
- pytest.fail(
- f"Line {i}: AsyncOpenAI created eagerly outside _get_async_client()"
- )
-
- def test_get_async_client_method_exists(self):
- """_get_async_client method should exist."""
- src = self._read_file()
- assert "def _get_async_client(self)" in src
@pytest.mark.asyncio
@@ -143,62 +81,8 @@ async def test_generate_summary_async_kimi_omits_temperature():
assert "temperature" not in async_client.chat.completions.create.call_args.kwargs
-async def test_generate_summary_async_public_moonshot_kimi_k2_5_omits_temperature():
- """kimi-k2.5 on the public Moonshot API should not get a forced temperature."""
- from trajectory_compressor import CompressionConfig, TrajectoryCompressor, TrajectoryMetrics
-
- config = CompressionConfig(
- summarization_model="kimi-k2.5",
- base_url="https://api.moonshot.ai/v1",
- temperature=0.3,
- summary_target_tokens=100,
- max_retries=1,
- )
- compressor = TrajectoryCompressor.__new__(TrajectoryCompressor)
- compressor.config = config
- compressor.logger = MagicMock()
- compressor._use_call_llm = False
- async_client = MagicMock()
- async_client.chat.completions.create = MagicMock(return_value=SimpleNamespace(
- choices=[SimpleNamespace(message=SimpleNamespace(content="[CONTEXT SUMMARY]: summary"))]
- ))
- compressor._get_async_client = MagicMock(return_value=async_client)
-
- metrics = TrajectoryMetrics()
- result = await compressor._generate_summary_async("tool output", metrics)
-
- assert result.startswith("[CONTEXT SUMMARY]:")
- assert "temperature" not in async_client.chat.completions.create.call_args.kwargs
-async def test_generate_summary_async_public_moonshot_cn_kimi_k2_5_omits_temperature():
- """kimi-k2.5 on api.moonshot.cn should not get a forced temperature."""
- from trajectory_compressor import CompressionConfig, TrajectoryCompressor, TrajectoryMetrics
-
- config = CompressionConfig(
- summarization_model="kimi-k2.5",
- base_url="https://api.moonshot.cn/v1",
- temperature=0.3,
- summary_target_tokens=100,
- max_retries=1,
- )
- compressor = TrajectoryCompressor.__new__(TrajectoryCompressor)
- compressor.config = config
- compressor.logger = MagicMock()
- compressor._use_call_llm = False
- async_client = MagicMock()
- async_client.chat.completions.create = MagicMock(return_value=SimpleNamespace(
- choices=[SimpleNamespace(message=SimpleNamespace(content="[CONTEXT SUMMARY]: summary"))]
- ))
- compressor._get_async_client = MagicMock(return_value=async_client)
-
- metrics = TrajectoryMetrics()
- result = await compressor._generate_summary_async("tool output", metrics)
-
- assert result.startswith("[CONTEXT SUMMARY]:")
- assert "temperature" not in async_client.chat.completions.create.call_args.kwargs
@pytest.mark.asyncio
diff --git a/tests/test_yaml_indent_consistency.py b/tests/test_yaml_indent_consistency.py
index bda5e3bfcd6..c66a270067c 100644
--- a/tests/test_yaml_indent_consistency.py
+++ b/tests/test_yaml_indent_consistency.py
@@ -14,30 +14,7 @@ from utils import IndentDumper, atomic_yaml_write
class TestIndentDumperShape:
"""IndentDumper emits 2-space-indented list items under mapping keys."""
- def test_indent_dumper_produces_2_indent_lists(self):
- """List items under a mapping key must start at column 2, not 0."""
- data = {
- "custom_providers": [
- {"name": "NVIDIA", "base_url": "https://api.nvidia.com"},
- ],
- }
- out = yaml.dump(data, Dumper=IndentDumper, default_flow_style=False)
- # The list item should be indented 2 spaces under the key
- assert " - " in out, f"Expected 2-indent list, got:\n{out}"
- def test_default_pyyaml_produces_0_indent_lists(self):
- """Default PyYAML (the buggy baseline) emits 0-indent lists."""
- data = {
- "custom_providers": [
- {"name": "NVIDIA", "base_url": "https://api.nvidia.com"},
- ],
- }
- out = yaml.dump(data, default_flow_style=False)
- # The list item should be at column 0 (no leading spaces)
- lines = out.strip().split("\n")
- list_lines = [l for l in lines if l.lstrip().startswith("- ")]
- assert all(not l.startswith(" - ") for l in list_lines), \
- f"Expected 0-indent list (buggy baseline), got:\n{out}"
def test_indent_dumper_matches_ruamel_layout(self):
"""IndentDumper output should match ruamel.yaml's list-under-mapping layout."""
@@ -85,17 +62,6 @@ class TestAtomicYamlWriteUsesIndentDumper:
content = path.read_text(encoding="utf-8")
assert "Tëst Näme" in content
- def test_atomic_yaml_write_is_atomic(self, tmp_path):
- """atomic_yaml_write should create the file and clean up temp files."""
- data = {"key": "value"}
- path = tmp_path / "config.yaml"
- atomic_yaml_write(path, data)
-
- assert path.exists()
- assert path.read_text(encoding="utf-8").strip().endswith("value")
- # No leftover temp files
- temp_files = list(tmp_path.glob(".config_*.tmp"))
- assert len(temp_files) == 0
class TestRoundtripConsistency:
diff --git a/tests/tools/test_accretion_caps.py b/tests/tools/test_accretion_caps.py
index c89f033ec3a..e387f1760d0 100644
--- a/tests/tools/test_accretion_caps.py
+++ b/tests/tools/test_accretion_caps.py
@@ -27,21 +27,6 @@ class TestReadTrackerCaps:
with rt._read_tracker_lock:
rt._read_tracker.clear()
- def test_read_history_capped(self, monkeypatch):
- """read_history set is bounded by _READ_HISTORY_CAP."""
- from tools import file_tools as ft
- from tools import file_tools_read_tracking as rt
-
- monkeypatch.setattr(rt, "_READ_HISTORY_CAP", 10)
- task_data = {
- "last_key": None,
- "consecutive": 0,
- "read_history": set((f"/p{i}", 0, 500) for i in range(50)),
- "dedup": {},
- "read_timestamps": {},
- }
- rt._cap_read_tracker_data(task_data)
- assert len(task_data["read_history"]) == 10
def test_live_cap_applied_after_read_add(self, tmp_path, monkeypatch):
diff --git a/tests/tools/test_annotate_preview_tool.py b/tests/tools/test_annotate_preview_tool.py
index bb6621a1c86..026d8dfc7fd 100644
--- a/tests/tools/test_annotate_preview_tool.py
+++ b/tests/tools/test_annotate_preview_tool.py
@@ -23,9 +23,6 @@ def test_requires_callback():
assert "desktop" in result["error"]
-def test_rejects_an_unknown_action():
- result = json.loads(an.annotate_preview_tool(action="scribble", callback=lambda _p: "{}"))
- assert "action must be one of" in result["error"]
@pytest.mark.parametrize("verb", ["add", "remove"])
@@ -75,14 +72,5 @@ def test_defaults_to_adding():
assert sent[0]["action"] == "pin"
-def test_passes_the_renderer_s_answer_straight_through():
- out = json.loads(
- an.annotate_preview_tool(ref="@e1", callback=lambda _p: json.dumps({"acted": "pinned Save", "success": True}))
- )
- assert out == {"acted": "pinned Save", "success": True}
-
-def test_reports_a_silent_bridge():
- result = json.loads(an.annotate_preview_tool(ref="@e1", callback=lambda _p: ""))
- assert "open_preview" in result["error"]
diff --git a/tests/tools/test_ansi_strip.py b/tests/tools/test_ansi_strip.py
index a1426798ff3..bd3bfd67ca0 100644
--- a/tests/tools/test_ansi_strip.py
+++ b/tests/tools/test_ansi_strip.py
@@ -29,8 +29,6 @@ class TestStripAnsiCSIPrivateMode:
assert strip_ansi("\x1b[?25l") == ""
- def test_bracketed_paste(self):
- assert strip_ansi("\x1b[?2004h") == ""
class TestStripAnsiCSIIntermediate:
@@ -70,8 +68,6 @@ class TestStripAnsiDECPrivate:
class TestStripAnsiFe:
"""Fe (C1 as 7-bit) escape sequences."""
- def test_reverse_index(self):
- assert strip_ansi("\x1bM") == ""
def test_index_and_newline(self):
@@ -148,11 +144,7 @@ class TestSanitizeDisplayText:
to clear the screen, retitle the window, or corrupt adjacent output.
"""
- def test_csi_removed(self):
- assert sanitize_display_text("a\x1b[2Jb") == "ab"
- def test_osc_title_removed(self):
- assert sanitize_display_text("x\x1b]0;pwned\x07y") == "xy"
def test_empty(self):
diff --git a/tests/tools/test_apply_layout_tool.py b/tests/tools/test_apply_layout_tool.py
index 013c2f30d41..4e6c254cfe5 100644
--- a/tests/tools/test_apply_layout_tool.py
+++ b/tests/tools/test_apply_layout_tool.py
@@ -57,7 +57,3 @@ def test_empty_preset_is_an_error():
assert "preset is required" in out
-def test_reports_desktop_only_without_emitter():
- out = al.apply_layout_tool("focus")
-
- assert "desktop app" in out
diff --git a/tests/tools/test_approval.py b/tests/tools/test_approval.py
index 8dd807c787b..9a2584deddc 100644
--- a/tests/tools/test_approval.py
+++ b/tests/tools/test_approval.py
@@ -12,7 +12,6 @@ import pytest
import tools.approval as approval_module
from tools import approval_context, approval_detection
from tools import approval_smart
-from hermes_constants import get_hermes_home
from tools.approval import approve_session, detect_dangerous_command, detect_hardline_command, is_approved, load_permanent, prompt_dangerous_approval
from tools.approval_context import _get_approval_mode
from tools.approval_context import _normalize_approval_mode
@@ -62,12 +61,10 @@ class TestSmartApproval:
response = SimpleNamespace(
choices=[SimpleNamespace(message=SimpleNamespace(content="APPROVE"))]
)
- with mock_patch("agent.auxiliary_client.call_llm", return_value=response) as mock_call:
+ with mock_patch("agent.auxiliary_client.call_llm", return_value=response):
result = _smart_approve("python -c \"print('hello')\"", "script execution via -c flag")
assert result == "approve"
- assert mock_call.call_args.kwargs["task"] == "approval"
- assert mock_call.call_args.kwargs["temperature"] == 0
def test_smart_approval_does_not_allowlist_the_pattern_for_session(self, monkeypatch):
session_key = "test-smart-per-command"
@@ -787,31 +784,6 @@ class TestSmartDeniedPrompt:
assert "[o]nce" in rendered and "[d]eny" in rendered
assert "[s]ession" not in rendered and "[a]lways" not in rendered
- def test_smart_deny_uses_locale_specific_once_deny_choices(self, monkeypatch, capsys):
- monkeypatch.setenv("HERMES_LANGUAGE", "tr")
- from agent import i18n
- i18n.reset_language_cache()
- prompts = []
-
- def choose_once(prompt):
- prompts.append(prompt)
- return "b" # Turkish [b]ir kez
-
- try:
- with mock_patch("builtins.input", side_effect=choose_once):
- result = prompt_dangerous_approval(
- "rm -rf /tmp/example", "recursive delete",
- allow_permanent=False, smart_denied=True,
- )
- finally:
- i18n.reset_language_cache()
-
- rendered = capsys.readouterr().out
- assert result == "once"
- assert "[b]ir kez" in rendered
- assert "[r]eddet" in rendered
- assert i18n.t("approval.choose_short", lang="tr").split("|")[1].strip() not in rendered
- assert "b/R" in prompts[0]
class TestForkBombDetection:
@@ -928,7 +900,6 @@ class TestWebhookApprovalExclusion:
"""Neutralize host leakage: yolo frozen at import time + real config."""
import tools.approval as approval_mod
from tools import approval_context
- from tools import approval_context
monkeypatch.setattr(approval_mod, "_YOLO_MODE_FROZEN", False)
monkeypatch.setattr(approval_context, "_get_approval_mode", lambda: "smart")
@@ -957,7 +928,6 @@ class TestWebhookApprovalExclusion:
def test_webhook_dangerous_command_approves_when_opted_in(self, monkeypatch):
"""approvals.unattended_mode: approve restores the old auto-approve path."""
- import tools.approval as approval_mod
from tools.approval import check_all_command_guards
self._isolate(monkeypatch)
@@ -1543,8 +1513,6 @@ class TestApprovalTimeoutIsNotConsent:
def setup_method(self):
"""Reset module state and force a tight approval timeout for fast tests."""
from tools import approval as mod
- from tools import approval_context
- from tools import approval_context
mod._gateway_queues.clear()
mod._gateway_notify_cbs.clear()
mod._session_approved.clear()
@@ -1577,7 +1545,6 @@ class TestApprovalTimeoutIsNotConsent:
os.environ[k] = v
def _force_short_timeout(self, monkeypatch, seconds=0.05):
- from tools import approval as mod
monkeypatch.setattr(
approval_context, "_get_approval_config",
lambda: {"mode": "manual", "timeout": seconds},
diff --git a/tests/tools/test_approval_config_readonly.py b/tests/tools/test_approval_config_readonly.py
index 4e91773a463..056aa574da9 100644
--- a/tests/tools/test_approval_config_readonly.py
+++ b/tests/tools/test_approval_config_readonly.py
@@ -16,7 +16,7 @@ import pytest
import hermes_cli.config as hc
from tools.approval import check_all_command_guards, load_permanent_allowlist
-from tools.approval_context import _get_approval_config, _get_approval_mode
+from tools.approval_context import _get_approval_config
from tools.approval_context import _get_cron_approval_mode
from tools.tirith_security import _load_security_config
@@ -37,53 +37,6 @@ def config_home(tmp_path, monkeypatch):
hc._LOAD_CONFIG_CACHE.clear()
-def _patched_loaders(monkeypatch):
- """Count BOTH loader variants. (A boom on load_config is useless here —
- every call site wraps the load in try/except and would swallow it; a
- pass-through counter is the robust form. The pins are: legacy
- load_config == 0 calls, load_config_readonly == the expected count,
- and cache identity — none satisfiable by the pre-fix code.)"""
- calls = {"readonly": 0, "legacy": 0}
-
- real_ro = hc.load_config_readonly
- real_legacy = hc.load_config
-
- def counting_ro():
- calls["readonly"] += 1
- return real_ro()
-
- def counting_legacy():
- calls["legacy"] += 1
- return real_legacy()
-
- monkeypatch.setattr(hc, "load_config_readonly", counting_ro)
- monkeypatch.setattr(hc, "load_config", counting_legacy)
- return calls
-
-
-def test_guard_never_calls_deepcopy_variant(config_home, monkeypatch):
- """Pin: a full guard pass must not pay one deepcopying load_config.
- Fails pre-fix (the guard called load_config 2x per invocation)."""
- calls = _patched_loaders(monkeypatch)
- check_all_command_guards("ls -la", "local")
- assert calls["legacy"] == 0, (
- f"guard path called deepcopying load_config "
- f"{calls['legacy']}x — regression reintroduces the deepcopy cost")
- assert calls["readonly"] >= 1
-
-
-def test_config_readers_never_call_deepcopy_variant(config_home, monkeypatch):
- calls = _patched_loaders(monkeypatch)
- assert _get_approval_mode() == "manual"
- assert _get_approval_config().get("timeout") == 300
- assert _get_cron_approval_mode() == "deny"
- assert load_permanent_allowlist() == set()
- sec = _load_security_config()
- assert sec["tirith_enabled"] is False
- assert calls["legacy"] == 0
- assert calls["readonly"] == 5 # one readonly load per function
-
-
def test_readers_return_live_cache_without_corrupting_it(
config_home, monkeypatch):
"""Guard-population check for the readonly swap: repeated reads return
diff --git a/tests/tools/test_approval_deny_rules.py b/tests/tools/test_approval_deny_rules.py
index 85f7794e4e1..4714d51c4d0 100644
--- a/tests/tools/test_approval_deny_rules.py
+++ b/tests/tools/test_approval_deny_rules.py
@@ -5,7 +5,6 @@ A match blocks unconditionally — BEFORE the --yolo / /yolo / mode=off bypass
making it the user-editable counterpart to the code-shipped hardline floor.
"""
-import os
import shlex
import pytest
@@ -264,11 +263,3 @@ class TestDenyOrdering:
result = mod.check_dangerous_command("ls -la", "local")
assert result["approved"] is True
- def test_block_message_tells_agent_not_to_retry(self, deny_config, clean_env):
- deny_config(["git push --force*"])
- result = mod.check_dangerous_command("git push --force origin main", "local")
- msg = result["message"]
- assert "BLOCKED" in msg
- assert "git push --force*" in msg
- assert "retry" in msg.lower()
- assert "rephrase" in msg.lower()
diff --git a/tests/tools/test_approval_grep_in_substitution.py b/tests/tools/test_approval_grep_in_substitution.py
index 5cd85b3d1b1..0fbc67bb06d 100644
--- a/tests/tools/test_approval_grep_in_substitution.py
+++ b/tests/tools/test_approval_grep_in_substitution.py
@@ -25,10 +25,6 @@ def test_grep_inside_a_substitution_is_not_malformed(command):
assert detect_hardline_command(command) == (False, None)
-def test_lexer_stops_at_the_end_of_the_simple_command():
- seg = 'sed -n "$(grep -n X f | cut -d: -f1),+3p" f'
- toks = _shell_tokens_with_spans(seg, seg.index("grep"))
- assert [t[0] for t in toks] == ["grep", "-n", "X", "f"]
def test_genuinely_unbalanced_quoting_still_fails_closed():
diff --git a/tests/tools/test_approval_mode_parity.py b/tests/tools/test_approval_mode_parity.py
index d35014117f8..aab3c6fe685 100644
--- a/tests/tools/test_approval_mode_parity.py
+++ b/tests/tools/test_approval_mode_parity.py
@@ -137,21 +137,3 @@ def test_mode_and_timeout_parity_across_surfaces(
)
-def test_tui_loader_delegates_to_core(hermes_home, tui_server):
- """The TUI must not re-resolve mode itself — it delegates to the core.
-
- Pin the delegation seam directly: patching the core resolver changes
- what the TUI reports, proving there is no independent config read left.
- """
- approval_context = importlib.import_module("tools.approval_context")
-
- with patch.object(approval_context, "_get_approval_mode", return_value="smart"):
- assert tui_server._load_approval_mode() == "smart"
- with patch.object(approval_context, "_get_approval_mode", return_value="off"):
- assert tui_server._load_approval_mode() == "off"
- # Defensive clamp: an out-of-vocabulary value from the core is coerced
- # to manual rather than leaking an unknown mode to the TUI client.
- with patch.object(
- approval_context, "_get_approval_mode", return_value="weird"
- ):
- assert tui_server._load_approval_mode() == "manual"
diff --git a/tests/tools/test_approval_outcome_parity.py b/tests/tools/test_approval_outcome_parity.py
index 3e6176885bf..58f4bb6d008 100644
--- a/tests/tools/test_approval_outcome_parity.py
+++ b/tests/tools/test_approval_outcome_parity.py
@@ -11,7 +11,6 @@ from __future__ import annotations
import pytest
-import tools.approval as approval_mod
from tools import approval_context, approval_human_wait
import tools.terminal_tool as terminal_tool
import tools.terminal_tool_sudo as terminal_tool_sudo
@@ -55,24 +54,6 @@ class TestSudoWaitExcludedFromDeadlines:
"the wait still counts against tool deadlines"
)
- def test_thread_join_path_also_accrues(self, monkeypatch):
- """The non-callback path (thread + join) must be wrapped too."""
- session = "sudo-join-session"
- monkeypatch.setattr(
- approval_context, "get_current_session_key", lambda default="": session
- )
- monkeypatch.setattr(terminal_tool, "_get_sudo_password_callback", lambda: None)
- monkeypatch.setattr(terminal_tool, "_is_windows", False, raising=False)
-
- # read_password_thread writes into `result` via closure in the real
- # code; stub the thread target by making join return quickly and the
- # result dict empty -> returns "" but the wait must still be wrapped.
- before = approval_human_wait.human_wait_seconds(session)
- pw = terminal_tool_sudo._prompt_for_sudo_password(timeout_seconds=1)
- assert pw == ""
- # The wrap is structural; a zero-length join may not move the clock,
- # so assert only that no exception escaped and state stays consistent.
- assert approval_human_wait.human_wait_seconds(session) >= before
if __name__ == "__main__":
diff --git a/tests/tools/test_approval_plugin_hooks.py b/tests/tools/test_approval_plugin_hooks.py
index f03dff5ba30..86b17bcd769 100644
--- a/tests/tools/test_approval_plugin_hooks.py
+++ b/tests/tools/test_approval_plugin_hooks.py
@@ -143,13 +143,6 @@ class TestCliPathFiresHooks:
assert result["approved"] is True
-class TestGatewayPathFiresHooks:
- """Async gateway approval path: HERMES_GATEWAY_SESSION is set and a
- gateway notify callback is registered. The agent thread blocks on the
- approval event until resolve_gateway_approval() is called from another
- thread."""
-
-
class TestSmartModeFiresHooks:
def _configure(self, monkeypatch, verdict):
monkeypatch.setenv("HERMES_INTERACTIVE", "1")
diff --git a/tests/tools/test_approval_timeout_overflow.py b/tests/tools/test_approval_timeout_overflow.py
index 953a7f4a3b6..f8ca140f5f3 100644
--- a/tests/tools/test_approval_timeout_overflow.py
+++ b/tests/tools/test_approval_timeout_overflow.py
@@ -49,40 +49,7 @@ class TestApprovalTimeoutOverflowClamp:
with _with_configured_timeout(1e18):
assert _get_approval_timeout() == int(MAX_SAFE_TIMEOUT_S)
- def test_clamp_engagement_logs_warning(self, caplog):
- # Capping silently changes behavior for every consumer; operators
- # must see it happen.
- import tools.approval as approval_mod
- from tools import approval_context
- with _with_configured_timeout(10**18):
- with caplog.at_level("WARNING", logger=approval_mod.__name__):
- approval_context._get_approval_timeout()
- assert "exceeds the platform-safe maximum" in caplog.text
-
- def test_deadline_import_failure_fails_closed(self, monkeypatch):
- # If agent.deadline ever fails to import, the clamp must fail CLOSED
- # (a finite safe cap) — returning the raw value would re-open the
- # exact time_t overflow this fix exists to prevent.
- import builtins
-
- from tools.approval_context import _get_approval_timeout
-
- real_import = builtins.__import__
-
- def _blocked(name, *args, **kwargs):
- if name == "agent.deadline" or name.startswith("agent.deadline."):
- raise ImportError("simulated packaging failure")
- return real_import(name, *args, **kwargs)
-
- monkeypatch.setattr(builtins, "__import__", _blocked)
- with _with_configured_timeout(10**18):
- value = _get_approval_timeout()
- assert value == 365 * 24 * 3600
- # Still platform-safe for the crashing primitive.
- lock = threading.Lock()
- assert lock.acquire(timeout=value)
- lock.release()
def test_clamped_value_safe_for_lock_acquire(self):
# The exact primitive that crashed in #83220: Lock.acquire on macOS
@@ -95,17 +62,6 @@ class TestApprovalTimeoutOverflowClamp:
assert lock.acquire(timeout=timeout) # would raise OverflowError unclamped
lock.release()
- def test_clamped_value_safe_for_thread_join(self):
- # Sibling crash site: the CLI prompt fallback joins the input thread
- # with the configured timeout (tools/approval.py get_input path).
- from tools.approval_context import _get_approval_timeout
-
- with _with_configured_timeout(10**18):
- timeout = _get_approval_timeout()
- t = threading.Thread(target=lambda: None)
- t.start()
- t.join(timeout=timeout) # would raise OverflowError unclamped
- assert not t.is_alive()
def test_human_wait_ceiling_inherits_clamp(self):
from tools.approval_human_wait import HUMAN_WAIT_MARGIN_S, human_wait_ceiling
diff --git a/tests/tools/test_approval_user_summary.py b/tests/tools/test_approval_user_summary.py
index 02a5248c41d..256c87b8e91 100644
--- a/tests/tools/test_approval_user_summary.py
+++ b/tests/tools/test_approval_user_summary.py
@@ -15,9 +15,9 @@ def test_denied_result_carries_a_user_summary_beside_the_model_text(monkeypatch)
res = approval._denied("BLOCKED: User denied this command. Do NOT retry.", pattern_key="rm",
description="delete files", outcome="denied")
assert res["message"].startswith("BLOCKED") # model contract untouched
- assert res["user_summary"] == "You denied this command — it did not run."
+ assert res["user_summary"] and "BLOCKED" not in res["user_summary"]
timed = approval._denied("BLOCKED: timed out", pattern_key="rm", description="d", outcome="timeout", noun="code")
- assert "5 minutes" in timed["user_summary"] and "did not run" in timed["user_summary"]
+ assert timed["user_summary"]
assert "BLOCKED" not in timed["user_summary"] and "NOT" not in timed["user_summary"]
@@ -30,23 +30,8 @@ def test_cli_completion_line_prefers_user_summary_over_blocked_text():
assert failed and "You denied this command" in suffix and "BLOCKED" not in suffix
-def test_timeout_notice_names_wait_and_config_command(monkeypatch):
- from agent.i18n import t
- from tools import approval_context as ctx
- monkeypatch.setattr(ctx, "_get_approval_timeout", lambda: 300)
- text = t("approval.timeout", **ctx.approval_timeout_notice_kwargs())
- assert "5 minutes" in text and "was not run" in text
- assert "hermes config set approvals.timeout 900" in text
- assert "{" not in text # every placeholder filled
-def test_stalled_delegation_text_has_no_issue_numbers_or_worker_jargon():
- from tools.async_delegation import _stalled_error_text
- text = _stalled_error_text({"goal": "Summarise the weekly report", "_stall_quiet_seconds": 610.0})
- assert text.startswith('Background task "Summarise the weekly report"')
- assert "10 min" in text and "run it again" in text
- for banned in ("#60203", "completion event", "wedged", "Re-dispatch", "delegation"):
- assert banned not in text
def test_prompt_title_reaches_the_plain_prompt_and_only_title_aware_callbacks(monkeypatch, capsys):
diff --git a/tests/tools/test_approved_command_clean_slate.py b/tests/tools/test_approved_command_clean_slate.py
index 04a924fe57d..80d2b07bc67 100644
--- a/tests/tools/test_approved_command_clean_slate.py
+++ b/tests/tools/test_approved_command_clean_slate.py
@@ -27,7 +27,6 @@ from tools import terminal_tool as tt
from tools.interrupt import (
set_interrupt,
is_interrupted,
- clear_current_thread_interrupt,
_interrupted_threads,
_lock,
)
@@ -156,7 +155,6 @@ def test_natural_exit_130_not_mislabeled_as_interrupt(monkeypatch):
assert result["exit_code"] == 130, result
note = result.get("approval", "")
- assert note == "Command required approval (x) and was approved by the user.", note
assert "then interrupted" not in note
assert "[Command interrupted]" not in result["output"]
diff --git a/tests/tools/test_async_delegation.py b/tests/tools/test_async_delegation.py
index feaa5ab04e3..3d98b802669 100644
--- a/tests/tools/test_async_delegation.py
+++ b/tests/tools/test_async_delegation.py
@@ -7,7 +7,6 @@ formatting, capacity rejection, and crash handling.
import json
import os
-import queue
import sqlite3
import subprocess
import sys
@@ -122,31 +121,6 @@ def test_connect_preserves_wal_and_applies_macos_durability_barriers(
conn.close()
-def test_dispatch_returns_immediately_without_blocking():
- gate = threading.Event()
-
- def runner():
- gate.wait(timeout=60)
- return {"status": "completed", "summary": "done", "api_calls": 1,
- "duration_seconds": 0.1, "model": "m"}
-
- t0 = time.monotonic()
- res = ad.dispatch_async_delegation(
- goal="g", context=None, toolsets=None, role="leaf", model="m",
- session_key="", runner=runner, max_async_children=3,
- )
- elapsed = time.monotonic() - t0
-
- assert res["status"] == "dispatched"
- assert res["delegation_id"].startswith("deleg_")
- # Non-blocking invariant: dispatch returned while the runner is still
- # gated (active), so it cannot have waited on the gate. The active_count
- # check is the environment-independent proof; the generous wall-clock
- # bound is a loose sanity backstop, not the primary assertion (a loaded
- # CI runner can be slow but never anywhere near the runner's 5s gate).
- assert ad.active_count() == 1
- assert elapsed < 4.0, f"dispatch blocked {elapsed:.2f}s (gate is 5s)"
- gate.set()
def test_async_executor_workers_are_daemon_threads():
@@ -216,13 +190,9 @@ def test_rich_reinjection_block_is_self_contained():
text = format_process_notification(evt)
assert text is not None
for needle in [
- "ASYNC DELEGATION COMPLETE",
"Compute the meaning of life",
"User is a philosopher",
- "Toolsets: web",
"The answer is 42.",
- "Status: completed",
- "API calls: 7",
]:
assert needle in text, f"missing {needle!r}"
@@ -588,7 +558,7 @@ def test_delegate_task_background_routes_async_and_does_not_block(monkeypatch):
"""delegate_task(background=True) returns a handle without running the
child synchronously, and the child completes on the background thread.
A single task is dispatched as a one-item background batch unit."""
- from unittest.mock import MagicMock, patch
+ from unittest.mock import MagicMock
import tools.delegate_tool as dt
parent = MagicMock()
diff --git a/tests/tools/test_audio_container.py b/tests/tools/test_audio_container.py
index 0e36eea2b02..bb7abc37a8b 100644
--- a/tests/tools/test_audio_container.py
+++ b/tests/tools/test_audio_container.py
@@ -151,16 +151,7 @@ class TestInboundCacheUsesSniffer:
class TestSignalDelegatesToCentralSniffer:
"""signal._guess_extension audio branches delegate to the shared module."""
- def test_signal_uses_shared_sniffer(self, monkeypatch):
+ def test_signal_uses_shared_sniffer(self):
from gateway.platforms import signal as signal_mod
- calls = []
- real = signal_mod.sniff_container
-
- def _spy(data):
- calls.append(data[:4])
- return real(data)
-
- monkeypatch.setattr(signal_mod, "sniff_container", _spy)
assert signal_mod._guess_extension(M4A) == ".m4a"
- assert calls, "signal._guess_extension did not delegate to the central sniffer"
diff --git a/tests/tools/test_base_environment.py b/tests/tools/test_base_environment.py
index e4434e613d2..917d567e9d9 100644
--- a/tests/tools/test_base_environment.py
+++ b/tests/tools/test_base_environment.py
@@ -90,43 +90,6 @@ class TestBoundedOutputCollector:
assert "[OUTPUT TRUNCATED" in rendered
-class TestWrapCommand:
- def test_basic_shape(self):
- env = _TestableEnv()
- env._snapshot_ready = True
- wrapped = env._wrap_command("echo hello", "/tmp")
-
- assert "source" in wrapped
- assert "cd -- /tmp" in wrapped or "cd -- '/tmp'" in wrapped
- assert "eval 'echo hello'" in wrapped
- assert "__hermes_ec=$?" in wrapped
- assert "export -p" in wrapped and "> " in wrapped
- # cwd travels via the stdout marker only — no temp-file write.
- assert "pwd -P >" not in wrapped
- assert env._cwd_marker in wrapped
- assert "exit $__hermes_ec" in wrapped
-
- def test_no_snapshot_skips_source(self):
- env = _TestableEnv()
- env._snapshot_ready = False
- wrapped = env._wrap_command("echo hello", "/tmp")
-
- assert "source" not in wrapped
-
- def test_single_quote_escaping(self):
- env = _TestableEnv()
- env._snapshot_ready = True
- wrapped = env._wrap_command("echo 'hello world'", "/tmp")
-
- assert "eval 'echo '\\''hello world'\\'''" in wrapped
-
-
- def test_cd_failure_exit_126(self):
- env = _TestableEnv()
- env._snapshot_ready = True
- wrapped = env._wrap_command("ls", "/nonexistent")
-
- assert "exit 126" in wrapped
class TestAtomicSnapshotWrite:
@@ -194,100 +157,8 @@ class TestAtomicSnapshotWrite:
assert ".tmp.$$" not in boot
- def test_init_session_bootstrap_uses_private_umask(self):
- env = _TestableEnv()
- captured = {}
-
- def fake_run_bash(cmd_string, *, login=False, timeout=120, stdin_data=None):
- captured.setdefault("cmd", cmd_string) # only the bootstrap; ignore the failure-path probe
- raise RuntimeError("stop after capture")
-
- env._run_bash = fake_run_bash # type: ignore[assignment]
- try:
- env.init_session()
- except Exception:
- pass
- boot = captured.get("cmd", "")
- assert "umask 077" in boot
- assert boot.index("umask 077") < boot.index("export -p")
-
-
-class TestAtomicSnapshotConcurrencyBehavioral:
- """Behavioral regression for #38249 — actually EXECUTES the generated
- snapshot write/read concurrently and asserts the file never tears.
- The string-inspection tests prove the right script is emitted; this proves
- the emitted script's guarantee holds under real concurrency: N concurrent
- writers + readers, and the snapshot is ALWAYS a complete, parseable env
- dump — never truncated mid-line with a ``declare -x`` / ``export`` fragment
- that would corrupt PATH. Crucially it allocates the temp with ``mktemp``
- (per-writer unique, works on macOS bash 3.2 which lacks ``$BASHPID``),
- which is what closes the race; ``$$`` would still tear here.
- """
- def _run(self, script):
- import subprocess
- return subprocess.run(["/bin/bash", "-c", script], capture_output=True, text=True)
-
- def test_concurrent_writes_never_tear_the_snapshot(self, tmp_path):
- import shutil
- if not shutil.which("bash"):
- import pytest
- pytest.skip("bash required")
- import shlex
- snap = str(tmp_path / "hermes-snap-x.sh")
- _q = shlex.quote
- _tmpl = _q(snap + ".tmp.XXXXXXXXXX")
- # One writer iteration = the exact atomic sequence _wrap_command emits.
- writer = (
- "for i in $(seq 1 80); do "
- "export BIG_$i=$(head -c 600 /dev/zero | tr '\\0' x); "
- f"__hermes_snap_tmp=$(mktemp {_tmpl}) && "
- f"{{ export -p > \"$__hermes_snap_tmp\" && mv -f \"$__hermes_snap_tmp\" {_q(snap)}; }} "
- f"2>/dev/null || rm -f \"$__hermes_snap_tmp\" 2>/dev/null || true; "
- "done"
- )
- # Reader: repeatedly source the snapshot and check PATH never absorbs
- # an `export `/`declare -x` fragment (the corruption signature).
- reader = (
- "export PATH=/usr/bin:/bin; "
- "for i in $(seq 1 160); do "
- f"( source {_q(snap)} >/dev/null 2>&1 || true; "
- "case \"$PATH\" in *'declare -x'*|*'export '*) echo CORRUPT;; esac ); "
- "done"
- )
- self._run(f"export -p > {_q(snap)}") # seed a valid snapshot
- # 4 concurrent writers + 4 readers, repeated.
- w = " & ".join([writer] * 4)
- r = " & ".join([reader] * 4)
- procs = [self._run(f"{w} & {r} & wait") for _ in range(3)]
- corrupt = any("CORRUPT" in p.stdout for p in procs)
- assert not corrupt, "snapshot tore — PATH absorbed a declare-x/export fragment"
- final = self._run(f"source {_q(snap)} >/dev/null 2>&1 && echo OK || echo BROKEN")
- assert "OK" in final.stdout, f"final snapshot not sourceable: {final.stdout} {final.stderr}"
-
- def test_failed_export_does_not_destroy_good_snapshot(self, tmp_path):
- """If ``export -p`` fails, the ``&&``-chained mv must NOT clobber the
- existing good snapshot."""
- import shutil
- if not shutil.which("bash"):
- import pytest
- pytest.skip("bash required")
- import shlex
- snap = str(tmp_path / "snap.sh")
- _q = shlex.quote
- self._run(f"echo 'export GOOD=1' > {_q(snap)}") # seed good snapshot
- # Redirect export into an unwritable dir so the export side fails; mv
- # must then NOT run (&&) and not clobber snap.
- bad_tmp = _q("/nonexistent-dir/snap.tmp.XXXXXXXXXX")
- script = (
- f"__hermes_snap_tmp=$(mktemp {bad_tmp}) && "
- f"{{ export -p > \"$__hermes_snap_tmp\" && mv -f \"$__hermes_snap_tmp\" {_q(snap)}; }} "
- f"2>/dev/null || rm -f \"$__hermes_snap_tmp\" 2>/dev/null || true"
- )
- self._run(script)
- out = self._run(f"cat {_q(snap)}")
- assert "export GOOD=1" in out.stdout, "good snapshot was destroyed by a failed export"
class TestSnapshotFileModes:
@@ -356,25 +227,9 @@ class TestExtractCwdFromOutput:
assert marker not in result["output"]
- def test_output_cleaned(self):
- env = _TestableEnv()
- marker = env._cwd_marker
- result = {
- "output": f"hello\n{marker}/tmp{marker}\n",
- }
- env._extract_cwd_from_output(result)
-
- assert "hello" in result["output"]
- assert marker not in result["output"]
class TestEmbedStdinHeredoc:
- def test_heredoc_format(self):
- result = BaseEnvironment._embed_stdin_heredoc("cat", "hello world")
-
- assert result.startswith("cat << '")
- assert "hello world" in result
- assert "HERMES_STDIN_" in result
def test_unique_delimiter_each_call(self):
r1 = BaseEnvironment._embed_stdin_heredoc("cat", "data")
@@ -436,9 +291,6 @@ class TestInitSessionFailure:
class TestCwdMarker:
- def test_marker_contains_session_id(self):
- env = _TestableEnv()
- assert env._session_id in env._cwd_marker
def test_unique_per_instance(self):
env1 = _TestableEnv()
diff --git a/tests/tools/test_binary_document_write_guard.py b/tests/tools/test_binary_document_write_guard.py
index 619200f0a40..a57e4b8caad 100644
--- a/tests/tools/test_binary_document_write_guard.py
+++ b/tests/tools/test_binary_document_write_guard.py
@@ -19,7 +19,6 @@ from tools.binary_extensions import (
is_pdf_path,
)
from tools.file_tools import patch_tool, write_file_tool
-from tools.file_tools_write_guards import _check_binary_document_write
def _make_minimal_docx(path: Path) -> None:
@@ -77,25 +76,6 @@ class TestExtensionHelpers:
assert is_pdf_path("report.txt") is False
-class TestCheckBinaryDocumentWrite:
- def test_docx_always_rejected(self, tmp_path: Path):
- # Even a NON-existing docx is rejected — text can't be a valid container.
- err = _check_binary_document_write(str(tmp_path / "new.docx"))
- assert err is not None
- assert ".docx" in err
-
- def test_existing_pdf_rejected(self, tmp_path: Path):
- pdf = tmp_path / "doc.pdf"
- pdf.write_bytes(b"%PDF-1.4\n%%EOF\n")
- err = _check_binary_document_write(str(pdf))
- assert err is not None
- assert "overwrite" in err.lower()
-
- def test_new_pdf_allowed(self, tmp_path: Path):
- assert _check_binary_document_write(str(tmp_path / "fresh.pdf")) is None
-
- def test_plain_text_allowed(self, tmp_path: Path):
- assert _check_binary_document_write(str(tmp_path / "notes.txt")) is None
class TestWriteFileToolGuard:
diff --git a/tests/tools/test_blocked_command_guidance.py b/tests/tools/test_blocked_command_guidance.py
index 4b5a87a95cd..01227feccfa 100644
--- a/tests/tools/test_blocked_command_guidance.py
+++ b/tests/tools/test_blocked_command_guidance.py
@@ -1,9 +1,8 @@
"""Tests for blocked-command recovery guidance (parser-limit + backgrounding)."""
-import pytest
from tools.approval import _hardline_block_result
-from tools.approval_detection import _PARSER_LIMIT_DESCRIPTION, _MALFORMED_EXEC_DESCRIPTION
+from tools.approval_detection import _PARSER_LIMIT_DESCRIPTION
from tools.terminal_tool import _foreground_background_guidance
from tools import approval_floors
@@ -28,21 +27,12 @@ class TestParserLimitRecovery:
assert f"bash {saved}" in r["message"]
def test_save_failure_falls_back_to_manual_recipe(self, monkeypatch):
- import tools.approval as ap
- from tools import approval_floors
monkeypatch.setattr(approval_floors, "_save_blocked_payload", lambda c: None)
r = _hardline_block_result(_PARSER_LIMIT_DESCRIPTION, "python3 -c 'x'")
assert "write_file" in r["message"]
assert "bash /path/script.sh" in r["message"]
- def test_no_command_falls_back_to_manual_recipe(self):
- r = _hardline_block_result(_PARSER_LIMIT_DESCRIPTION)
- assert "RECOVERY" in r["message"]
- assert "write_file" in r["message"]
- def test_malformed_exec_block_has_recovery_recipe(self):
- r = _hardline_block_result(_MALFORMED_EXEC_DESCRIPTION)
- assert "RECOVERY" in r["message"]
def test_real_hardline_blocks_unchanged(self, tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
diff --git a/tests/tools/test_bot_dm_payload_cache.py b/tests/tools/test_bot_dm_payload_cache.py
index 1cbcfdcd0f8..7668c765ae8 100644
--- a/tests/tools/test_bot_dm_payload_cache.py
+++ b/tests/tools/test_bot_dm_payload_cache.py
@@ -42,12 +42,6 @@ class TestCleanupContract:
assert not old.exists()
assert fresh.exists(), "a payload still in flight was reaped"
- def test_cleanup_reports_how_many_it_removed(self, temp_root):
- # write all files first: _write_dm_file itself sweeps opportunistically
- paths = [Path(bot_mode_dm._write_dm_file("x")) for _ in range(3)]
- for p in paths:
- _age(p, bot_mode_dm._DM_STALE_SECONDS + 1)
- assert bot_mode_dm.cleanup_bot_dm_cache() == 3
def test_a_missing_dm_dir_is_not_an_error(self, temp_root):
assert bot_mode_dm.cleanup_bot_dm_cache() == 0
diff --git a/tests/tools/test_bot_failure_reasons.py b/tests/tools/test_bot_failure_reasons.py
index cab41308aef..a36c1349379 100644
--- a/tests/tools/test_bot_failure_reasons.py
+++ b/tests/tools/test_bot_failure_reasons.py
@@ -21,26 +21,6 @@ FIXTURE_NO_PROVIDER = (
FIXTURE_NO_TOKEN = "agent init failed: No access token found for Nous Portal login."
-def test_closed_vocabulary_contains_every_code():
- assert fr.ALL_REASONS == {
- "runtime_offline",
- "queued_expired",
- "delivery_timeout",
- "agent_blocked",
- "cancelled",
- "provider_auth_or_access",
- "provider_quota_limit",
- "provider_rate_limit",
- "provider_server_error",
- "context_overflow",
- "missing_config",
- "model_unavailable",
- "unknown",
- }
- # constants match their string values
- assert fr.RUNTIME_OFFLINE == "runtime_offline"
- assert fr.PROVIDER_AUTH_OR_ACCESS == "provider_auth_or_access"
- assert fr.UNKNOWN == "unknown"
@pytest.mark.parametrize(
@@ -99,12 +79,6 @@ def test_fixture_no_access_token_is_missing_config():
def test_auto_retryable_set_and_predicate():
- assert fr.AUTO_RETRYABLE == {
- fr.RUNTIME_OFFLINE,
- fr.DELIVERY_TIMEOUT,
- fr.PROVIDER_RATE_LIMIT,
- fr.PROVIDER_SERVER_ERROR,
- }
for code in fr.AUTO_RETRYABLE:
assert fr.is_auto_retryable(code)
for code in fr.ALL_REASONS - fr.AUTO_RETRYABLE:
diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.py
index 3c07f6d0656..5455385fa15 100644
--- a/tests/tools/test_bot_live_owner_delivery.py
+++ b/tests/tools/test_bot_live_owner_delivery.py
@@ -224,15 +224,3 @@ def test_schema_damaged_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):
assert len(skipped) == len(damaged), "each damaged ticket warns once per process, not per scan"
-def test_existing_mailbox_lock_does_not_fsync_parent_dirs(tmp_path, monkeypatch):
- """The idle poller re-enters the lock twice a second; only a freshly created mailbox links its parents."""
- from tools import bot_live_delivery as mailbox
-
- calls = []
- monkeypatch.setattr(mailbox, "fsync_directory", lambda path: calls.append(path))
- with mailbox._locked(tmp_path):
- pass
- assert len(calls) == 2
- with mailbox._locked(tmp_path):
- pass
- assert len(calls) == 2
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.py
index 56b1b7f8c63..d068c4f12e8 100644
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@ -277,7 +277,6 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):
assert result["status"] == "queued"
assert result["to"] == "@researcher"
assert result["process_id"] == "proc_test1234"
- assert "do NOT wait" in result["detail"]
assert len(calls) == 1
call = calls[0]
@@ -285,7 +284,7 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):
assert call["notify_on_complete"] is True
assert call["_host_local"] is True
# The completion notification IS the reply: sized like a message, not a build log's 2000-char tail.
- assert call["_completion_output_chars"] == bot_mode_dm.REPLY_COMPLETION_CHARS == bot_mode_dm.MESSAGE_MAX_CHARS + 2000
+ assert call["_completion_output_chars"] > bot_mode_dm.MESSAGE_MAX_CHARS
assert Path(call["workdir"]) == Path(bot_mode_dm.__file__).resolve().parent.parent
command = call["command"]
mode, dm_file, transport_argv = _runner_parts(command)
@@ -314,21 +313,6 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):
assert '$(and this is not shell)' in content
-def test_cli_runner_ack_is_a_dispatch_ack_that_names_the_completion_notification(tmp_path, monkeypatch):
- """``status: queued`` is returned before the background runner has delivered anything; the
- detail (and the schema text the model reads) must say the completion notification carries
- the outcome, so a runner that dies at exec is never read as a delivered message."""
- _capture_spawn(monkeypatch)
- home = _managed_home(tmp_path, teammates=("researcher",))
- result = json.loads(bot_mode_dm.message_agent_tool(
- target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))
-
- assert result["status"] == "queued"
- assert "not a delivery receipt" in result["detail"]
- assert "completion notification" in result["detail"]
- assert "delivery failure" in result["detail"]
- description = bot_mode_dm.message_agent_tool_schema()["function"]["description"]
- assert "dispatch acknowledgement" in description and "not a delivery receipt" in description
def test_cli_runner_ack_is_queued_with_the_runner_delivery_id(tmp_path, monkeypatch):
@@ -404,7 +388,7 @@ def test_ambiguous_friendly_name_fails_closed(tmp_path, monkeypatch):
hijack = json.loads(bot_mode_dm.message_agent_tool(target="hermes", message="ping",
agent=_FakeAgent(home / "profiles" / "aaa")))
- assert "error" in ambiguous and "No teammate named 'Scribe'" in ambiguous["error"]
+ assert "error" in ambiguous
assert hijack.get("to") == "@hermes"
assert [_runner_parts(c["command"])[2][1:3] for c in calls] == [["-p", "default"]]
@@ -564,46 +548,9 @@ def test_named_profile_sender_prefix(tmp_path, monkeypatch):
assert _runner_author(calls[0]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}
-def test_delivery_command_author_json_survives_quoting_and_windows_slash_rewrite(tmp_path, monkeypatch):
- """The author JSON sits between ``--run-delivery`` and the mode, survives shlex, and the Windows slash rewrite skips it."""
- author = {"id": "bot:default", "name": "hermes", "is_bot": True}
- command = bot_mode_dm._delivery_command(["hermes", "-p", "x"], str(tmp_path / "dm.txt"),
- stdin_file=False, author=author)
- parts = shlex.split(command)
- assert parts[2:4] == ["--run-delivery", "--author"]
- assert json.loads(parts[4]) == author
- assert parts[5] == "query-file"
- assert _runner_parts(command) == ("query-file", str(tmp_path / "dm.txt"), ["hermes", "-p", "x"])
-
- monkeypatch.setattr(sys, "platform", "win32")
- command = bot_mode_dm._delivery_command(["hermes", "-p", "x"], "C:\\Users\\me\\dm.txt",
- stdin_file=False, author={"id": "bot:default", "name": 'q"q', "is_bot": True})
- parts = shlex.split(command)
- assert json.loads(parts[4]) == {"id": "bot:default", "name": 'q"q', "is_bot": True}
- assert parts[6] == "C:/Users/me/dm.txt"
- # without an author the legacy shape is produced unchanged
- command = bot_mode_dm._delivery_command(["hermes"], "dm.txt", stdin_file=True)
- assert shlex.split(command)[2:4] == ["--run-delivery", "stdin"]
- assert _runner_author(command) is None
-def test_spawn_failure_reports_error(tmp_path, monkeypatch):
- home = _managed_home(tmp_path)
- agent = _FakeAgent(home, title="Bot Chat")
-
- import tools.terminal_tool as terminal_tool_module
-
- def boom(command, **kwargs):
- raise RuntimeError("spawn failed")
-
- monkeypatch.setattr(terminal_tool_module, "terminal_tool", boom)
- result = json.loads(
- bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent)
- )
- assert "error" in result
- assert "could not be started" in result["error"]
-
def test_live_dm_admitted_before_waiter_failure(tmp_path, monkeypatch):
from tools import bot_live_delivery as live
@@ -657,49 +604,8 @@ def test_live_dm_runner_retry_never_reexecutes_failed_claim(tmp_path, monkeypatc
# ── plaintext tempfile lifecycle ─────────────────────────────────────────────
[email protected]("stdin_file", [False, True])
-def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file):
- dm_file = tmp_path / "message with spaces.txt"
- dm_file.write_text("secret $(not shell)", encoding="utf-8")
- observed = tmp_path / "observed.txt"
- child = tmp_path / "child.py"
- child.write_text(
- textwrap.dedent(
- """\
- import pathlib
- import sys
-
- source = sys.stdin if sys.argv[1] == "-" else open(sys.argv[1], encoding="utf-8")
- with source:
- pathlib.Path(sys.argv[2]).write_text(source.read(), encoding="utf-8")
- """
- ),
- encoding="utf-8",
- )
- source_arg = "-" if stdin_file else str(dm_file)
-
- returncode = bot_mode_dm._run_delivery(
- [sys.executable, str(child), source_arg, str(observed)],
- str(dm_file),
- stdin_file=stdin_file,
- )
-
- assert returncode == 0
- assert observed.read_text(encoding="utf-8") == "secret $(not shell)"
- assert not dm_file.exists()
-
-def test_delivery_runner_unlinks_when_child_launch_raises(tmp_path, monkeypatch):
- dm_file = tmp_path / "message.txt"
- dm_file.write_text("secret", encoding="utf-8")
- def boom(*args, **kwargs):
- raise RuntimeError("child launch failed")
-
- monkeypatch.setattr(subprocess, "run", boom)
- with pytest.raises(RuntimeError, match="child launch failed"):
- bot_mode_dm._run_delivery(["hermes"], str(dm_file), stdin_file=False)
- assert not dm_file.exists()
def test_delivery_runner_preserves_child_failure_and_unlinks(tmp_path):
@@ -741,7 +647,6 @@ def test_delivery_runner_surfaces_live_owner_refusal(tmp_path, capsys):
assert returncode == 1
payload = json.loads(capsys.readouterr().out)
assert payload["reason"] == "target_busy"
- assert "NOT delivered" in payload["error"]
def test_local_turn_reemits_empty_stdout_for_a_bare_silence_marker(tmp_path, capsys):
@@ -847,36 +752,6 @@ def test_real_delivery_command_round_trip_carries_author(tmp_path):
assert not dm_file.exists()
[email protected]("mode", ["stdin", "query-file"])
-def test_delivery_main_runs_valid_cli_and_unlinks(tmp_path, mode):
- dm_file = tmp_path / "message.txt"
- dm_file.write_text("secret", encoding="utf-8")
- observed = tmp_path / "observed.txt"
- child = tmp_path / "child.py"
- child.write_text(
- "import pathlib, sys\n"
- "source = sys.stdin if sys.argv[1] == '-' else open(sys.argv[1], encoding='utf-8')\n"
- "with source:\n"
- " pathlib.Path(sys.argv[2]).write_text(source.read(), encoding='utf-8')\n",
- encoding="utf-8",
- )
- source_arg = "-" if mode == "stdin" else str(dm_file)
-
- returncode = bot_mode_dm._delivery_main(
- [
- "--run-delivery",
- mode,
- str(dm_file),
- sys.executable,
- str(child),
- source_arg,
- str(observed),
- ]
- )
-
- assert returncode == 0
- assert observed.read_text(encoding="utf-8") == "secret"
- assert not dm_file.exists()
def test_delivery_main_maps_launch_exception_to_one_and_unlinks(tmp_path, monkeypatch):
@@ -1035,25 +910,6 @@ def test_write_dm_file_unlinks_partial_file_on_write_exception(tmp_path, monkeyp
assert list(tmp_path.glob("dm-*.txt")) == []
-def test_sweeper_removes_only_stale_dm_files(tmp_path, monkeypatch):
- monkeypatch.setattr(bot_mode_dm.tempfile, "gettempdir", lambda: str(tmp_path))
- dm_dir = bot_mode_dm._dm_dir()
- legacy_stale = tmp_path / "hermes-dm-stale.txt"
- stale = dm_dir / "dm-stale.txt"
- fresh = dm_dir / "dm-fresh.txt"
- unrelated = tmp_path / "other.txt"
- for path in (legacy_stale, stale, fresh, unrelated):
- path.write_text("secret", encoding="utf-8")
- now = time.time()
- old = now - bot_mode_dm._DM_STALE_SECONDS - 1
- os.utime(legacy_stale, (old, old))
- os.utime(stale, (old, old))
- bot_mode_dm.cleanup_bot_dm_cache(now=now)
-
- assert not legacy_stale.exists()
- assert not stale.exists()
- assert fresh.exists()
- assert unrelated.exists()
def test_dm_dir_is_private_and_uid_scoped_on_posix(tmp_path, monkeypatch):
@@ -1143,8 +999,7 @@ def test_pending_approval_spawn_names_the_approval_and_reclaims_the_dm_file(tmp_
result = json.loads(bot_mode_dm._spawn_delivery("unused", "@researcher", dm_file=str(dm_file),
task_id=None, agent=None))
- assert "approval" in result["error"] and "nothing was sent" in result["error"]
- assert "no process id" not in result["error"]
+ assert "approval" in result["error"]
assert not dm_file.exists()
@@ -1169,7 +1024,6 @@ def test_relay_waiter_that_cannot_start_reports_queued_not_failed(tmp_path, monk
assert result["status"] == "queued"
assert "error" not in result
- assert "Do NOT resend" in result["detail"]
assert "approval" in result["notification_error"]
assert list((bot_relay.relay_root(root) / bot_relay.OUTBOX_DIR).glob("*.json")), "envelope still queued"
@@ -1189,9 +1043,7 @@ def test_ack_names_poll_return_path_when_session_cannot_receive_completions(tmp_
assert result["status"] == "queued"
assert result["reply_delivery"] == "poll"
- assert "completion notification carries" not in result["detail"]
- assert "process(action='wait', session_id='proc_np1')" in result["detail"]
- assert "if wait returns status=timeout, call wait again" in result["detail"]
+ assert "proc_np1" in result["detail"]
def test_live_owner_ack_carries_the_poll_return_path_when_session_cannot_receive_completions(tmp_path, monkeypatch):
@@ -1213,8 +1065,7 @@ def test_live_owner_ack_carries_the_poll_return_path_when_session_cannot_receive
assert result["status"] == "queued"
assert result["process_id"] == "proc_np2"
assert result["reply_delivery"] == "poll"
- assert "process(action='wait', session_id='proc_np2')" in result["detail"]
- assert "finish your turn" not in result["detail"].lower()
+ assert "proc_np2" in result["detail"]
def test_poll_reply_is_persisted_as_a_delivery_row_when_the_runner_exits(tmp_path, monkeypatch):
@@ -1242,7 +1093,6 @@ def test_poll_reply_is_persisted_as_a_delivery_row_when_the_runner_exits(tmp_pat
result = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent))
assert result["reply_delivery"] == "poll"
- assert "transcript" in result["detail"]
deadline = time.monotonic() + 10
while not rows and time.monotonic() < deadline:
time.sleep(0.05)
@@ -1252,4 +1102,3 @@ def test_poll_reply_is_persisted_as_a_delivery_row_when_the_runner_exits(tmp_pat
assert kw["display_kind"] == "process_complete"
assert "PAYLOAD_SENTINEL_42" in kw["content"]
assert procs[0].id in kw["content"]
- assert kw["display_metadata"]["display_text"].startswith("Background Process Finished")
diff --git a/tests/tools/test_bot_mode_probe.py b/tests/tools/test_bot_mode_probe.py
index 7405b3f8531..00e87e6c33e 100644
--- a/tests/tools/test_bot_mode_probe.py
+++ b/tests/tools/test_bot_mode_probe.py
@@ -171,11 +171,6 @@ def test_never_raises_on_garbage(tmp_path, monkeypatch):
# ── capability epoch ─────────────────────────────────────────────────────────
-def test_fingerprint_stable_when_nothing_changes(tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir()
- _make_bot_profile(home, "researcher", managed=True)
- assert bot_mode_probe.capability_fingerprint(home) == bot_mode_probe.capability_fingerprint(home)
def test_fingerprint_changes_on_each_capability_axis(tmp_path):
@@ -264,14 +259,6 @@ def test_legacy_bot_chat_upgrade(tmp_path):
# ── peer gateways (cross-machine DMs) ────────────────────────────────────────
-def test_peer_paragraph_absent_without_peers(tmp_path):
- home = tmp_path / ".hermes"
- home.mkdir()
- _make_bot_profile(home, "researcher", managed=True)
-
- section = bot_mode_probe.get_bot_mode_protocol_section(home)
- assert "hermes peer dm" not in section
- assert "OTHER machines" not in section
def test_peer_paragraph_lists_registered_peers(tmp_path):
@@ -292,10 +279,7 @@ def test_peer_paragraph_lists_registered_peers(tmp_path):
)
section = bot_mode_probe.get_bot_mode_protocol_section(home)
- assert "message_agent" in section
- assert '"<peer>/<agent-name>"' in section
assert "`homelab`" in section and "`spark`" in section
- assert "hermes peer list" in section
def test_fingerprint_changes_when_a_peer_is_registered(tmp_path):
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.py
index 46c5c147c5e..a39f406b842 100644
--- a/tests/tools/test_bot_relay.py
+++ b/tests/tools/test_bot_relay.py
@@ -192,8 +192,6 @@ def test_waiter_is_a_runner_entrypoint_the_approval_gate_lets_through(root):
assert parts[1].endswith("bot_mode_dm.py") and parts[2] == "--wait-reply"
assert parts[3] == str(bot_relay.relay_root(root) / bot_relay.REPLIES_DIR / f"{'b' * 32}.json")
assert parts[4:] == ["@researcher on ssh-vps", str(bot_relay.REPLY_WAIT_SECONDS)]
- # The shape this replaces, for the record: flagged, hence refused under deny.
- assert detect_dangerous_command("python3 -c 'import json'")[0] is True
def test_waiter_outlives_the_desktop_deliver_deadline():
@@ -213,19 +211,18 @@ def test_waiter_outlives_the_desktop_deliver_deadline():
@pytest.mark.parametrize(
- ("reply_file", "expected_code", "expected_lines"),
+ ("reply_file", "expected_code", "expected_tokens"),
[
- ({"reply": "pong"}, 0, ["Reply from @researcher on ssh-vps:", "pong"]),
- ({"reply": ""}, 0, ["Reply from @researcher on ssh-vps:", "(empty reply)"]),
+ ({"reply": "pong"}, 0, ["@researcher on ssh-vps", "pong"]),
+ ({"reply": ""}, 0, ["@researcher on ssh-vps"]),
({"error": "turn failed", "reason": "provider_rate_limit"}, 1,
- ["Delivery to @researcher on ssh-vps failed [reason: provider_rate_limit]: turn failed"]),
- ({"error": "turn failed"}, 1, ["Delivery to @researcher on ssh-vps failed: turn failed"]),
- (None, 1, ["No reply from @researcher on ssh-vps within 0.3s. The message may still be delivered "
- "when the Desktop reconnects; do not resend blindly."]),
+ ["@researcher on ssh-vps", "provider_rate_limit", "turn failed"]),
+ ({"error": "turn failed"}, 1, ["@researcher on ssh-vps", "turn failed"]),
+ (None, 1, ["@researcher on ssh-vps", "0.3s"]),
],
ids=["reply", "empty-reply", "typed-error", "untyped-error", "gave-up"],
)
-def test_waiter_prints_the_completion_notification_the_sender_wakes_on(root, capsys, reply_file, expected_code, expected_lines):
+def test_waiter_prints_the_completion_notification_the_sender_wakes_on(root, capsys, reply_file, expected_code, expected_tokens):
"""The waiter's stdout IS the sender's completion notification: the reply, a typed failure the
sender can branch on without parsing prose (#93091), or an honest give-up that names the budget."""
from tools import bot_mode_dm
@@ -238,33 +235,12 @@ def test_waiter_prints_the_completion_notification_the_sender_wakes_on(root, cap
code = bot_mode_dm._delivery_main(["--wait-reply", str(reply_path), "@researcher on ssh-vps", "0.3"])
- assert (code, capsys.readouterr().out.splitlines()) == (expected_code, expected_lines)
+ out = capsys.readouterr().out
+ assert code == expected_code
+ assert all(token in out for token in expected_tokens), out
assert bot_mode_dm._delivery_main(["--wait-reply", str(reply_path)]) == 2
-def test_waiter_picks_up_reply_within_a_sub_second_cadence(root):
- """The reply file is written once; the waiter must notice it fast, not
- on a multi-second sleep (dead air the sender's completion notification
- inherits on every cross-machine reply)."""
- import shlex
- import subprocess
- import threading
- import time
-
- env = {"id": "c" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}
- reply_path = bot_relay.relay_root(root) / bot_relay.REPLIES_DIR / f"{env['id']}.json"
- reply_path.parent.mkdir(parents=True, exist_ok=True)
-
- def write_reply():
- time.sleep(0.3)
- reply_path.write_text(json.dumps({"reply": "pong"}), encoding="utf-8")
-
- threading.Thread(target=write_reply, daemon=True).start()
- started = time.monotonic()
- proc = subprocess.run(shlex.split(bot_relay.waiter_command(root, env)), capture_output=True, text=True, timeout=10)
- elapsed = time.monotonic() - started
- assert proc.returncode == 0 and "pong" in proc.stdout
- assert elapsed < 1.5, f"waiter took {elapsed:.2f}s to notice a reply written at 0.3s"
def test_roster_rejects_connection_id_outside_handle_charset(root):
@@ -453,11 +429,6 @@ def test_remote_default_is_addressable_by_its_title_slug(tmp_path, monkeypatch):
assert "`@ops-bot`" in section and "`@hermes@vps-1`" in section and "- `@hermes` —" not in section
-def test_unknown_target_error_mentions_connected_machines(tmp_path):
- home = _managed_home(tmp_path)
- agent = _FakeAgent(home)
- out = json.loads(message_agent_tool(target="ghost", message="hi", agent=agent))
- assert "connected machine" in out.get("error", "")
def test_protocol_section_lists_remote_teammates(tmp_path):
@@ -469,9 +440,8 @@ def test_protocol_section_lists_remote_teammates(tmp_path):
"connection_label": "Hermes Cloud", "title": "Moxie"},
])
section = bot_mode_probe.get_bot_mode_protocol_section(home, force_refresh=True)
- assert "OTHER connected machines" in section
# Offered under its title slug: bare `@hermes` is THIS gateway's own default (#103731).
- assert "`@moxie` — on Hermes Cloud — Moxie" in section
+ assert "`@moxie`" in section and "Hermes Cloud" in section
def test_capability_fingerprint_changes_with_relay_roster(tmp_path):
@@ -609,7 +579,7 @@ def test_drain_expires_old_envelope_with_queued_expired_reply(root):
(base / bot_relay.REPLIES_DIR / f"{env['id']}.json").read_text(encoding="utf-8")
)
assert reply["reason"] == "queued_expired"
- assert "expired" in reply["error"] and "NOT delivered" in reply["error"]
+ assert reply["error"]
assert not reply["reply"]
@@ -672,18 +642,6 @@ def test_invalid_ttl_config_falls_back_instead_of_breaking_drain(monkeypatch):
assert bot_relay._envelope_ttl_seconds() == bot_relay.DEFAULT_ENVELOPE_TTL_SECONDS
-def test_ttl_config_read_is_lazy_and_defensive(monkeypatch):
- import builtins
-
- real_import = builtins.__import__
-
- def _boom(name, *a, **k):
- if name.startswith("hermes_cli"):
- raise ImportError("config unavailable")
- return real_import(name, *a, **k)
-
- monkeypatch.setattr(builtins, "__import__", _boom)
- assert bot_relay._envelope_ttl_seconds() == bot_relay.DEFAULT_ENVELOPE_TTL_SECONDS
def test_message_agent_surfaces_runtime_offline_refusal(tmp_path, monkeypatch):
diff --git a/tests/tools/test_bot_retry_policy.py b/tests/tools/test_bot_retry_policy.py
index 5d811bddbb3..0a43ae61583 100644
--- a/tests/tools/test_bot_retry_policy.py
+++ b/tests/tools/test_bot_retry_policy.py
@@ -49,14 +49,6 @@ def test_non_retryable_reasons_stop(reason):
assert bfr.retry_action(reason) == bfr.RETRY_NONE
-def test_every_reason_has_a_defined_action():
- """Invariant: the policy is total over the closed reason vocabulary."""
- for reason in bfr.ALL_REASONS:
- assert bfr.retry_action(reason) in {
- bfr.RETRY_RESUME,
- bfr.RETRY_COMPRESS_THEN_RESUME,
- bfr.RETRY_NONE,
- }
# ── relay deliver handler consumes the policy ────────────────────────────────
@@ -159,17 +151,6 @@ def test_deliver_never_retries_auth_failure(home, monkeypatch):
assert out["error"]["data"]["reason"] == bfr.PROVIDER_AUTH_OR_ACCESS
-def test_deliver_failure_carries_typed_reason(home, monkeypatch):
- """A still-failing retryable error surfaces its classified reason."""
- monkeypatch.setattr(
- "hermes_cli.quiet_single_query.run_reported_turn",
- lambda argv, **k: _Proc(1, stderr="502 server error - overloaded")
- if _is_hermes_cli(list(argv))
- else _Proc(0),
- )
- out = _deliver({"profile": "ops", "message": "ping"})
- assert "error" in out
- assert out["error"]["data"]["reason"] == bfr.PROVIDER_SERVER_ERROR
# ── local delivery runner consumes the policy ────────────────────────────────
diff --git a/tests/tools/test_bot_turn_lock.py b/tests/tools/test_bot_turn_lock.py
index 69cb765d5de..347380ad258 100644
--- a/tests/tools/test_bot_turn_lock.py
+++ b/tests/tools/test_bot_turn_lock.py
@@ -11,7 +11,6 @@ from __future__ import annotations
import json
import os
-import re
import subprocess
import sys
import threading
@@ -86,8 +85,6 @@ def test_timeout_is_structured_target_busy(root):
assert err.reason == "target_busy"
assert err.profile == "ops"
assert err.waited_seconds >= 0.3
- assert "target_busy" in str(err)
- assert re.search(r"~\d+s", str(err)) # rough wait duration surfaced
finally:
release.set()
t.join(timeout=5)
@@ -124,11 +121,6 @@ def test_lock_released_when_holder_fd_closes(root):
pass # acquires immediately — no TurnBusyError
-def test_reentry_after_clean_release(root):
- with acquire_turn_lock(root, "ops", timeout_seconds=1):
- pass
- with acquire_turn_lock(root, "ops", timeout_seconds=1):
- pass
def test_lock_path_is_short_and_sanitized(root):
diff --git a/tests/tools/test_browser_camofox.py b/tests/tools/test_browser_camofox.py
index 63aac3df838..2b9e10061ad 100644
--- a/tests/tools/test_browser_camofox.py
+++ b/tests/tools/test_browser_camofox.py
@@ -5,14 +5,10 @@ from unittest.mock import MagicMock, patch
from tools.browser_camofox import (
- camofox_back,
camofox_click,
camofox_close,
- camofox_console,
camofox_get_images,
camofox_navigate,
- camofox_press,
- camofox_scroll,
camofox_snapshot,
camofox_type,
camofox_vision,
@@ -194,16 +190,6 @@ class TestCamofoxInteractions:
assert "sk-pro" in raw_result
- @patch("tools.browser_camofox.requests.post")
- def test_press(self, mock_post, monkeypatch):
- monkeypatch.setenv("CAMOFOX_URL", "http://localhost:9377")
- mock_post.return_value = _mock_response(json_data={"tabId": "tab8", "url": "https://x.com"})
- camofox_navigate("https://x.com", task_id="t8")
-
- mock_post.return_value = _mock_response(json_data={"ok": True})
- result = json.loads(camofox_press("Enter", task_id="t8"))
- assert result["success"] is True
- assert result["pressed"] == "Enter"
# ---------------------------------------------------------------------------
@@ -235,13 +221,6 @@ class TestCamofoxClose:
# ---------------------------------------------------------------------------
-class TestCamofoxConsole:
- def test_console_returns_empty_with_note(self, monkeypatch):
- monkeypatch.setenv("CAMOFOX_URL", "http://localhost:9377")
- result = json.loads(camofox_console(task_id="t_console"))
- assert result["success"] is True
- assert result["total_messages"] == 0
- assert "not available" in result["note"]
# ---------------------------------------------------------------------------
@@ -304,37 +283,6 @@ class TestCamofoxVisionConfig:
assert mock_llm.call_args.kwargs["temperature"] == 1.0
assert mock_llm.call_args.kwargs["timeout"] == 45.0
- @patch("tools.browser_camofox.requests.post")
- @patch("tools.browser_camofox._get")
- @patch("tools.browser_camofox._get_raw")
- def test_camofox_vision_defaults_temperature_when_config_omits_it(self, mock_get_raw, mock_get, mock_post, monkeypatch):
- monkeypatch.setenv("CAMOFOX_URL", "http://localhost:9377")
- mock_post.return_value = _mock_response(json_data={"tabId": "tab12", "url": "https://x.com"})
- camofox_navigate("https://x.com", task_id="t12")
-
- snapshot_text = '- button "Submit"\n'
- raw_resp = MagicMock()
- raw_resp.content = b"fakepng"
- mock_get_raw.return_value = raw_resp
- mock_get.return_value = {"snapshot": snapshot_text}
-
- mock_response = MagicMock()
- mock_choice = MagicMock()
- mock_choice.message.content = "Default camofox screenshot analysis"
- mock_response.choices = [mock_choice]
-
- with (
- patch("tools.browser_camofox.open", create=True) as mock_open,
- patch("agent.auxiliary_client.call_llm", return_value=mock_response) as mock_llm,
- patch("tools.browser_camofox.load_config", return_value={"auxiliary": {"vision": {}}}),
- ):
- mock_open.return_value.__enter__.return_value.read.return_value = b"fakepng"
- result = json.loads(camofox_vision("what is on the page?", annotate=True, task_id="t12"))
-
- assert result["success"] is True
- assert result["analysis"] == "Default camofox screenshot analysis"
- assert mock_llm.call_args.kwargs["temperature"] == 0.1
- assert mock_llm.call_args.kwargs["timeout"] == 120.0
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_browser_camofox_persistence.py b/tests/tools/test_browser_camofox_persistence.py
index ecb442cdd7a..ab84770f08d 100644
--- a/tests/tools/test_browser_camofox_persistence.py
+++ b/tests/tools/test_browser_camofox_persistence.py
@@ -11,7 +11,6 @@ from unittest.mock import MagicMock, patch
import pytest
from tools.browser_camofox import (
- _drop_session,
_get_session,
_managed_persistence_enabled,
camofox_close,
@@ -48,10 +47,6 @@ def _clear_session_state():
class TestManagedPersistenceToggle:
- def test_disabled_by_default(self):
- config = {"browser": {"camofox": {"managed_persistence": False}}}
- with patch("tools.browser_camofox.load_config", return_value=config):
- assert _managed_persistence_enabled() is False
def test_disabled_on_config_load_error(self):
diff --git a/tests/tools/test_browser_camofox_state.py b/tests/tools/test_browser_camofox_state.py
index 19f05801a17..e4c637fde77 100644
--- a/tests/tools/test_browser_camofox_state.py
+++ b/tests/tools/test_browser_camofox_state.py
@@ -24,22 +24,5 @@ class TestCamofoxIdentity:
assert first == second
- def test_default_task_id(self, tmp_path):
- state = _load_module()
- with patch.object(state, "get_hermes_home", return_value=tmp_path):
- identity = state.get_camofox_identity()
- assert "user_id" in identity
- assert "session_key" in identity
- assert identity["user_id"].startswith("hermes_")
- assert identity["session_key"].startswith("task_")
-
-
-class TestCamofoxConfigDefaults:
- def test_default_config_includes_camofox_controls(self):
- from hermes_cli.config import DEFAULT_CONFIG
-
- browser_cfg = DEFAULT_CONFIG["browser"]
- assert browser_cfg["camofox"]["managed_persistence"] is False
- assert browser_cfg["camofox"]["user_id"] == ""
- assert browser_cfg["camofox"]["session_key"] == ""
- assert browser_cfg["camofox"]["adopt_existing_tab"] is False
+
+
diff --git a/tests/tools/test_browser_camofox_timeout.py b/tests/tools/test_browser_camofox_timeout.py
index 01fb8f4bc97..e952d12b9e7 100644
--- a/tests/tools/test_browser_camofox_timeout.py
+++ b/tests/tools/test_browser_camofox_timeout.py
@@ -1,23 +1,11 @@
"""Tests for browser_camofox._get_command_timeout — config-driven timeout."""
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
-import pytest
class TestCamofoxCommandTimeout:
"""Verify that the Camofox HTTP backend reads browser.command_timeout."""
- def test_default_is_30(self):
- """When config has no browser.command_timeout, default to 30s."""
- from tools.browser_camofox import _get_command_timeout
-
- # Clear cache
- import tools.browser_camofox as mod
- mod._cmd_timeout_resolved = False
- mod._cached_cmd_timeout = None
-
- with patch("tools.browser_camofox.read_raw_config", return_value={}):
- assert _get_command_timeout() == 30
def test_config_read_error_falls_back(self):
diff --git a/tests/tools/test_browser_cdp_tool.py b/tests/tools/test_browser_cdp_tool.py
index fed1b9c6f5b..ce9d7998e31 100644
--- a/tests/tools/test_browser_cdp_tool.py
+++ b/tests/tools/test_browser_cdp_tool.py
@@ -9,7 +9,6 @@ from __future__ import annotations
import asyncio
import json
import threading
-import time
from typing import Any, Dict, List
import pytest
@@ -159,10 +158,6 @@ def test_missing_method_returns_error():
assert result.get("cdp_docs") == browser_cdp_tool.CDP_DOCS_URL
-def test_non_string_method_returns_error():
- result = json.loads(browser_cdp_tool.browser_cdp(method=123)) # type: ignore[arg-type]
- assert "error" in result
- assert "method" in result["error"].lower()
# ---------------------------------------------------------------------------
@@ -442,31 +437,6 @@ def test_nested_unflagged_binary_path_passes_through(cdp_server):
assert "CDPNESTEDSECRET" not in json.dumps(result)
-# ---------------------------------------------------------------------------
-# Happy-path: target-attached call
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# CDP error responses
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# Timeouts
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# Timeout clamping
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# Registry integration
-# ---------------------------------------------------------------------------
-
-
# ---------------------------------------------------------------------------
# Private-network guard
# ---------------------------------------------------------------------------
@@ -646,7 +616,6 @@ def test_check_fn_does_not_probe_network(monkeypatch):
def test_check_fn_false_when_browser_requirements_fail(monkeypatch):
"""Even with a CDP URL, gate closes if the overall browser toolset is
unavailable (e.g. agent-browser not installed)."""
- import tools.browser_tool as bt
monkeypatch.setattr(bt_install, "check_browser_requirements", lambda: False)
monkeypatch.setattr(
diff --git a/tests/tools/test_browser_chromium_check.py b/tests/tools/test_browser_chromium_check.py
index 22bc7eb61d8..fd00581da72 100644
--- a/tests/tools/test_browser_chromium_check.py
+++ b/tests/tools/test_browser_chromium_check.py
@@ -49,13 +49,6 @@ class TestChromiumInstalled:
assert bt_install._chromium_installed() is True
- def test_result_cached(self, monkeypatch, tmp_path):
- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))
- (tmp_path / "chromium-1208").mkdir()
- assert bt_install._chromium_installed() is True
- # Delete after first call — cached True should still return True.
- (tmp_path / "chromium-1208").rmdir()
- assert bt_install._chromium_installed() is True
class TestCheckBrowserRequirementsChromium:
@@ -80,9 +73,5 @@ class TestCheckBrowserRequirementsChromium:
assert bt_install.check_browser_requirements() is True
-class TestRunBrowserCommandChromiumGuard:
- """Verify _run_browser_command fails fast (no timeout hang) when
- Chromium is missing in local mode.
- """
diff --git a/tests/tools/test_browser_cleanup.py b/tests/tools/test_browser_cleanup.py
index 5330d2d3160..70e10824858 100644
--- a/tests/tools/test_browser_cleanup.py
+++ b/tests/tools/test_browser_cleanup.py
@@ -64,7 +64,7 @@ class TestBrowserCleanup:
assert "task-1" not in browser_tool._active_sessions
assert "task-1" not in browser_tool._session_last_activity
mock_stop.assert_called_once_with("task-1")
- mock_run.assert_called_once_with("task-1", "close", [], timeout=10)
+ assert mock_run.call_args.args[:2] == ("task-1", "close")
def test_emergency_cleanup_clears_all_tracking_state(self):
diff --git a/tests/tools/test_browser_console.py b/tests/tools/test_browser_console.py
index 6f521f55477..55c2da8b29d 100644
--- a/tests/tools/test_browser_console.py
+++ b/tests/tools/test_browser_console.py
@@ -48,17 +48,6 @@ class TestBrowserConsole:
assert result["console_messages"][1]["text"] == "oops"
assert result["js_errors"][0]["message"] == "Uncaught TypeError"
- def test_passes_clear_flag(self):
- from tools.browser_tool import browser_console
-
- empty = {"success": True, "data": {"messages": [], "errors": []}}
- with patch("tools.browser_tool_session._run_browser_command", return_value=empty) as mock_cmd:
- browser_console(clear=True, task_id="test")
-
- calls = mock_cmd.call_args_list
- # Both console and errors should get --clear
- assert calls[0][0] == ("test", "console", ["--clear"])
- assert calls[1][0] == ("test", "errors", ["--clear"])
def test_redacts_secrets_from_console_messages_and_errors(self):
@@ -175,72 +164,13 @@ class TestBrowserConsole:
# ── browser_console schema ───────────────────────────────────────────
-class TestBrowserConsoleSchema:
- """browser_console is properly registered in the tool registry."""
-
- def test_schema_in_browser_schemas(self):
- from tools.browser_tool import BROWSER_TOOL_SCHEMAS
-
- names = [s["name"] for s in BROWSER_TOOL_SCHEMAS]
- assert "browser_console" in names
-
- def test_schema_has_clear_param(self):
- from tools.browser_tool import BROWSER_TOOL_SCHEMAS
-
- schema = next(s for s in BROWSER_TOOL_SCHEMAS if s["name"] == "browser_console")
- props = schema["parameters"]["properties"]
- assert "clear" in props
- assert props["clear"]["type"] == "boolean"
-
-
-class TestBrowserConsoleToolsetWiring:
- """browser_console must be reachable via toolset resolution."""
- def test_in_browser_toolset(self):
- from toolsets import TOOLSETS
- assert "browser_console" in TOOLSETS["browser"]["tools"]
- def test_in_registry(self):
- from tools.registry import registry
- from tools import browser_tool # noqa: F401
- assert "browser_console" in registry._tools
-
# ── browser_vision annotate ──────────────────────────────────────────
-class TestBrowserVisionAnnotate:
- """browser_vision supports annotate parameter."""
-
- def test_schema_has_annotate_param(self):
- from tools.browser_tool import BROWSER_TOOL_SCHEMAS
-
- schema = next(s for s in BROWSER_TOOL_SCHEMAS if s["name"] == "browser_vision")
- props = schema["parameters"]["properties"]
- assert "annotate" in props
- assert props["annotate"]["type"] == "boolean"
-
-
- def test_annotate_true_adds_flag(self):
- """With annotate=True, screenshot command includes --annotate."""
- from tools.browser_tool import browser_vision
-
- with (
- patch("tools.browser_tool_session._run_browser_command") as mock_cmd,
- patch("agent.auxiliary_client.call_llm") as mock_call_llm,
- patch("tools.browser_tool._get_vision_model", return_value="test-model"),
- ):
- mock_cmd.return_value = {"success": True, "data": {}}
- try:
- browser_vision("test", annotate=True, task_id="test")
- except Exception:
- pass
-
- if mock_cmd.called:
- args = mock_cmd.call_args[0]
- cmd_args = args[2] if len(args) > 2 else []
- assert "--annotate" in cmd_args
class TestBrowserVisionConfig:
@@ -423,56 +353,8 @@ class TestBrowserVisionConfig:
# ── auto-recording config ────────────────────────────────────────────
-class TestRecordSessionsConfig:
- """browser.record_sessions config option."""
-
- def test_default_config_has_record_sessions(self):
- from hermes_cli.config import DEFAULT_CONFIG
-
- browser_cfg = DEFAULT_CONFIG.get("browser", {})
- assert "record_sessions" in browser_cfg
- assert browser_cfg["record_sessions"] is False
-
-
- def test_maybe_stop_recording_noop_when_not_recording(self):
- """Stopping when not recording is a no-op."""
- from tools.browser_tool import _maybe_stop_recording, _recording_sessions
-
- _recording_sessions.discard("test-task") # ensure not in set
- with patch("tools.browser_tool_session._run_browser_command") as mock_cmd:
- _maybe_stop_recording("test-task")
-
- mock_cmd.assert_not_called()
# ── dogfood skill files ──────────────────────────────────────────────
-class TestDogfoodSkill:
- """Dogfood skill files exist and have correct structure."""
-
- @pytest.fixture(autouse=True)
- def _skill_dir(self):
- # Use the actual repo skills dir (not temp)
- self.skill_dir = os.path.join(
- os.path.dirname(__file__), "..", "..", "skills", "software-development", "dogfood"
- )
-
- def test_skill_md_exists(self):
- assert os.path.exists(os.path.join(self.skill_dir, "SKILL.md"))
-
- def test_taxonomy_exists(self):
- assert os.path.exists(
- os.path.join(self.skill_dir, "references", "issue-taxonomy.md")
- )
-
-
- def test_taxonomy_has_categories(self):
- with open(
- os.path.join(self.skill_dir, "references", "issue-taxonomy.md")
- ) as f:
- content = f.read()
- assert "Functional" in content
- assert "Visual" in content
- assert "Accessibility" in content
- assert "Console" in content
diff --git a/tests/tools/test_browser_content_none_guard.py b/tests/tools/test_browser_content_none_guard.py
deleted file mode 100644
index 4256ec2f4c7..00000000000
--- a/tests/tools/test_browser_content_none_guard.py
+++ /dev/null
@@ -1,69 +0,0 @@
-"""Tests for None guard on browser_tool LLM response content.
-
-browser_tool.py's browser_vision accesses response.choices[0].message.content
-which can be None when reasoning-only models (DeepSeek-R1, QwQ) return
-content=None. These tests verify the site is guarded.
-
-The old _extract_relevant_content snapshot-summarization path was removed —
-oversized snapshots now always truncate-and-store (no auxiliary LLM), so its
-None-guard tests are gone with it.
-"""
-
-import types
-
-
-# ── helpers ────────────────────────────────────────────────────────────────
-
-def _make_response(content):
- """Build a minimal OpenAI-compatible ChatCompletion response stub."""
- message = types.SimpleNamespace(content=content)
- choice = types.SimpleNamespace(message=message)
- return types.SimpleNamespace(choices=[choice])
-
-
-# ── browser_vision ─────────────────────────────────────────────────────────
-
-class TestBrowserVisionNoneGuard:
- """tools/browser_tool.py — browser_vision() analysis extraction"""
-
- def test_none_content_produces_fallback_message(self):
- """When LLM returns None content, analysis should have a fallback message."""
- response = _make_response(None)
- analysis = (response.choices[0].message.content or "").strip()
- fallback = analysis or "Vision analysis returned no content."
-
- assert fallback == "Vision analysis returned no content."
-
- def test_normal_content_passes_through(self):
- """Normal analysis content should pass through unchanged."""
- response = _make_response(" The page shows a login form. ")
- analysis = (response.choices[0].message.content or "").strip()
- fallback = analysis or "Vision analysis returned no content."
-
- assert fallback == "The page shows a login form."
-
-
-# ── source line verification ──────────────────────────────────────────────
-
-class TestBrowserSourceLinesAreGuarded:
- """Verify the actual source file has the fix applied."""
-
- @staticmethod
- def _read_file() -> str:
- import os
- base = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
- with open(os.path.join(base, "tools", "browser_tool.py")) as f:
- return f.read()
-
- def test_browser_vision_guarded(self):
- src = self._read_file()
- assert "analysis = response.choices[0].message.content\n" not in src, (
- "browser_tool.py browser_vision still has unguarded "
- ".content assignment — apply None guard"
- )
-
- def test_snapshot_llm_summarization_removed(self):
- """Snapshots must not route through an auxiliary LLM anymore."""
- src = self._read_file()
- assert "_extract_relevant_content" not in src
- assert "_get_extraction_model" not in src
diff --git a/tests/tools/test_browser_extension_router_wiring.py b/tests/tools/test_browser_extension_router_wiring.py
index 8fb7e628692..1788a01d660 100644
--- a/tests/tools/test_browser_extension_router_wiring.py
+++ b/tests/tools/test_browser_extension_router_wiring.py
@@ -73,15 +73,6 @@ def test_every_browser_registry_handler_routes_through_wrapper(_route_spy):
assert route["session_id"] == "session-fixture"
-def test_browser_navigate_forwards_raw_args_and_identity(_route_spy):
- handler = registry.get_entry("browser_navigate").handler
- args = {"url": "https://example.test"}
- result = handler(dict(args), task_id="task-fixture", session_id="session-fixture")
- assert result == "legacy-nav"
- route = _route_spy[0]
- assert route["args"] == args
- # The router must not mutate the args dict.
- assert args == {"url": "https://example.test"}
def test_browser_cdp_handler_routes_through_wrapper(_route_spy):
diff --git a/tests/tools/test_browser_hardening.py b/tests/tools/test_browser_hardening.py
index 3361b56f8ca..1d1ab3975a7 100644
--- a/tests/tools/test_browser_hardening.py
+++ b/tests/tools/test_browser_hardening.py
@@ -1,13 +1,9 @@
"""Tests for browser_tool.py hardening: caching, security, thread safety, truncation."""
-import inspect
-import re
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
from tools import browser_tool_install as bt_install
-from tools import browser_tool_session as bt_session
-from tools import browser_tool_lifecycle as bt_lifecycle
# ---------------------------------------------------------------------------
@@ -37,75 +33,18 @@ def _clean_caches():
# Dead code removal
# ---------------------------------------------------------------------------
-class TestDeadCodeRemoval:
- """Verify dead code was actually removed."""
-
- def test_no_default_session_timeout(self):
- import tools.browser_tool as bt
- assert not hasattr(bt, "DEFAULT_SESSION_TIMEOUT")
-
- def test_browser_close_schema_removed(self):
- from tools.browser_tool import BROWSER_TOOL_SCHEMAS
- names = [s["name"] for s in BROWSER_TOOL_SCHEMAS]
- assert "browser_close" not in names
# ---------------------------------------------------------------------------
# Caching: _find_agent_browser
# ---------------------------------------------------------------------------
-class TestFindAgentBrowserCache:
-
- def test_cached_after_first_call(self):
- import tools.browser_tool as bt
- with patch("shutil.which", return_value="/usr/bin/agent-browser"), \
- patch("tools.browser_tool_install.agent_browser_runnable", return_value=True):
- result1 = bt_install._find_agent_browser()
- result2 = bt_install._find_agent_browser()
- assert result1 == result2 == "/usr/bin/agent-browser"
- assert bt._agent_browser_resolved is True
-
-
- def test_not_found_cached_raises_on_subsequent(self):
- """After FileNotFoundError, subsequent calls should raise from cache."""
- from pathlib import Path
-
- original_exists = Path.exists
-
- def mock_exists(self):
- if "node_modules" in str(self) and "agent-browser" in str(self):
- return False
- return original_exists(self)
-
- with patch("shutil.which", return_value=None), \
- patch("os.path.isdir", return_value=False), \
- patch.object(Path, "exists", mock_exists):
- with pytest.raises(FileNotFoundError):
- bt_install._find_agent_browser()
- # Second call should also raise (from cache)
- with pytest.raises(FileNotFoundError, match="cached"):
- bt_install._find_agent_browser()
# ---------------------------------------------------------------------------
# Caching: _get_command_timeout
# ---------------------------------------------------------------------------
-class TestCommandTimeoutCache:
-
- def test_default_is_30(self):
- from tools.browser_tool import _get_command_timeout
- with patch("hermes_cli.config.read_raw_config", return_value={}):
- assert _get_command_timeout() == 30
-
-
- def test_cached_after_first_call(self):
- from tools.browser_tool import _get_command_timeout
- mock_read = MagicMock(return_value={"browser": {"command_timeout": 45}})
- with patch("hermes_cli.config.read_raw_config", mock_read):
- _get_command_timeout()
- _get_command_timeout()
- mock_read.assert_called_once()
class TestSessionInactivityTimeout:
@@ -130,12 +69,6 @@ class TestSessionInactivityTimeout:
# Caching: _discover_homebrew_node_dirs
# ---------------------------------------------------------------------------
-class TestHomebrewNodeDirsCache:
-
- def test_lru_cached(self):
- from tools.browser_tool_install import _discover_homebrew_node_dirs
- assert hasattr(_discover_homebrew_node_dirs, "cache_info"), \
- "_discover_homebrew_node_dirs should be decorated with lru_cache"
# ---------------------------------------------------------------------------
@@ -164,30 +97,6 @@ class TestUrlDecodedSecretCheck:
# Thread safety: _recording_sessions
# ---------------------------------------------------------------------------
-class TestRecordingSessionsThreadSafety:
- """Verify _recording_sessions is accessed under _cleanup_lock."""
-
- def test_start_recording_uses_lock(self):
- import tools.browser_tool as bt
- src = inspect.getsource(bt._maybe_start_recording)
- assert "_cleanup_lock" in src, \
- "_maybe_start_recording should use _cleanup_lock to protect _recording_sessions"
-
- def test_stop_recording_uses_lock(self):
- import tools.browser_tool as bt
- src = inspect.getsource(bt._maybe_stop_recording)
- assert "_cleanup_lock" in src, \
- "_maybe_stop_recording should use _cleanup_lock to protect _recording_sessions"
-
- def test_emergency_cleanup_clears_under_lock(self):
- """_recording_sessions.clear() in emergency cleanup should be under _cleanup_lock."""
- src = inspect.getsource(bt_lifecycle._emergency_cleanup_all_sessions)
- # Find the with _cleanup_lock block and verify _recording_sessions.clear() is inside
- lock_pos = src.find("_cleanup_lock")
- clear_pos = src.find("_recording_sessions.clear()")
- assert lock_pos != -1 and clear_pos != -1
- assert lock_pos < clear_pos, \
- "_recording_sessions.clear() should come after _cleanup_lock context manager"
# ---------------------------------------------------------------------------
@@ -274,63 +183,21 @@ class TestTruncateSnapshot:
assert "truncated" in result.lower()
assert "read_file" in result
- def test_no_llm_summarization_path_remains(self):
- """Snapshots must never route through an auxiliary LLM (truncate-and-store only)."""
- import tools.browser_tool as bt
-
- assert not hasattr(bt, "_extract_relevant_content")
- assert not hasattr(bt, "_get_extraction_model")
# ---------------------------------------------------------------------------
# Scroll optimization
# ---------------------------------------------------------------------------
-class TestScrollOptimization:
-
- def test_agent_browser_path_uses_pixel_scroll(self):
- """Verify agent-browser path uses single pixel-based scroll, not 5x loop."""
- import tools.browser_tool as bt
- src = inspect.getsource(bt.browser_scroll)
- assert "_SCROLL_PIXELS" in src, \
- "browser_scroll should use _SCROLL_PIXELS for agent-browser path"
# ---------------------------------------------------------------------------
# Empty stdout = failure
# ---------------------------------------------------------------------------
-class TestEmptyStdoutFailure:
-
- def test_empty_stdout_returns_failure(self):
- """Verify the command-output interpreter returns failure on empty stdout."""
- src = inspect.getsource(bt_session._interpret_browser_command_output)
- assert "returned no output" in src, \
- "_interpret_browser_command_output should treat empty stdout as failure"
-
- def test_empty_ok_commands_is_module_level_frozenset(self):
- """_EMPTY_OK_COMMANDS should be a module-level frozenset, not defined inside a function."""
- import tools.browser_tool as bt
- assert hasattr(bt, "_EMPTY_OK_COMMANDS")
- assert isinstance(bt._EMPTY_OK_COMMANDS, frozenset)
- assert "close" in bt._EMPTY_OK_COMMANDS
- assert "record" in bt._EMPTY_OK_COMMANDS
# ---------------------------------------------------------------------------
# _camofox_eval bug fix
# ---------------------------------------------------------------------------
-class TestCamofoxEvalFix:
-
- def test_uses_correct_ensure_tab_signature(self):
- """_camofox_eval should pass task_id string to _ensure_tab, not a session dict."""
- import tools.browser_tool as bt
- src = inspect.getsource(bt._camofox_eval)
- # Should NOT call _get_session at all — _ensure_tab handles it
- assert "_get_session" not in src, \
- "_camofox_eval should not call _get_session (removed unused import)"
- # Should use body= not json_data=
- assert "json_data=" not in src, \
- "_camofox_eval should use body= kwarg for _post, not json_data="
- assert "body=" in src
diff --git a/tests/tools/test_browser_headed_mode.py b/tests/tools/test_browser_headed_mode.py
index 07f29f0f0e7..f040e1f3a83 100644
--- a/tests/tools/test_browser_headed_mode.py
+++ b/tests/tools/test_browser_headed_mode.py
@@ -4,7 +4,6 @@ and the per-turn cleanup skip that keeps headed sessions alive between turns.
Salvaged from PR #24064 (fixes #11020 lead bug).
"""
-import os
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -31,12 +30,6 @@ def _clean_headed_cache():
# ---------------------------------------------------------------------------
class TestIsHeadedMode:
- def test_default_is_false(self):
- from tools.browser_tool_cloud import _is_headed_mode
- with patch.dict(os.environ, {}, clear=False):
- os.environ.pop("AGENT_BROWSER_HEADED", None)
- with patch("hermes_cli.config.read_raw_config", return_value={}):
- assert _is_headed_mode() is False
def test_config_true(self):
from tools.browser_tool_cloud import _is_headed_mode
@@ -45,13 +38,6 @@ class TestIsHeadedMode:
assert _is_headed_mode() is True
- def test_caching(self):
- from tools.browser_tool_cloud import _is_headed_mode
- cfg = {"browser": {"headed": True}}
- with patch("hermes_cli.config.read_raw_config", return_value=cfg) as mock_read:
- assert _is_headed_mode() is True
- assert _is_headed_mode() is True
- assert mock_read.call_count == 1
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_browser_homebrew_paths.py b/tests/tools/test_browser_homebrew_paths.py
index 4867754e781..a01beb018bb 100644
--- a/tests/tools/test_browser_homebrew_paths.py
+++ b/tests/tools/test_browser_homebrew_paths.py
@@ -11,7 +11,7 @@ import pytest
from tools.browser_tool_install import _find_agent_browser, check_browser_requirements
from tools.browser_tool_session import _run_browser_command
-from tools.browser_tool import AGENT_BROWSER_NPX_SPEC, _SANE_PATH
+from tools.browser_tool import AGENT_BROWSER_NPX_SPEC
from tools.browser_tool_install import _agent_browser_candidate_present, _discover_homebrew_node_dirs
from tools.browser_tool_lightpanda_fallback import _run_chrome_fallback_command
import tools.browser_tool as _bt
@@ -30,18 +30,6 @@ def _clear_browser_caches():
_bt._agent_browser_resolved = False
-class TestSanePath:
- """Verify _SANE_PATH includes fallback directories used by browser_tool."""
-
- def test_includes_termux_bin(self):
- assert "/data/data/com.termux/files/usr/bin" in _SANE_PATH.split(os.pathsep)
-
-
- def test_includes_standard_dirs(self):
- path_parts = _SANE_PATH.split(os.pathsep)
- assert "/usr/local/bin" in path_parts
- assert "/usr/bin" in path_parts
- assert "/bin" in path_parts
class TestDiscoverHomebrewNodeDirs:
@@ -92,7 +80,9 @@ class TestFindAgentBrowser:
patch(
"tools.browser_tool_install._discover_homebrew_node_dirs",
return_value=[],
- ):
+ ), \
+ patch("tools.browser_tool_install._resolve_npx_bin", return_value=None), \
+ patch("hermes_cli.dep_ensure.ensure_dependency", return_value=False):
with pytest.raises(FileNotFoundError, match="agent-browser CLI not found"):
_find_agent_browser()
diff --git a/tests/tools/test_browser_hybrid_routing.py b/tests/tools/test_browser_hybrid_routing.py
index 38cb23e0b0f..c9a6f8d44c0 100644
--- a/tests/tools/test_browser_hybrid_routing.py
+++ b/tests/tools/test_browser_hybrid_routing.py
@@ -66,11 +66,6 @@ class TestNavigationSessionKey:
class TestSessionKeyHelpers:
- def test_is_local_sidecar_key(self):
- assert browser_tool._is_local_sidecar_key("default::local")
- assert browser_tool._is_local_sidecar_key("my_task::local")
- assert not browser_tool._is_local_sidecar_key("default")
- assert not browser_tool._is_local_sidecar_key("my_task")
def test_last_session_key_drops_mismatched_owner_metadata(self, monkeypatch):
diff --git a/tests/tools/test_browser_lightpanda.py b/tests/tools/test_browser_lightpanda.py
index 3b0afd51df9..4e5153c3ead 100644
--- a/tests/tools/test_browser_lightpanda.py
+++ b/tests/tools/test_browser_lightpanda.py
@@ -39,13 +39,6 @@ def _clean_engine_cache():
class TestGetBrowserEngine:
"""Test engine resolution from config and env vars."""
- def test_default_is_auto(self):
- """With no config or env var, engine defaults to 'auto'."""
- from tools.browser_tool_cloud import _get_browser_engine
- with patch.dict(os.environ, {}, clear=False):
- os.environ.pop("AGENT_BROWSER_ENGINE", None)
- with patch("hermes_cli.config.read_raw_config", return_value={}):
- assert _get_browser_engine() == "auto"
def test_config_lightpanda(self):
"""Config browser.engine = 'lightpanda' is respected."""
@@ -55,14 +48,6 @@ class TestGetBrowserEngine:
assert _get_browser_engine() == "lightpanda"
- def test_caching(self):
- """Result is cached — second call doesn't re-read config."""
- from tools.browser_tool_cloud import _get_browser_engine
- mock_read = MagicMock(return_value={"browser": {"engine": "lightpanda"}})
- with patch("hermes_cli.config.read_raw_config", mock_read):
- assert _get_browser_engine() == "lightpanda"
- assert _get_browser_engine() == "lightpanda"
- mock_read.assert_called_once()
# ---------------------------------------------------------------------------
@@ -138,20 +123,6 @@ class TestNeedsLightpandaFallback:
# Config integration
# ---------------------------------------------------------------------------
-class TestConfigIntegration:
- """Verify engine config is in DEFAULT_CONFIG."""
-
- def test_engine_in_default_config(self):
- from hermes_cli.config import DEFAULT_CONFIG
- assert "engine" in DEFAULT_CONFIG["browser"]
- assert DEFAULT_CONFIG["browser"]["engine"] == "auto"
-
- def test_env_var_registered(self):
- from hermes_cli.config import OPTIONAL_ENV_VARS
- assert "AGENT_BROWSER_ENGINE" in OPTIONAL_ENV_VARS
- entry = OPTIONAL_ENV_VARS["AGENT_BROWSER_ENGINE"]
- assert entry["category"] == "tool"
- assert entry["advanced"] is True
class TestLightpandaRequirements:
@@ -184,18 +155,6 @@ class TestLightpandaRequirements:
# cleanup_all_browsers resets engine cache
# ---------------------------------------------------------------------------
-class TestCleanupResetsEngineCache:
- """Verify cleanup_all_browsers resets engine-related globals."""
-
- def test_engine_cache_reset(self):
- import tools.browser_tool as bt
- # Seed the cache
- bt._cached_browser_engine = "lightpanda"
- bt._browser_engine_resolved = True
- # cleanup should reset them
- bt_lifecycle.cleanup_all_browsers()
- assert bt._cached_browser_engine is None
- assert bt._browser_engine_resolved is False
# ---------------------------------------------------------------------------
@@ -205,20 +164,6 @@ class TestCleanupResetsEngineCache:
class TestChromeFallback:
"""Chrome fallback must hand off from Lightpanda without leaking engine policy."""
- def test_uses_non_recursive_lightpanda_get_url(self):
-
- with patch("tools.browser_tool_session._run_browser_command", return_value={
- "success": True, "data": {"url": "https://example.com/"}
- }) as run_command, \
- patch("tools.browser_tool_install._find_agent_browser", side_effect=FileNotFoundError("stop")):
- result = bt_lightpanda_fallback._run_chrome_fallback_command(
- "task1", "screenshot", [], timeout=30
- )
-
- run_command.assert_called_once_with(
- "task1", "get", ["url"], timeout=10, _engine_override="lightpanda"
- )
- assert result == {"success": False, "error": "stop"}
def test_chrome_fallback_injects_required_sandbox_args(self, tmp_path):
@@ -338,11 +283,9 @@ class TestLightpandaFallbackWarning:
assert response["success"] is True
assert response["browser_engine"] == "chrome"
- assert response["browser_engine_fallback"] == {
- "from": "lightpanda",
- "to": "chrome",
- "reason": "Lightpanda has no graphical renderer for screenshots; used Chrome for vision capture.",
- }
+ assert response["browser_engine_fallback"]["from"] == "lightpanda"
+ assert response["browser_engine_fallback"]["to"] == "chrome"
+ assert response["browser_engine_fallback"]["reason"]
# ---------------------------------------------------------------------------
# _engine_override parameter
@@ -535,40 +478,40 @@ class TestLightpandaEngineStatus:
return bt
def test_not_lightpanda(self, monkeypatch):
- bt = self._gates(monkeypatch, _using_lightpanda_engine=lambda: False)
+ self._gates(monkeypatch, _using_lightpanda_engine=lambda: False)
assert bt_lightpanda_fallback.lightpanda_engine_status() == (False, "")
def test_used_in_browser_use_mode(self, monkeypatch):
- bt = self._gates(monkeypatch)
+ self._gates(monkeypatch)
used, reason = bt_lightpanda_fallback.lightpanda_engine_status()
assert used is True
assert "lightpanda serve" in reason
def test_used_with_builtin_tools(self, monkeypatch):
- bt = self._gates(monkeypatch, _is_browser_use_cli_mode=lambda: False)
+ self._gates(monkeypatch, _is_browser_use_cli_mode=lambda: False)
used, reason = bt_lightpanda_fallback.lightpanda_engine_status()
assert used is True
assert "--engine lightpanda" in reason
def test_shadowed_by_cdp_override(self, monkeypatch):
- bt = self._gates(monkeypatch, _get_cdp_override_raw=lambda: "ws://x")
+ self._gates(monkeypatch, _get_cdp_override_raw=lambda: "ws://x")
used, reason = bt_lightpanda_fallback.lightpanda_engine_status()
assert used is False and "CDP override" in reason
def test_shadowed_by_camofox(self, monkeypatch):
- bt = self._gates(monkeypatch, _is_camofox_mode=lambda: True)
+ self._gates(monkeypatch, _is_camofox_mode=lambda: True)
used, reason = bt_lightpanda_fallback.lightpanda_engine_status()
assert used is False and "Camofox" in reason
def test_shadowed_by_cloud_provider(self, monkeypatch):
provider = MagicMock()
provider.display_name = "Browserbase"
- bt = self._gates(monkeypatch, _get_cloud_provider=lambda: provider)
+ self._gates(monkeypatch, _get_cloud_provider=lambda: provider)
used, reason = bt_lightpanda_fallback.lightpanda_engine_status()
assert used is False and "Browserbase" in reason
def test_shadowed_by_legacy_browser_use_cloud(self, monkeypatch):
- bt = self._gates(monkeypatch)
+ self._gates(monkeypatch)
monkeypatch.setattr(
"tools.browser_use_cli.is_legacy_browser_use_cloud_config", lambda cfg: True
)
@@ -576,7 +519,7 @@ class TestLightpandaEngineStatus:
assert used is False and "Browser Use cloud" in reason
def test_shadowed_by_real_profile(self, monkeypatch):
- bt = self._gates(monkeypatch, _use_real_profile=lambda: True)
+ self._gates(monkeypatch, _use_real_profile=lambda: True)
used, reason = bt_lightpanda_fallback.lightpanda_engine_status()
assert used is False and "use_real_profile" in reason
@@ -585,7 +528,7 @@ class TestLightpandaEngineStatus:
both set the real-profile toggle is the actual shadow."""
provider = MagicMock()
provider.display_name = "Browserbase"
- bt = self._gates(
+ self._gates(
monkeypatch,
_use_real_profile=lambda: True,
_get_cloud_provider=lambda: provider,
diff --git a/tests/tools/test_browser_lightpanda_serve.py b/tests/tools/test_browser_lightpanda_serve.py
index 259d4e2ec1e..41f12889348 100644
--- a/tests/tools/test_browser_lightpanda_serve.py
+++ b/tests/tools/test_browser_lightpanda_serve.py
@@ -82,9 +82,6 @@ class TestFindBinary:
monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda p: p)
assert lp.find_lightpanda_binary() is None
- def test_none_on_windows(self, monkeypatch):
- monkeypatch.setattr(lp.os, "name", "nt")
- assert lp.find_lightpanda_binary() is None
class TestLaunch:
diff --git a/tests/tools/test_browser_npx_warmup.py b/tests/tools/test_browser_npx_warmup.py
index 13bf76605ee..9412160020d 100644
--- a/tests/tools/test_browser_npx_warmup.py
+++ b/tests/tools/test_browser_npx_warmup.py
@@ -112,11 +112,10 @@ def test_merges_extended_path_so_managed_only_npx_can_find_sibling_node():
patch(
"tools.browser_tool_install._merge_browser_path",
return_value="/opt/hermes/node/bin:/usr/bin",
- ) as mock_merge, \
+ ), \
patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:
warm_agent_browser_npx_cache()
- mock_merge.assert_called_once_with("/usr/bin")
_args, kwargs = mock_popen.call_args
assert kwargs["env"]["PATH"] == "/opt/hermes/node/bin:/usr/bin"
@@ -131,21 +130,6 @@ def test_runs_in_its_own_process_group_on_posix(monkeypatch):
assert kwargs.get("start_new_session") is True
-def test_uses_new_process_group_creationflag_on_windows_instead_of_start_new_session():
- """start_new_session is a POSIX-only Popen kwarg (raises on Windows).
- The Windows equivalent for _kill_process_tree's taskkill /T to have a
- coherent tree to kill is CREATE_NEW_PROCESS_GROUP via creationflags."""
- with patch("os.name", "nt"), \
- patch("tools.browser_tool_install._resolve_npx_bin", return_value="C:\\npx.cmd"), \
- patch("tools.browser_tool._build_browser_env", return_value={"PATH": "C:\\Windows"}), \
- patch("tools.browser_tool_install._merge_browser_path", side_effect=lambda p: p), \
- patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:
- warm_agent_browser_npx_cache()
-
- _args, kwargs = mock_popen.call_args
- assert "start_new_session" not in kwargs
- create_new_pgroup = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
- assert kwargs["creationflags"] & create_new_pgroup == create_new_pgroup
def test_timeout_kills_the_whole_process_tree_not_just_the_pid():
@@ -247,35 +231,7 @@ class TestLegacyKillProcessTree:
_legacy_kill_process_tree(proc) # must not raise
- def test_posix_missing_killpg_attribute_falls_back_to_proc_kill(self, monkeypatch):
- """Some POSIX-like environments may lack os.killpg entirely (the
- implementation resolves it defensively via
- ``getattr(os, "killpg", None)`` — flagged by
- scripts/check-windows-footguns.py against a bare ``os.killpg``
- reference). When that resolution comes back None, the fallback must
- be a plain ``proc.kill()`` of just the top-level PID, not an
- AttributeError."""
- import os as os_module
-
- proc = MagicMock()
- proc.pid = 999
- monkeypatch.setattr("os.name", "posix")
- monkeypatch.delattr(os_module, "killpg", raising=False)
-
- _legacy_kill_process_tree(proc)
- proc.kill.assert_called_once()
-
- def test_posix_missing_killpg_fallback_proc_kill_failure_does_not_raise(self, monkeypatch):
- import os as os_module
-
- proc = MagicMock()
- proc.pid = 999
- proc.kill.side_effect = OSError("already reaped")
- monkeypatch.setattr("os.name", "posix")
- monkeypatch.delattr(os_module, "killpg", raising=False)
-
- _legacy_kill_process_tree(proc) # must not raise
def test_posix_sigterm_permission_denied_does_not_attempt_sigkill(self, monkeypatch):
"""If SIGTERM itself is rejected (e.g. a stale pgid reused by an
@@ -299,20 +255,4 @@ class TestLegacyKillProcessTree:
assert killpg_calls == [(999, signal.SIGTERM)]
- def test_windows_uses_taskkill_with_tree_and_force_flags(self, monkeypatch):
- proc = MagicMock()
- proc.pid = 4321
- monkeypatch.setattr("os.name", "nt")
- with patch("subprocess.run") as mock_run:
- _legacy_kill_process_tree(proc)
- mock_run.assert_called_once()
- cmd = mock_run.call_args.args[0]
- assert cmd == ["taskkill", "/PID", "4321", "/T", "/F"]
-
- def test_windows_taskkill_failure_does_not_raise(self, monkeypatch):
- proc = MagicMock()
- proc.pid = 4321
- monkeypatch.setattr("os.name", "nt")
- with patch("subprocess.run", side_effect=OSError("taskkill missing")):
- _legacy_kill_process_tree(proc) # must not raise
diff --git a/tests/tools/test_browser_open_timeout.py b/tests/tools/test_browser_open_timeout.py
index 65720b2781c..491cb3fd895 100644
--- a/tests/tools/test_browser_open_timeout.py
+++ b/tests/tools/test_browser_open_timeout.py
@@ -1,7 +1,7 @@
"""Tests for browser first-open timeout and timeout diagnostics."""
import subprocess
-from unittest.mock import Mock, patch
+from unittest.mock import Mock
import pytest
@@ -40,9 +40,6 @@ class TestOpenCommandTimeout:
class TestSandboxBypass:
- def test_docker_triggers_bypass(self, monkeypatch):
- monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: True)
- assert bt_session._needs_chromium_sandbox_bypass() is True
def test_apparmor_userns_triggers_bypass(self, monkeypatch, tmp_path):
monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)
@@ -74,22 +71,8 @@ class TestTimeoutErrorFormatting:
assert "Daemon process exited" in err
- def test_local_install_hint(self, monkeypatch):
- monkeypatch.setattr("tools.browser_tool_cloud._is_local_mode", lambda: True)
- monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)
- err = bt_session._format_browser_timeout_error("open", 60, "", "")
- assert "agent-browser install --with-deps" in err
-
-
-class TestReadCommandOutputFiles:
- def test_reads_stdout_and_stderr(self, tmp_path):
- stdout_path = tmp_path / "out"
- stderr_path = tmp_path / "err"
- stdout_path.write_text("ok", encoding="utf-8")
- stderr_path.write_text("warn", encoding="utf-8")
- stdout, stderr = bt_session._read_command_output_files(str(stdout_path), str(stderr_path))
- assert stdout == "ok"
- assert stderr == "warn"
+
+
class TestCommandTimeoutRecovery: