The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py15 (375 removed)
teknium185cd82f1dd27
diff --git a/scripts/ci/check_os_marker_fakes.py b/scripts/ci/check_os_marker_fakes.pyindex f4c1a61c82e..2f6509ed865 100644--- a/scripts/ci/check_os_marker_fakes.py+++ b/scripts/ci/check_os_marker_fakes.py@@ -55,7 +55,6 @@ _BASELINE = frozenset("tests/hermes_cli/test_update_launchd_restart_verification.py","tests/hermes_cli/test_update_launchd_unloaded_gateway.py","tests/hermes_cli/test_urllib_security.py",- "tests/hermes_state/test_state_synchronous_pragma.py","tests/test_hermes_constants.py","tests/tools/test_macos_protected_search.py","tests/tools/test_skills_tool.py",diff --git a/tests/fakes/__init__.py b/tests/fakes/__init__.pydeleted file mode 100644index e69de29bb2d..00000000000diff --git a/tests/fakes/fake_ha_server.py b/tests/fakes/fake_ha_server.pydeleted file mode 100644index b5119da3660..00000000000--- a/tests/fakes/fake_ha_server.py+++ /dev/null@@ -1,301 +0,0 @@-"""Fake Home Assistant server for integration testing.--Provides a real HTTP + WebSocket server (via aiohttp.web) that mimics the-Home Assistant API surface used by hermes-agent:--- ``/api/websocket`` -- WebSocket auth handshake + event push-- ``/api/states`` -- GET all entity states-- ``/api/states/{entity_id}`` -- GET single entity state-- ``/api/services/{domain}/{service}`` -- POST service call-- ``/api/services/persistent_notification/create`` -- POST notification--Usage::-- async with FakeHAServer(token="test-token") as server:- url = server.url # e.g. "http://127.0.0.1:54321"- await server.push_event(event_data)- assert server.received_notifications # verify what arrived-"""--import asyncio-import json-from typing import Any, Dict, List, Optional--import aiohttp-from aiohttp import web-from aiohttp.test_utils import TestServer---# -- Sample entity data ---------------------------------------------------------ENTITY_STATES: List[Dict[str, Any]] = [- {- "entity_id": "light.bedroom",- "state": "on",- "attributes": {"friendly_name": "Bedroom Light", "brightness": 200},- "last_changed": "2025-01-15T10:30:00+00:00",- "last_updated": "2025-01-15T10:30:00+00:00",- },- {- "entity_id": "light.kitchen",- "state": "off",- "attributes": {"friendly_name": "Kitchen Light"},- "last_changed": "2025-01-15T09:00:00+00:00",- "last_updated": "2025-01-15T09:00:00+00:00",- },- {- "entity_id": "sensor.temperature",- "state": "22.5",- "attributes": {- "friendly_name": "Kitchen Temperature",- "unit_of_measurement": "C",- },- "last_changed": "2025-01-15T10:00:00+00:00",- "last_updated": "2025-01-15T10:00:00+00:00",- },- {- "entity_id": "switch.fan",- "state": "on",- "attributes": {"friendly_name": "Living Room Fan"},- "last_changed": "2025-01-15T08:00:00+00:00",- "last_updated": "2025-01-15T08:00:00+00:00",- },- {- "entity_id": "climate.thermostat",- "state": "heat",- "attributes": {- "friendly_name": "Main Thermostat",- "current_temperature": 21,- "temperature": 23,- },- "last_changed": "2025-01-15T07:00:00+00:00",- "last_updated": "2025-01-15T07:00:00+00:00",- },-]---class FakeHAServer:- """In-process fake Home Assistant for integration tests.-- Parameters- ----------- token : str- The expected Bearer token for authentication.- """-- def __init__(self, token: str = "test-token-123"):- self.token = token-- # Observability -- tests inspect these after exercising the adapter.- self.received_service_calls: List[Dict[str, Any]] = []- self.received_notifications: List[Dict[str, Any]] = []-- # Control -- tests push events, server forwards them over WS.- self._event_queue: asyncio.Queue[Dict[str, Any]] = asyncio.Queue()-- # Flag to simulate auth rejection.- self.reject_auth = False-- # Flag to simulate server errors.- self.force_500 = False-- # Internal bookkeeping.- self._app: Optional[web.Application] = None- self._server: Optional[TestServer] = None- self._ws_connections: List[web.WebSocketResponse] = []-- # -- Public helpers ---------------------------------------------------------- @property- def url(self) -> str:- """Base URL of the running server, e.g. ``http://127.0.0.1:12345``."""- assert self._server is not None, "Server not started"- host = self._server.host- port = self._server.port- return f"http://{host}:{port}"-- async def push_event(self, event_data: Dict[str, Any]) -> None:- """Enqueue a state_changed event for delivery over WebSocket."""- await self._event_queue.put(event_data)-- # -- Lifecycle --------------------------------------------------------------- async def start(self) -> None:- self._app = self._build_app()- self._server = TestServer(self._app)- await self._server.start_server()-- async def stop(self) -> None:- # Close any remaining WS connections.- for ws in self._ws_connections:- if not ws.closed:- await ws.close()- self._ws_connections.clear()- if self._server is not None:- await self._server.close()-- async def __aenter__(self) -> "FakeHAServer":- await self.start()- return self-- async def __aexit__(self, *exc) -> None:- await self.stop()-- # -- Application construction ------------------------------------------------ def _build_app(self) -> web.Application:- app = web.Application()- app.router.add_get("/api/websocket", self._handle_ws)- app.router.add_get("/api/states", self._handle_get_states)- app.router.add_get("/api/states/{entity_id}", self._handle_get_state)- # Notification endpoint must be registered before the generic service- # route so that it takes priority.- app.router.add_post(- "/api/services/persistent_notification/create",- self._handle_notification,- )- app.router.add_post(- "/api/services/{domain}/{service}",- self._handle_call_service,- )- return app-- # -- Auth helper ------------------------------------------------------------- def _check_rest_auth(self, request: web.Request) -> Optional[web.Response]:- """Return a 401 response if the Bearer token is wrong, else None."""- auth = request.headers.get("Authorization", "")- if auth != f"Bearer {self.token}":- return web.Response(status=401, text="Unauthorized")- if self.force_500:- return web.Response(status=500, text="Internal Server Error")- return None-- # -- WebSocket handler ------------------------------------------------------- async def _handle_ws(self, request: web.Request) -> web.WebSocketResponse:- ws = web.WebSocketResponse()- await ws.prepare(request)- self._ws_connections.append(ws)-- # Step 1: auth_required- await ws.send_json({"type": "auth_required", "ha_version": "2025.1.0"})-- # Step 2: receive auth- msg = await ws.receive()- if msg.type != aiohttp.WSMsgType.TEXT:- await ws.close()- return ws- auth_msg = json.loads(msg.data)-- # Step 3: validate- if self.reject_auth or auth_msg.get("access_token") != self.token:- await ws.send_json({"type": "auth_invalid", "message": "Invalid token"})- await ws.close()- return ws-- await ws.send_json({"type": "auth_ok", "ha_version": "2025.1.0"})-- # Step 4: subscribe_events- msg = await ws.receive()- if msg.type != aiohttp.WSMsgType.TEXT:- await ws.close()- return ws- sub_msg = json.loads(msg.data)- sub_id = sub_msg.get("id", 1)-- # Step 5: ACK- await ws.send_json({- "id": sub_id,- "type": "result",- "success": True,- "result": None,- })-- # Step 6: push events from queue until closed- try:- while not ws.closed:- try:- event_data = await asyncio.wait_for(- self._event_queue.get(), timeout=0.1,- )- await ws.send_json({- "id": sub_id,- "type": "event",- "event": event_data,- })- except asyncio.TimeoutError:- continue- except (ConnectionResetError, asyncio.CancelledError):- pass-- return ws-- # -- REST handlers ----------------------------------------------------------- async def _handle_get_states(self, request: web.Request) -> web.Response:- err = self._check_rest_auth(request)- if err:- return err- return web.json_response(ENTITY_STATES)-- async def _handle_get_state(self, request: web.Request) -> web.Response:- err = self._check_rest_auth(request)- if err:- return err- entity_id = request.match_info["entity_id"]- for s in ENTITY_STATES:- if s["entity_id"] == entity_id:- return web.json_response(s)- return web.Response(status=404, text=f"Entity {entity_id} not found")-- async def _handle_notification(self, request: web.Request) -> web.Response:- err = self._check_rest_auth(request)- if err:- return err- body = await request.json()- self.received_notifications.append(body)- return web.json_response([])-- async def _handle_call_service(self, request: web.Request) -> web.Response:- err = self._check_rest_auth(request)- if err:- return err- domain = request.match_info["domain"]- service = request.match_info["service"]- body = await request.json()-- self.received_service_calls.append({- "domain": domain,- "service": service,- "data": body,- })-- # Return affected entities (mimics real HA behaviour for light/switch).- affected = []- entity_id = body.get("entity_id")- if entity_id:- for s in ENTITY_STATES:- if s["entity_id"] == entity_id:- if service == "turn_on":- s["state"] = "on"- elif service == "turn_off":- s["state"] = "off"- elif service == "set_temperature" and "temperature" in body:- s["attributes"]["temperature"] = body["temperature"]- # Keep current state or set to heat if off- if s["state"] == "off":- s["state"] = "heat"- # Simulate temperature sensor approaching the target- for ts in ENTITY_STATES:- if ts["entity_id"] == "sensor.temperature":- ts["state"] = str(body["temperature"] - 0.5)- break- affected.append({- "entity_id": entity_id,- "state": s["state"],- "attributes": s.get("attributes", {}),- })- break-- return web.json_response(affected)diff --git a/tests/hermes_state/test_no_locked_readers_gate.py b/tests/hermes_state/test_no_locked_readers_gate.pydeleted file mode 100644index 0664669a9a1..00000000000--- a/tests/hermes_state/test_no_locked_readers_gate.py+++ /dev/null@@ -1,291 +0,0 @@-"""Pattern-C gate: pure-read SessionDB methods must not take the writer lock.--The gateway shares ONE SessionDB across every agent. ``self._lock`` guards-the single writer connection — any read-only query executed under it-convoys every concurrent turn's persistence behind that reader (Pattern C-of the 2026-08 perf triage; #90734 shipped the unlocked-reader subset,-this gate covers the locked-reader subset).--``_read_ctx()`` exists precisely for reads: WAL reader from a bounded-pool, no lock, with a byte-identical fallback to the locked writer when-WAL is off. Reads have no reason to hold the writer lock.--The gate parses ``hermes_state.py`` with ``ast`` and flags any method-that (a) opens ``with self._lock:`` and (b) runs ONLY read statements-(SELECT/PRAGMA-read) on ``self._conn`` inside it — i.e. a pure reader-convoying on the writer lock. Methods that write under the lock are the-lock's legitimate users and pass. New violations fail with the method-name and the fix (route through ``_read_ctx()``).--``SessionDB`` itself is declared in ``hermes_state.py`` as-``class SessionDB(SessionSearchMixin, SessionSchemaMixin,-SessionPortabilityMixin)`` — its actual methods live across four files.-A gate that only opens ``hermes_state.py`` never sees a locked reader-declared in one of the three mixin files, so ``_ALL_STATE_SOURCES`` scans-each of them under their own class name.--Deliberately NOT flagged:-- methods that INSERT/UPDATE/DELETE/REPLACE under the lock (writers);-- read-modify-write methods (the read is ordered against its own write);-- ``_read_ctx``'s own writer-fallback (``yield self._conn`` — no execute);-- SELECTs on ``conn``/other objects (already pooled readers).-"""--from __future__ import annotations--import ast-import re-from pathlib import Path--import pytest--_REPO_ROOT = Path(__file__).resolve().parents[2]-_STATE_PY = _REPO_ROOT / "hermes_state.py"--# SessionDB's own class body lives in hermes_state.py; the rest of its-# methods come from these mixins (see module docstring). Each entry is-# (source file, class name to scan in that file).-_ALL_STATE_SOURCES: list[tuple[Path, str]] = [- (_STATE_PY, "SessionDB"),- (_REPO_ROOT / "hermes_state_search.py", "SessionSearchMixin"),- (_REPO_ROOT / "hermes_state_schema.py", "SessionSchemaMixin"),- (_REPO_ROOT / "hermes_state_portability.py", "SessionPortabilityMixin"),-]--_WRITE_RE = re.compile(- r"^\s*(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER|VACUUM|BEGIN|COMMIT|ANALYZE)\b",- re.IGNORECASE,-)-# PRAGMA is read-only EXCEPT the checkpoint/optimize family, which mutates-# the database file and legitimately belongs on the writer connection.-_PRAGMA_WRITE_RE = re.compile(- r"^\s*PRAGMA\s+(wal_checkpoint|optimize|incremental_vacuum|integrity_check)",- re.IGNORECASE,-)-_READ_RE = re.compile(r"^\s*(SELECT|PRAGMA)\b", re.IGNORECASE)--# Methods allowed to keep a pure-read body under the writer lock, each with-# the reason. Keep this list SHRINKING — never add to it without the same-# scrutiny a new blocking call would get.-_ALLOWED_LOCKED_READERS: dict[str, str] = {- # get_meta stays on the writer lock BY DESIGN (see its inline comment):- # fts_rebuild_step reads rebuild progress before entering a write- # transaction, and a pooled WAL reader sees only committed data — the- # writer's own just-staged meta updates would be invisible to it.- "get_meta": "read-your-writes: rebuild progress read before write txn",-}---def _first_sql_text(call: ast.Call) -> str | None:- """Best-effort SQL text from an execute()'s first argument."""- if not call.args:- return None- arg = call.args[0]- text = None- if isinstance(arg, ast.Constant) and isinstance(arg.value, str):- text = arg.value- elif isinstance(arg, ast.JoinedStr):- parts = [- v.value for v in arg.values- if isinstance(v, ast.Constant) and isinstance(v.value, str)- ]- text = "".join(parts)- if not text or not text.strip():- return None- return text.strip()---def _is_self_conn_execute(call: ast.Call, aliases: set[str]) -> bool:- """Match ``self._conn.execute*`` and ``<alias>.execute*`` where the- alias was bound from ``self._conn`` (``conn = self._conn``)."""- f = call.func- if not (- isinstance(f, ast.Attribute)- and f.attr in ("execute", "executemany", "executescript")- ):- return False- target = f.value- if (- isinstance(target, ast.Attribute)- and target.attr == "_conn"- and isinstance(target.value, ast.Name)- and target.value.id == "self"- ):- return True- return isinstance(target, ast.Name) and target.id in aliases---def _collect_conn_aliases(method: ast.AST) -> set[str]:- """Names bound from ``self._conn`` anywhere in the method body."""- aliases: set[str] = set()- for node in ast.walk(method):- if isinstance(node, ast.Assign) and isinstance(node.value, ast.Attribute):- v = node.value- if (- v.attr == "_conn"- and isinstance(v.value, ast.Name)- and v.value.id == "self"- ):- for t in node.targets:- if isinstance(t, ast.Name):- aliases.add(t.id)- return aliases---def _is_self_lock_with(item: ast.withitem) -> bool:- ctx = item.context_expr- return (- isinstance(ctx, ast.Attribute)- and ctx.attr == "_lock"- and isinstance(ctx.value, ast.Name)- and ctx.value.id == "self"- )---def _scan_locked_readers(- state_py: "Path | None" = None, class_name: str = "SessionDB"-) -> list[str]:- target = state_py if state_py is not None else _STATE_PY- tree = ast.parse(target.read_text(encoding="utf-8"))- violations: list[str] = []-- session_db = None- for node in tree.body:- if isinstance(node, ast.ClassDef) and node.name == class_name:- session_db = node- break- assert session_db is not None, f"{class_name} class not found in {target}"-- for method in session_db.body:- if not isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)):- continue- aliases = _collect_conn_aliases(method)- for node in ast.walk(method):- if not isinstance(node, ast.With):- continue- if not any(_is_self_lock_with(i) for i in node.items):- continue- reads, writes, unknown = 0, 0, 0- for inner in ast.walk(node):- if isinstance(inner, ast.Call) and _is_self_conn_execute(inner, aliases):- word_full = _first_sql_text(inner)- word = word_full.split(None, 1)[0].upper() if word_full else None- if word is None:- # SQL held in a variable or built f-string: the- # scanner cannot prove it reads. A lock block whose- # ONLY statements are unprovable is still flagged- # below — writers name their verbs in literals- # throughout this file, so opacity correlates with- # composed SELECTs, and silently skipping these is- # how 5 readers hid from the first version of this- # gate.- unknown += 1- elif _PRAGMA_WRITE_RE.match(word_full or ""):- writes += 1- elif _WRITE_RE.match(word):- writes += 1- elif _READ_RE.match(word):- reads += 1- else:- unknown += 1- # Method calls under the lock may write internally- # (e.g. self._execute_write, cursor ops) — treat any- # self.<something>() as potentially writing.- elif isinstance(inner, ast.Call):- f = inner.func- if (- isinstance(f, ast.Attribute)- and isinstance(f.value, ast.Name)- and f.value.id == "self"- and (- "write" in f.attr- or "commit" in f.attr- or f.attr.startswith(("set_", "record_", "insert_",- "update_", "delete_", "clear_"))- )- ):- writes += 1- if writes == 0 and (reads > 0 or unknown > 0):- if method.name not in _ALLOWED_LOCKED_READERS:- kind = "pure-read" if unknown == 0 else "no-proven-write"- violations.append(- f"{method.name} (line {node.lineno}): {kind} "- f"body under `with self._lock:` — route through "- f"_read_ctx() instead (or add a justified "- f"allowlist entry)"- )- return violations---def _scan_all_state_sources() -> list[str]:- """Run ``_scan_locked_readers`` over every file that contributes methods- to ``SessionDB`` — the class body in ``hermes_state.py`` plus each mixin- it inherits from (see module docstring). Violations are prefixed with- their source filename since methods can share names across mixins.- """- violations: list[str] = []- for path, class_name in _ALL_STATE_SOURCES:- for v in _scan_locked_readers(path, class_name):- violations.append(f"{path.name}: {v}")- return violations---class TestNoPureReadersUnderWriterLock:- def test_no_locked_pure_readers(self):- violations = _scan_all_state_sources()- assert violations == [], (- "Pure-read SessionDB methods holding the writer lock "- "(Pattern C — every concurrent turn's persistence convoys "- "behind these reads):\n " + "\n ".join(violations)- )-- def test_gate_detects_a_locked_reader(self, tmp_path):- """Sabotage self-check: the scanner must flag a synthetic violation."""- sabotage = (- "class SessionDB:\n"- " def innocent_writer(self):\n"- " with self._lock:\n"- " self._conn.execute(\"UPDATE t SET x = 1\")\n"- " def guilty_reader(self):\n"- " with self._lock:\n"- " return self._conn.execute(\"SELECT 1\").fetchone()\n"- " def guilty_alias_reader(self):\n"- " with self._lock:\n"- " conn = self._conn\n"- " return conn.execute(\"SELECT 2\").fetchone()\n"- " def guilty_variable_sql(self, query):\n"- " with self._lock:\n"- " return self._conn.execute(query).fetchall()\n"- " def innocent_variable_writer(self, query):\n"- " with self._lock:\n"- " self._conn.execute(query)\n"- " self._conn.execute(\"UPDATE t SET x = 2\")\n"- )- p = tmp_path / "fake_state.py"- p.write_text(sabotage, encoding="utf-8")- violations = _scan_locked_readers(p)- flagged = {v.split(" ")[0] for v in violations}- assert flagged == {- "guilty_reader", "guilty_alias_reader", "guilty_variable_sql"- }, violations-- def test_scan_all_state_sources_visits_every_mixin_file(self, tmp_path):- """Sabotage self-check for the multi-file scope itself: a locked- reader planted in a MIXIN file (not hermes_state.py) must still be- caught. Guards against the gate's scope silently narrowing back to- one file — exactly how the real 2026-08 gap (9 locked readers across- three mixin files, invisible to the single-file scanner) happened.- """- mixin_sabotage = (- "class FakeMixin:\n"- " def guilty_mixin_reader(self):\n"- " with self._lock:\n"- " return self._conn.execute(\"SELECT 1\").fetchone()\n"- )- p = tmp_path / "fake_mixin.py"- p.write_text(mixin_sabotage, encoding="utf-8")-- violations = [- f"{p.name}: {v}" for v in _scan_locked_readers(p, "FakeMixin")- ]- assert any("guilty_mixin_reader" in v for v in violations), violationsdiff --git a/tests/hermes_state/test_replace_messages_archive_siblings.py b/tests/hermes_state/test_replace_messages_archive_siblings.pyindex a2decc87907..c401205d213 100644--- a/tests/hermes_state/test_replace_messages_archive_siblings.py+++ b/tests/hermes_state/test_replace_messages_archive_siblings.py@@ -79,26 +79,6 @@ class TestAcpPersistPreservesArchives:]assert [m["content"] for m in live] == ["rewritten", "rewritten answer"]- def test_persist_source_has_no_failopen_probe(self):- """The fail-open has_archived_messages probe must stay dead in _persist.-- Guards the #80216 bug class at the source level: a probe that fails- open (``except: has_archived = False``) silently reintroduces the- destructive replace. ``active_only=True`` must be unconditional.- """- import inspect- import acp_adapter.session as acp_session-- src = inspect.getsource(acp_session.SessionManager._persist)- # Assert on the CALL, not a local-variable name — a reintroduced probe- # under any local name (archived = db.has_archived_messages(...))- # must still trip this guard. The explanatory comment in _persist- # writes the name as "(has_archived_messages)" (paren BEFORE the- # name), so the call-shaped substring doesn't false-positive on it.- assert "has_archived_messages(" not in src, (- "_persist re-grew a has_archived_messages probe — #80216 class"- )- assert "active_only=True" in srcdef test_fresh_session_active_only_equals_full_replace(self, state_db):"""On a never-compacted session active_only=True must behave exactly@@ -124,39 +104,6 @@ class TestAcpPersistPreservesArchives:assert _archived_count(state_db, sid) == 0-class TestTuiPromptTruncationPreservesArchives:- def test_truncation_source_uses_active_only(self):- """The edit/regenerate persistence call must pass active_only=True."""- import inspect- import tui_gateway.methods_prompt as mp-- src = inspect.getsource(mp)- # The truncation write is the only replace_messages call in the module;- # it must carry active_only=True.- import re- calls = re.findall(r"db\.replace_messages\([^)]*\)", src, re.S)- assert calls, "expected the truncation replace_messages call"- for call in calls:- assert "active_only=True" in call, (- f"bare replace_messages in methods_prompt — #80216 class: {call}"- )-- def test_truncation_write_keeps_archived_rows(self, state_db):- """Drive the exact write shape methods_prompt now performs against a- compacted session and assert the archive survives."""- sid = "tui-compacted"- _seed_compacted_session(state_db, sid)- assert _archived_count(state_db, sid) == 4-- truncated = [{"role": "user", "content": "kept head"}]- state_db.replace_messages(sid, truncated, active_only=True)-- assert _archived_count(state_db, sid) == 4- live = [- m for m in state_db.get_messages_as_conversation(sid)- if m.get("role") in ("user", "assistant")- ]- assert [m["content"] for m in live] == ["kept head"]class TestArchiveDroppedIsRecoverable:diff --git a/tests/hermes_state/test_schema_read_probe.py b/tests/hermes_state/test_schema_read_probe.pyindex 4de30263eea..ca4ffe69356 100644--- a/tests/hermes_state/test_schema_read_probe.py+++ b/tests/hermes_state/test_schema_read_probe.py@@ -99,5 +99,3 @@ class TestSchemaReadProbeStatements:finally:conn.close()- def test_probe_statements_are_cached(self):- assert schema_read_probe_statements() is schema_read_probe_statements()diff --git a/tests/hermes_state/test_search_slow_query_log.py b/tests/hermes_state/test_search_slow_query_log.pydeleted file mode 100644index cbcbecb11d7..00000000000--- a/tests/hermes_state/test_search_slow_query_log.py+++ /dev/null@@ -1,60 +0,0 @@-"""Tests for the session-search slow-query log (salvaged from PR #65544)."""--import logging--import pytest--from hermes_state import SessionDB---def db(tmp_path):- d = SessionDB(db_path=tmp_path / "state.db")- d.create_session(session_id="s1", source="cli", model="m")- d.append_message("s1", role="user", content="hello graphiti 일본 MCP 정리")- yield d- d.close()---def test_slow_log_emitted_at_zero_threshold(db, monkeypatch, caplog):- monkeypatch.setenv("HERMES_SEARCH_SLOW_MS", "0")- with caplog.at_level(logging.INFO, logger="hermes_state"):- rows = db.search_messages("graphiti", limit=5)- assert rows- slow = [r for r in caplog.records if "slow session search" in r.getMessage()]- assert slow, "threshold 0 must log every search"- msg = slow[0].getMessage()- assert "path=" in msg and "rows=1" in msg---def test_no_log_under_threshold(db, monkeypatch, caplog):- monkeypatch.setenv("HERMES_SEARCH_SLOW_MS", "60000")- with caplog.at_level(logging.INFO, logger="hermes_state"):- db.search_messages("graphiti", limit=5)- assert not [r for r in caplog.records if "slow session search" in r.getMessage()]---def test_path_attribution(db):- # Without the cjk tokenizer loaded, routing matches the pre-cjk shape.- assert db._describe_search_path("graphiti OR neo4j") == "fts5"- assert db._describe_search_path("우선순위 캘린더") == "trigram"- assert db._describe_search_path("일본 MCP") == "like_scan"---def test_path_attribution_cjk_available(db):- # With the bigram index available, CJK queries (including 2-char terms)- # route to fts_cjk; lone 1-char CJK runs keep the LIKE route.- db._fts_cjk_available = True- try:- assert db._describe_search_path("일본 MCP") == "fts_cjk"- assert db._describe_search_path("우선순위 캘린더") == "fts_cjk"- assert db._describe_search_path("가 alone") == "like_scan"- assert db._describe_search_path("graphiti OR neo4j") == "fts5"- finally:- db._fts_cjk_available = False---def test_results_unchanged_by_wrapper(db, monkeypatch):- monkeypatch.setenv("HERMES_SEARCH_SLOW_MS", "0")- rows = db.search_messages("graphiti", limit=5)- assert rows and rows[0]["session_id"] == "s1"diff --git a/tests/hermes_state/test_session_db_context_manager.py b/tests/hermes_state/test_session_db_context_manager.pyindex 7cc51b0633d..43bf33c6317 100644--- a/tests/hermes_state/test_session_db_context_manager.py+++ b/tests/hermes_state/test_session_db_context_manager.py@@ -49,18 +49,6 @@ def test_with_block_closes_the_handle(tmp_path):assert _live_count(path) == 0-def test_enter_returns_the_same_handle(tmp_path):- """``with SessionDB(...) as db`` must bind the instance, not a wrapper.-- Returning anything else would silently break every attribute access in the- body, so this is cheap insurance on the one line that is easy to get wrong.- """- db = SessionDB(db_path=tmp_path / "state.db")-- with db as entered:- assert entered is db-- assert db._conn is Nonedef test_exception_inside_the_block_still_closes_and_propagates(tmp_path):diff --git a/tests/hermes_state/test_session_db_read_conn_pool.py b/tests/hermes_state/test_session_db_read_conn_pool.pyindex cdb7b582679..b98e564923a 100644--- a/tests/hermes_state/test_session_db_read_conn_pool.py+++ b/tests/hermes_state/test_session_db_read_conn_pool.py@@ -209,29 +209,6 @@ def test_read_open_failure_backs_off_but_recovers(db):db._close_read_conn(recovered)-def test_checkout_seam_is_the_single_acquisition_point(db):- """``_read_ctx`` must acquire via ``_checkout_read_conn`` and nothing else.-- If a future edit re-inlines the pool checkout into ``_read_ctx``, patching- ``_get_read_conn`` silently exercises nothing whenever the pool is warm --- which is exactly how the writer-lock fallback test below would rot into a- no-op without failing.- """- calls = []- original = db._checkout_read_conn-- def _spy():- calls.append(1)- return original()-- db._checkout_read_conn = _spy- try:- with db._read_ctx():- pass- finally:- db._checkout_read_conn = original- assert calls, "_read_ctx must route acquisition through _checkout_read_conn"def test_fallback_to_locked_writer_when_read_conn_unavailable(db, monkeypatch):@@ -500,7 +477,6 @@ def test_idle_permits_are_reclaimed_from_a_peer_instance(db):@pytest.mark.requires_waldef test_peak_is_bounded_across_many_database_files(tmp_path):"""Read connections must be capped for the PROCESS, not just per file."""- import hermes_statefrom hermes_state import SessionDB, _READ_POOL_MAXfrom hermes_state_readpool import _READ_POOL_PROCESS_MAXdiff --git a/tests/hermes_state/test_session_db_read_path_split.py b/tests/hermes_state/test_session_db_read_path_split.pyindex 67e57abb671..db488a85c0a 100644--- a/tests/hermes_state/test_session_db_read_path_split.py+++ b/tests/hermes_state/test_session_db_read_path_split.py@@ -26,33 +26,8 @@ def db(tmp_path):d.close()-def test_read_conn_is_per_thread(db):- conns = {}-- def grab(key):- conns[key] = db._get_read_conn()-- t1 = threading.Thread(target=grab, args=(1,))- t2 = threading.Thread(target=grab, args=(2,))- t1.start(); t2.start(); t1.join(); t2.join()- assert conns[1] is not None and conns[2] is not None- assert conns[1] is not conns[2]-def test_read_conn_reused_via_pool(db):- """Reuse is now the pool's job, not a per-thread memo.-- The old contract (``_get_read_conn()`` returns the same object twice on one- thread) was the leak: that memo pinned one unclosable connection per- (SessionDB x thread) forever. ``_get_read_conn`` now always opens a fresh- connection and reuse happens via checkout/return, so assert on that.- """- with db._read_ctx() as first:- assert first is not None- with db._read_ctx() as second:- assert second is first, "sequential readers must reuse the pooled conn"@pytest.mark.requires_waldiff --git a/tests/hermes_state/test_sqlite_lock_safe_inspection.py b/tests/hermes_state/test_sqlite_lock_safe_inspection.pyindex 9eaea87b53c..92978296740 100644--- a/tests/hermes_state/test_sqlite_lock_safe_inspection.py+++ b/tests/hermes_state/test_sqlite_lock_safe_inspection.py@@ -67,7 +67,10 @@ def _make_db(path, journal_mode: str) -> None:conn = sqlite3.connect(str(path), isolation_level=None)conn.execute(f"PRAGMA journal_mode={journal_mode}")conn.execute("CREATE TABLE t(v TEXT)")+ # One transaction: autocommit would fsync 200 times (~10 s on a loaded disk).+ conn.execute("BEGIN")conn.executemany("INSERT INTO t(v) VALUES (?)", [(f"row{i}",) for i in range(200)])+ conn.execute("COMMIT")conn.close()@@ -226,8 +229,10 @@ def test_probe_and_connect_do_not_race(tmp_path, clean_registry, monkeypatch):def slow_open(*args, **kwargs):handle = real_open(*args, **kwargs)inside_read.set()- # Hold the descriptor open while the writer tries to get in.- may_close.wait(10)+ # Hold the descriptor open while the writer tries to get in. With a+ # correct guard the writer is blocked and this always times out, so+ # keep it short; a broken guard lets the writer set it immediately.+ may_close.wait(2)return handledef writer():diff --git a/tests/hermes_state/test_sqlite_wal_reset_gate.py b/tests/hermes_state/test_sqlite_wal_reset_gate.pyindex e6baa623e85..0259a7a1beb 100644--- a/tests/hermes_state/test_sqlite_wal_reset_gate.py+++ b/tests/hermes_state/test_sqlite_wal_reset_gate.py@@ -13,13 +13,11 @@ import sqlite3import subprocessimport sysimport time-from types import SimpleNamespaceimport pytest-import hermes_stateimport hermes_state_wal-from hermes_state_wal import apply_wal_with_fallback, is_sqlite_wal_reset_vulnerable, sqlite_source_id+from hermes_state_wal import apply_wal_with_fallback, is_sqlite_wal_reset_vulnerable@pytest.fixture(autouse=True)@@ -65,8 +63,6 @@ class TestApplyWalWalResetGate:mode = apply_wal_with_fallback(conn, db_label="fresh.db")assert mode == "delete"assert conn.execute("PRAGMA journal_mode").fetchone()[0].lower() == "delete"- assert any("instead of enabling WAL" in r.getMessage() for r in caplog.records)- assert any(sys.executable in r.getMessage() for r in caplog.records)conn.close()def test_existing_wal_left_alone_when_vulnerable(@@ -94,27 +90,11 @@ class TestApplyWalWalResetGate:assert mode == "wal"assert conn.execute("PRAGMA journal_mode").fetchone()[0].lower() == "wal"assert conn.execute("SELECT x FROM t").fetchone()[0] == 42- assert any("already in WAL mode" in r.getMessage() for r in caplog.records)- # Must not attempt a live journal_mode flip.- assert not any(- "instead of enabling WAL" in r.getMessage() for r in caplog.records- )finally:conn.close()- def test_warning_deduped_per_label(self, tmp_path, monkeypatch, caplog):- monkeypatch.setattr(- hermes_state_wal, "is_sqlite_wal_reset_vulnerable", lambda version_info=None: True- )- with caplog.at_level("WARNING", logger="hermes_state"):- for name in ("a.db", "a.db", "b.db"):- conn = sqlite3.connect(str(tmp_path / name))- apply_wal_with_fallback(conn, db_label=name)- conn.close()- warnings = [r for r in caplog.records if "WAL-reset" in r.getMessage()]- assert len(warnings) == 2_HOLDER_SCRIPT = """@@ -390,30 +370,3 @@ class TestNoDowngradeUnderConcurrentOpeners:-def test_doctor_warns_without_adding_issues(monkeypatch, tmp_path, capsys):- """Vulnerable SQLite is warn-only in doctor — not a blocking issues[] entry."""- from hermes_cli.doctor import run_doctor-- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: home)- monkeypatch.setattr(- hermes_state_wal, "is_sqlite_wal_reset_vulnerable", lambda version_info=None: True- )- monkeypatch.setattr(hermes_state_wal, "sqlite_source_id", lambda: "testid-abc")- monkeypatch.setattr(sqlite3, "sqlite_version", "3.50.4", raising=False)-- args = SimpleNamespace(fix=False, ack=None)- try:- run_doctor(args)- except SystemExit:- pass-- out = capsys.readouterr().out- assert "SQLite" in out- assert "3.50.4" in out- assert "WAL-reset" in out- assert "hermes update" in out- # No longer appended to the blocking issues summary.- assert "Linked SQLite is vulnerable" not in outdiff --git a/tests/hermes_state/test_state_db_corrupt_quarantine.py b/tests/hermes_state/test_state_db_corrupt_quarantine.pyindex 4228abf6603..f6a136d63b2 100644--- a/tests/hermes_state/test_state_db_corrupt_quarantine.py+++ b/tests/hermes_state/test_state_db_corrupt_quarantine.py@@ -101,11 +101,6 @@ class TestQuarantinedHandleStopsTouchingTheFile:db.close()assert not any("wal_checkpoint" in sql for sql in recorder.recorded)assert db._conn is None- assert any(- "Skipping the close-time WAL checkpoint" in rec.getMessage()- and "hermes sessions recover" in rec.getMessage()- for rec in caplog.records- )def test_close_disables_sqlite_internal_checkpoint_on_py312(self, tmp_path):"""Quarantine must also stop SQLite's own last-connection checkpoint.diff --git a/tests/hermes_state/test_state_db_malformed_repair.py b/tests/hermes_state/test_state_db_malformed_repair.pyindex 54a31fd4ad0..4ae824c5a11 100644--- a/tests/hermes_state/test_state_db_malformed_repair.py+++ b/tests/hermes_state/test_state_db_malformed_repair.py@@ -747,7 +747,7 @@ def test_repair_restore_matches_canonical_on_vulnerable_sqlite(assert _mode_of(db_path) == "delete"-def test_repair_logs_mode_change_when_probe_succeeded(+def test_repair_reports_mode_change_when_probe_succeeded(tmp_path, caplog, monkeypatch):"""When the pre-surgery probe read the file (header intact), the@@ -775,34 +775,11 @@ def test_repair_logs_mode_change_when_probe_succeeded(assert report["repaired"] is Trueassert report["journal_mode_before"] == "delete"assert _mode_of(db_path) == "wal"- assert any(- "changed journal_mode" in r.getMessage() for r in caplog.records- ), f"expected the mode flip to be logged; got: {[r.getMessage() for r in caplog.records]}"-def test_repair_logs_nothing_when_mode_already_matches(- tmp_path, caplog, monkeypatch-):- """FTS-only corruption keeps the WAL bit; the restore is then a no-op and- must not emit a mode-flip WARNING."""- import logging-- db_path = tmp_path / "state.db"- _configure_journal_mode(monkeypatch, tmp_path, "wal")- _build_healthy_db(db_path)- _corrupt_duplicate_fts(db_path)- with caplog.at_level(logging.WARNING, logger="hermes_state"):- report = repair_state_db_schema(db_path)-- assert report["repaired"] is True- assert _mode_of(db_path) == "wal"- assert not any(- "changed journal_mode" in r.getMessage() for r in caplog.records- )--def test_repair_restore_failure_is_nonfatal_and_logged(+def test_repair_restore_failure_is_nonfatal(tmp_path, caplog, monkeypatch):"""When the canonical restore path raises (locked/unsupported fs), the@@ -830,10 +807,6 @@ def test_repair_restore_failure_is_nonfatal_and_logged(assert report["repaired"] is Trueassert _mode_of(db_path) == "delete"- assert any(- "journal-mode restore failed" in r.getMessage()- for r in caplog.records- )def test_repair_honors_configured_delete_mode(tmp_path, monkeypatch):diff --git a/tests/hermes_state/test_state_db_stats.py b/tests/hermes_state/test_state_db_stats.pyindex f4bdec9bbc3..43acd7c0e6a 100644--- a/tests/hermes_state/test_state_db_stats.py+++ b/tests/hermes_state/test_state_db_stats.py@@ -10,17 +10,13 @@ Covers:the doctor state.db section prints from."""-import hermes_state_dbfileimport json-import osimport sqlite3-from pathlib import Pathimport pytestfrom hermes_state import SessionDBfrom hermes_state_dbfile import collect_state_db_stats, count_db_holders-import hermes_cli.doctor_state@pytest.fixture()@@ -215,9 +211,7 @@ def test_render_warns_on_large_db():warns = [t for k, t, *rest in lines if k == "warn"] + [" ".join(rest) for k, t, *rest in lines if k == "warn"]- blob = " ".join(str(x) for x in warns)- assert "auto_prune" in blob- assert "config.yaml" in blob+ assert warnsdef test_render_large_db_with_pending_rebuild_suggests_optimize():@@ -244,32 +238,8 @@ def test_render_large_db_legacy_trigram_suggests_optimize():assert "optimize-storage" in blob-def test_render_large_db_v1_trigram_suggests_optimize():- from hermes_cli.doctor_state import STATE_DB_SIZE_WARN_BYTES, _render_state_db_stats-- lines = _render_state_db_stats(- _base_stats(- logical_size_bytes=STATE_DB_SIZE_WARN_BYTES + 1,- fts_storage_version=1,- ),- holders=None,- )- blob = " ".join(" ".join(str(p) for p in line) for line in lines)- assert "optimize-storage" in blob--def test_render_does_not_duplicate_legacy_wal_warning():- """A large WAL must NOT warn here: doctor's pre-existing WAL check- (50 MB threshold, with a --fix checkpoint) already covers it, and a- second warning at a higher threshold would duplicate the output."""- from hermes_cli.doctor_state import _render_state_db_stats- lines = _render_state_db_stats(- _base_stats(wal_size_bytes=256 * 1024 * 1024 + 1), holders=None- )- warns = [line for line in lines if line[0] == "warn"]- blob = " ".join(" ".join(str(p) for p in line) for line in warns).lower()- assert "wal" not in blobdef test_render_handles_all_none_stats():diff --git a/tests/hermes_state/test_state_db_write_durability.py b/tests/hermes_state/test_state_db_write_durability.pyindex 4ec9a1329ca..b1b1ca0afc9 100644--- a/tests/hermes_state/test_state_db_write_durability.py+++ b/tests/hermes_state/test_state_db_write_durability.py@@ -29,12 +29,11 @@ only the repair-connection durability half.)from __future__ import annotations-import astimport sqlite3-import sysfrom pathlib import Path-import hermes_state+import pytest+from hermes_state import repair_state_db_schemafrom hermes_state_repair import _connect_repair_durable@@ -54,6 +53,7 @@ def _make_db(tmp_path: Path) -> Path:# ── Repair-path write durability ────────────────────────────────────────[email protected]_onlydef test_connect_repair_durable_sets_macos_barriers(tmp_path: Path) -> None:"""The repair connection must carry both macOS durability barriers."""db = _make_db(tmp_path)@@ -66,20 +66,16 @@ def test_connect_repair_durable_sets_macos_barriers(tmp_path: Path) -> None:finally:conn.close()- if sys.platform == "darwin":- # SQLite: 0=OFF, 1=NORMAL, 2=FULL, 3=EXTRA. NORMAL is what tore the- # b-tree pages; FULL is what _enforce_macos_synchronous_full sets.- assert synchronous == 2, (- f"repair connection opened with synchronous={synchronous}; on "- "Darwin this lets REINDEX/VACUUM leave half-written b-tree pages"- )- assert checkpoint_fullfsync == 1, (- "repair connection has no F_FULLFSYNC barrier at checkpoint "- "boundaries; macOS fsync() does not flush the drive cache"- )- else:- # Elsewhere the helper is a plain connect — no behaviour change.- assert synchronous in (0, 1, 2, 3)+ # SQLite: 0=OFF, 1=NORMAL, 2=FULL, 3=EXTRA. NORMAL is what tore the+ # b-tree pages; FULL is what _enforce_macos_synchronous_full sets.+ assert synchronous == 2, (+ f"repair connection opened with synchronous={synchronous}; on "+ "Darwin this lets REINDEX/VACUUM leave half-written b-tree pages"+ )+ assert checkpoint_fullfsync == 1, (+ "repair connection has no F_FULLFSYNC barrier at checkpoint "+ "boundaries; macOS fsync() does not flush the drive cache"+ )def test_connect_repair_durable_is_autocommit(tmp_path: Path) -> None:@@ -94,49 +90,6 @@ def test_connect_repair_durable_is_autocommit(tmp_path: Path) -> None:conn.close()-def test_repair_path_has_no_bare_connects() -> None:- """No repair/probe site may bypass the durability helper.-- Source-level guard: the bare form is exactly what regressed, and a unit- test on the helper alone would not notice a sixth site being added.- """- # The repair/probe helpers live in hermes_state_repair; hermes_state only- # re-imports them.- import hermes_state_repair-- source = Path(hermes_state_repair.__file__).read_text(encoding="utf-8")- tree = ast.parse(source, filename=str(hermes_state_repair.__file__))-- def is_db_path_connect(node: ast.AST) -> bool:- if not isinstance(node, ast.Call):- return False- callee = node.func- if not (- isinstance(callee, ast.Attribute)- and isinstance(callee.value, ast.Name)- and callee.value.id == "sqlite3"- and callee.attr == "connect"- ):- return False- if not node.args:- return False- first = node.args[0]- return (- isinstance(first, ast.Call)- and isinstance(first.func, ast.Name)- and first.func.id == "str"- and len(first.args) == 1- and isinstance(first.args[0], ast.Name)- and first.args[0].id == "db_path"- )-- # The helper itself opens through ``connect_tracked`` (byte-probe registry, #63386), so no- # ``sqlite3.connect(str(db_path), ...)`` may remain anywhere in the module.- bare = [node for node in ast.walk(tree) if is_db_path_connect(node)]- assert bare == [], (- f"{len(bare)} repair/probe connection(s) bypass _connect_repair_durable() and write "- "state.db without the macOS fsync barriers or the live-connection registry"- )def test_repair_still_works_through_durable_connection(tmp_path: Path) -> None:diff --git a/tests/hermes_state/test_state_synchronous_pragma.py b/tests/hermes_state/test_state_synchronous_pragma.pyindex e6ec50ecf66..caa5350cf67 100644--- a/tests/hermes_state/test_state_synchronous_pragma.py+++ b/tests/hermes_state/test_state_synchronous_pragma.py@@ -11,11 +11,9 @@ under the stated assumption of `synchronous=FULL` on Ubuntu."""import sqlite3-import sysimport pytest-import hermes_stateimport hermes_state_walfrom hermes_state import apply_database_pragmasfrom hermes_state_wal import resolve_synchronous_level@@ -99,11 +97,11 @@ class TestResolveSynchronousLevel:class TestAppliedFromConfig:+ @pytest.mark.linux_onlydef test_configured_level_reaches_the_connection(self, tmp_path, monkeypatch):_config(monkeypatch, {"synchronous": "NORMAL"})conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "linux")apply_database_pragmas(conn, db_label="state.db")assert _level(conn) == 1finally:@@ -118,7 +116,6 @@ class TestAppliedFromConfig:_config(monkeypatch, {"synchronous": "FULL"})conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "linux")conn.execute("PRAGMA synchronous=0")assert _level(conn) == 0apply_database_pragmas(conn, db_label="state.db")@@ -131,7 +128,6 @@ class TestAppliedFromConfig:_config(monkeypatch, {"wal_autocheckpoint": 1000})conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "linux")conn.execute("PRAGMA synchronous=0")apply_database_pragmas(conn, db_label="state.db")assert _level(conn) == 0@@ -144,7 +140,6 @@ class TestAppliedFromConfig:_config(monkeypatch, {"synchronous": "PARANOID"})conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "linux")conn.execute("PRAGMA synchronous=2")with caplog.at_level("WARNING"):apply_database_pragmas(conn, db_label="state.db")@@ -161,7 +156,6 @@ class TestAppliedFromConfig:)conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "linux")apply_database_pragmas(conn, db_label="state.db")assert _level(conn) == 2assert conn.execute("PRAGMA wal_autocheckpoint").fetchone()[0] == 250@@ -178,69 +172,28 @@ class TestMacOSFloor:floor the config value would simply win by running last."""+ @pytest.mark.macos_onlydef test_lowering_below_full_is_refused_on_darwin(self, tmp_path, monkeypatch, caplog):_config(monkeypatch, {"synchronous": "NORMAL"})conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "darwin")hermes_state_wal._enforce_macos_synchronous_full(conn)assert _level(conn) == 2with caplog.at_level("WARNING"):apply_database_pragmas(conn, db_label="state.db")assert _level(conn) == 2, "config lowered the macOS btree protection"- assert "macOS" in caplog.textfinally:conn.close()+ @pytest.mark.macos_onlydef test_raising_above_full_is_allowed_on_darwin(self, tmp_path, monkeypatch):"""The floor is a floor, not a pin -- EXTRA is strictly safer."""_config(monkeypatch, {"synchronous": "EXTRA"})conn = _wal_conn(tmp_path)try:- monkeypatch.setattr(sys, "platform", "darwin")apply_database_pragmas(conn, db_label="state.db")assert _level(conn) == 3finally:conn.close()-- def test_the_floor_does_not_apply_off_darwin(self, tmp_path, monkeypatch):- """Linux operators may deliberately choose NORMAL for write volume."""- _config(monkeypatch, {"synchronous": "NORMAL"})- conn = _wal_conn(tmp_path)- try:- monkeypatch.setattr(sys, "platform", "linux")- conn.execute("PRAGMA synchronous=2")- apply_database_pragmas(conn, db_label="state.db")- assert _level(conn) == 1- finally:- conn.close()---def test_example_config_documents_the_key():- """An unpinnable durability level is the bug; docs are half the fix."""- from pathlib import Path-- text = Path(__file__).resolve().parents[2] / "cli-config.yaml.example"- body = text.read_text(encoding="utf-8")- assert "synchronous: FULL" in body---def test_example_config_calls_the_darwin_rule_a_floor_not_a_pin():- """The macOS wording has to match _apply_synchronous_pragma's actual rule.-- Saying macOS is "always held at FULL" reads as "your setting is ignored- here", which would talk an operator out of choosing EXTRA -- the one level- that IS honored on Darwin. Only sub-FULL values are refused. The wording- is the whole interface for a key nobody can otherwise observe, so pin the- distinction rather than just the key's presence.- """- from pathlib import Path-- body = (- Path(__file__).resolve().parents[2] / "cli-config.yaml.example"- ).read_text(encoding="utf-8")- assert "floor, not a pin" in body- assert "EXTRA is honored" in body- assert "always held" not in bodydiff --git a/tests/hermes_state/test_storage_failure_copy.py b/tests/hermes_state/test_storage_failure_copy.pyindex d7a0bceb7e2..00c0c0dd7ca 100644--- a/tests/hermes_state/test_storage_failure_copy.py+++ b/tests/hermes_state/test_storage_failure_copy.py@@ -25,7 +25,7 @@ def test_each_cause_has_a_stable_code_and_an_action(exc, code, command):failure = describe_storage_failure(exc)assert failure.code == codeassert command in failure.action- assert failure.gloss and failure.gloss[0].islower() # a clause that follows "Cause:"+ assert failure.gloss# The raw sqlite wording never leaks into the user-facing gloss.assert "sqlite" not in failure.gloss.lower() and "OperationalError" not in failure.glossdiff --git a/tests/hermes_state/test_tail_rewind_semantics.py b/tests/hermes_state/test_tail_rewind_semantics.pyindex 8c7a71adb1e..878163e806d 100644--- a/tests/hermes_state/test_tail_rewind_semantics.py+++ b/tests/hermes_state/test_tail_rewind_semantics.py@@ -29,7 +29,6 @@ And at the compressor boundary:from __future__ import annotations-import sqlite3from pathlib import Pathimport pytest@@ -233,7 +232,6 @@ class TestTailCountArchivesAsRewindSemantics:]def test_message_count_reflects_active_set(self, db: SessionDB) -> None:- import json as _json_seed(db)compacted = [*SUMMARY, {"role": "user", "content": "turn 4"},@@ -255,69 +253,3 @@ class TestTailCountArchivesAsRewindSemantics:assert int(mc) == 4-class TestCompressTagsCarriedTail:- def test_compress_marks_carried_forward_tail_dicts(self):- """compress() must tag its carried-forward tail dicts so the caller- can pass an accurate tail_count to the commit (#86366)."""- from agent.context_compressor import (- _COMPACTION_TAIL_MARKER,- ContextCompressor,- )- from unittest.mock import patch-- compressor = ContextCompressor.__new__(ContextCompressor)-- long_history = []- for i in range(12):- role = "user" if i % 2 == 0 else "assistant"- long_history.append({- "role": role,- "content": f"filler turn {i} " + "x" * 400,- })-- captured: dict = {}-- class _DB:- def archive_and_compact(self, session_id, messages, **kwargs):- captured["messages"] = messages- captured["tail_count"] = kwargs.get("tail_count", 0)- return len(messages)-- with (- patch.object(compressor, "_session_db", _DB(), create=True),- patch.object(compressor, "_session_id", "sessX", create=True),- patch.object(- compressor, "quiet_mode", True, create=True- ),- ):- # Drive compress() far enough to assemble compressed+tail by- # stubbing the LLM summarizer with a deterministic summary.- with (- patch.object(- compressor,- "_generate_summary",- return_value="deterministic summary",- create=True,- ),- patch.object(- compressor, "_prune_old_tool_results",- side_effect=lambda msgs, **k: (msgs, 0),- create=True,- ),- ):- try:- out = compressor.compress(list(long_history))- except Exception:- pytest.skip(- "compress() requires more runtime wiring than this "- "unit context provides; tag contract covered by the "- "persistence-layer tests above"- )-- tagged = [- m for m in (captured.get("messages") or [])- if isinstance(m, dict) and m.pop(_COMPACTION_TAIL_MARKER, None)- ]- # The marker is popped by the production caller before insert;- # here we just require it existed on the trailing dicts.- assert out is not Nonediff --git a/tests/hermes_state/test_wal_checkpoint_strategy.py b/tests/hermes_state/test_wal_checkpoint_strategy.pyindex a38a41ffd7b..2f5bf1c51e8 100644--- a/tests/hermes_state/test_wal_checkpoint_strategy.py+++ b/tests/hermes_state/test_wal_checkpoint_strategy.py@@ -6,9 +6,7 @@ transient per-cron-run connections closing many times an hour would racethe live gateway writer and corrupt B-tree pages (#45383)."""-import sqlite3-import logging-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockimport pytest@@ -72,22 +70,7 @@ class TestTryWalCheckpointPassive:"Periodic checkpoint should NOT use TRUNCATE")- def test_checkpoint_logs_warning_on_failure(self, db, caplog):- """Failed PASSIVE checkpoint logs a warning instead of silent pass."""- mock_conn = MagicMock()- mock_conn.execute.side_effect = sqlite3.OperationalError("disk I/O error")- db._conn = mock_conn-- with caplog.at_level(logging.WARNING):- db._try_wal_checkpoint()- assert any("WAL checkpoint (PASSIVE) failed" in r.message for r in caplog.records), (- f"Expected warning log about PASSIVE checkpoint failure, got: {caplog.text}"- )-- def test_checkpoint_returns_result_on_success(self, db):- """Successful PASSIVE checkpoint does not raise."""- db._try_wal_checkpoint()class TestCloseUsesPassive:@@ -119,18 +102,6 @@ class TestCloseUsesPassive:f"Expected 1 PASSIVE checkpoint at close, got {len(passive_calls)}")- def test_close_logs_debug_on_failure(self, db, caplog):- """Failed PASSIVE checkpoint at close logs debug (close is best-effort)."""- mock_conn = MagicMock()- mock_conn.execute.side_effect = sqlite3.OperationalError("database is locked")- db._conn = mock_conn-- with caplog.at_level(logging.DEBUG):- db.close()-- assert any("WAL checkpoint (PASSIVE) at close failed" in r.message for r in caplog.records), (- f"Expected debug log about PASSIVE failure at close, got: {caplog.text}"- )class TestVacuumUsesPassive:diff --git a/tests/hermes_state/test_writer_conn_thread_safety.py b/tests/hermes_state/test_writer_conn_thread_safety.pyindex 4ccedcd6d5b..a0b84f51d70 100644--- a/tests/hermes_state/test_writer_conn_thread_safety.py+++ b/tests/hermes_state/test_writer_conn_thread_safety.py@@ -22,7 +22,6 @@ Two independent layers are asserted here:logged without invalidating the already-durable write."""-import sqlite3import threadingimport time@@ -119,97 +118,6 @@ class TestConcurrentReadersDoNotRaceTheWriter:)assert errors == []- def test_unlocked_writer_conn_use_is_enumerated(self):- """Sibling-sweep tripwire: no method may touch ``self._conn``- outside ``with self._lock`` (or the __init__/close lifecycle, which- runs before/after any concurrent access is possible).-- This is the AST sweep that found the four incident sites, frozen as- a test so a future convenience read can't quietly reintroduce the- class.- """- import ast- import inspect-- import hermes_state as hs-- src = inspect.getsource(hs)- tree = ast.parse(src)-- ALLOWED_FUNCS = {- # Lifecycle: run before the instance is shared / after readers- # are drained. Not reachable concurrently with writers.- "__init__", "_open_writer", "_connect_and_init",- "_connect_and_init_with_lock_patience", "close",- # Lost-generation settlement: called only from close()'s- # `with self._lock` body (locked transitively, not lexically).- "_settle_lost_generation_locked",- }-- def is_lock_with(node):- if isinstance(node, ast.With):- for item in node.items:- ctx = item.context_expr- if (isinstance(ctx, ast.Attribute)- and ctx.attr == "_lock"- and isinstance(ctx.value, ast.Name)- and ctx.value.id == "self"):- return True- return False-- violations = []-- class Sweep(ast.NodeVisitor):- def __init__(self):- self.lock_depth = 0- self.func_stack = []-- @staticmethod- def _is_conn_attr(node):- return (isinstance(node, ast.Attribute)- and isinstance(node.value, ast.Name)- and node.value.id == "self"- and node.attr == "_conn")-- def _flag(self, node):- fn = self.func_stack[-1] if self.func_stack else "<module>"- if fn not in ALLOWED_FUNCS:- violations.append((node.lineno, fn))-- def generic_visit(self, node):- locked = is_lock_with(node)- is_func = isinstance(- node, (ast.FunctionDef, ast.AsyncFunctionDef)- )- if locked:- self.lock_depth += 1- if is_func:- self.func_stack.append(node.name)- if isinstance(node, ast.Call) and self.lock_depth == 0:- # A method call ON the connection (self._conn.execute(...))- func = node.func- if (isinstance(func, ast.Attribute)- and self._is_conn_attr(func.value)):- self._flag(func.value)- # ...or the connection handed to a helper that will- # execute on it (e.g. _collect_delegate_child_ids(self._conn, ...)).- for arg in list(node.args) + [k.value for k in node.keywords]:- if self._is_conn_attr(arg):- self._flag(arg)- super().generic_visit(node)- if locked:- self.lock_depth -= 1- if is_func:- self.func_stack.pop()-- Sweep().visit(tree)- assert violations == [], (- "self._conn used outside 'with self._lock' in: %r — route reads "- "through _read_ctx() (or take the lock); an unlocked statement "- "on the shared writer connection races concurrent writers and "- "raises SystemError, destroying the turn as "- "session_persistence_failed" % (violations,)- )class TestSystemErrorTransactionBoundary:diff --git a/tests/honcho_plugin/test_a2a_sessions.py b/tests/honcho_plugin/test_a2a_sessions.pyindex f883df5cb06..0df82937aa8 100644--- a/tests/honcho_plugin/test_a2a_sessions.py+++ b/tests/honcho_plugin/test_a2a_sessions.py@@ -171,15 +171,6 @@ class TestManagerUserPeerOverride:assert "7654321" not in joined-class TestConfigFlag:- def _config(self, tmp_path, monkeypatch, raw: dict) -> HonchoClientConfig:- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- path = tmp_path / "honcho.json"- path.write_text(json.dumps({"apiKey": "k", **raw}))- return HonchoClientConfig.from_global_config(config_path=path)-- def test_defaults_on(self, tmp_path, monkeypatch):- assert self._config(tmp_path, monkeypatch, {}).a2a_sessions is Trueclass TestRelayedDmFromALoggedInClient:diff --git a/tests/honcho_plugin/test_async_memory.py b/tests/honcho_plugin/test_async_memory.pyindex 95ffbc86b37..3cbb62b6d56 100644--- a/tests/honcho_plugin/test_async_memory.py+++ b/tests/honcho_plugin/test_async_memory.py@@ -13,7 +13,6 @@ import jsonimport loggingimport threadingimport time-from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest@@ -89,11 +88,6 @@ def make_manager(monkeypatch):# ---------------------------------------------------------------------------class TestWriteFrequencyParsing:- def test_string_async(self, tmp_path):- cfg_file = tmp_path / "config.json"- cfg_file.write_text(json.dumps({"apiKey": "k", "writeFrequency": "async"}))- cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)- assert cfg.write_frequency == "async"def test_integer_frequency(self, tmp_path):@@ -113,11 +107,6 @@ class TestWriteFrequencyParsing:cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)assert cfg.write_frequency == "session"- def test_defaults_to_async(self, tmp_path):- cfg_file = tmp_path / "config.json"- cfg_file.write_text(json.dumps({"apiKey": "k"}))- cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)- assert cfg.write_frequency == "async"# ---------------------------------------------------------------------------@@ -199,10 +188,6 @@ class TestResolveSessionNameTitle:)assert result == "agent-main-telegram-dm-42"- def test_global_strategy_returns_workspace(self):- cfg = HonchoClientConfig(session_strategy="global", workspace_id="my-workspace")- result = cfg.resolve_session_name("/some/dir")- assert result == "my-workspace"# ---------------------------------------------------------------------------@@ -251,15 +236,6 @@ class TestSaveRouting:mgr.save(sess) # turn 3assert mock_flush.call_count == 1- def test_int_frequency_skips_other_turns(self, make_manager):- mgr = make_manager(write_frequency=5)- sess = self._make_session_with_message(mgr)- with patch.object(mgr, "_flush_session") as mock_flush:- for _ in range(4):- mgr.save(sess)- assert mock_flush.call_count == 0- mgr.save(sess) # turn 5- assert mock_flush.call_count == 1# ---------------------------------------------------------------------------@@ -351,13 +327,6 @@ class TestAsyncWriterThread:assert len(flushed) == 1assert flushed[0] is sess- def test_shutdown_sentinel_stops_loop(self, make_manager):- mgr = make_manager(write_frequency="async")- mgr._ensure_async_writer_locked()- thread = mgr._async_thread- mgr.shutdown()- thread.join(timeout=10)- assert not thread.is_alive()def test_shutdown_without_started_thread_is_noop(self, make_manager):mgr = make_manager(write_frequency="async")@@ -414,15 +383,6 @@ class TestStopAsyncWriterDrain:assert flushed == ["after"]assert mgr._async_queue.empty()- def test_shutdown_gives_the_writer_join_what_the_flush_left_of_the_timeout(self, make_manager, monkeypatch):- mgr = make_manager("async")- seen = {}- monkeypatch.setattr(mgr, "_stop_async_writer_before",- lambda deadline: seen.setdefault("remaining", deadline - time.monotonic()) and [])-- mgr.shutdown(timeout=2.5)-- assert 2.0 < seen["remaining"] <= 2.5def _pending_session(self, mgr, uploads):session = _make_session(key="pending")@@ -715,16 +675,6 @@ class TestMemoryFileMigrationOwnerGate:assert honcho_session.upload_file.call_count == 1-# ----------------------------------------------------------------------------# HonchoClientConfig dataclass defaults for new fields-# -----------------------------------------------------------------------------class TestNewConfigFieldDefaults:- def test_write_frequency_default(self):- cfg = HonchoClientConfig()- assert cfg.write_frequency == "async"--class TestPrefetchCacheAccessors:def test_set_and_pop_context_result(self, make_manager):mgr = make_manager(write_frequency="turn")diff --git a/tests/honcho_plugin/test_auth_recovery.py b/tests/honcho_plugin/test_auth_recovery.pyindex 5b8077446b1..9ca21e39a4e 100644--- a/tests/honcho_plugin/test_auth_recovery.py+++ b/tests/honcho_plugin/test_auth_recovery.py@@ -3,7 +3,6 @@ forced refresh + single retry on sync and dialectic, backoff exemption, andthe one-time user-facing notice."""import json-import loggingimport timefrom pathlib import Pathfrom types import SimpleNamespace@@ -140,18 +139,6 @@ class TestExchangeRetry:token, _ = oauth.ensure_fresh_token(path, "hermes", now=2000)assert token == "hch-at-fresh"- def test_error_body_is_logged(self, tmp_path, monkeypatch, caplog):- path = tmp_path / "honcho.json"- _write(path, {"hosts": {"hermes": _host_block()}})- monkeypatch.setattr(oauth, "_REFRESH_RETRY_DELAY_SECONDS", 0)- monkeypatch.setattr(- oauth, "_http_post_form_status",- lambda *a, **k: (400, {"error": "invalid_grant", "error_description": "grant revoked"}),- )- with caplog.at_level(logging.WARNING, logger="plugins.memory.honcho.oauth"):- oauth.ensure_fresh_token(path, "hermes", now=1000)- assert "invalid_grant" in caplog.text- assert "grant revoked" in caplog.textdef test_honcho_token_prefixes_are_registered_with_the_shared_redactor(self):"""Importing the plugin registers hch-at-/hch-rt- with agent.redact, so every surface that@@ -269,8 +256,6 @@ class TestAuthErrorDetection:exc.status_code = 401assert _is_auth_error(exc)- def test_matches_401_text(self):- assert _is_auth_error(Exception("HTTP 401 Unauthorized"))def test_ignores_other_errors(self):assert not _is_auth_error(Exception("connection reset by peer"))@@ -534,14 +519,6 @@ def _relogin(path: Path) -> None:class TestDeadGrantSkipsCalls:- def test_dead_grant_issues_no_dialectic_call(self, tmp_path, monkeypatch):- _kill_grant(tmp_path, monkeypatch)- peer = _FlakyPeer(failures=0)- mgr = _make_manager(peer)- with pytest.raises(HonchoAuthError):- mgr.dialectic_query("k", "q")- assert peer.calls == 0- assert mgr.pop_auth_notice() is not Nonedef test_relogin_resumes_dialectic_without_waiting(self, tmp_path, monkeypatch):path = _kill_grant(tmp_path, monkeypatch)@@ -556,13 +533,6 @@ class TestDeadGrantSkipsCalls:assert peer.calls == 1assert mgr._auth_failure is None- def test_dead_grant_issues_no_sync_call(self, tmp_path, monkeypatch):- _kill_grant(tmp_path, monkeypatch)- flaky = _FlakyHonchoSession(failures=0)- mgr, session = _make_sync_manager(flaky)- assert mgr._flush_session(session) is False- assert flaky.calls == 0- assert mgr._auth_failure is not Nonedef test_relogin_resumes_sync_without_waiting(self, tmp_path, monkeypatch):path = _kill_grant(tmp_path, monkeypatch)@@ -957,16 +927,6 @@ def _initialized_provider():class TestInitAuthFailureNotice:- def test_peer_setup_401_in_hybrid_mode_produces_notice(self, tmp_path, monkeypatch):- client = MagicMock()- client.peer.side_effect = Exception("HTTP 401 Unauthorized")- _wire_init(tmp_path, monkeypatch, client)- provider = _initialized_provider()-- assert provider._manager is None- notice = provider.prefetch("what did we decide about the schema?")- assert "hermes honcho setup" in notice- assert "paused" in noticedef test_notice_is_emitted_exactly_once(self, tmp_path, monkeypatch):client = MagicMock()@@ -999,15 +959,6 @@ class TestInitAuthFailureNotice:notice = provider.prefetch("what happened before the grant died?")assert "hermes honcho setup" in notice- def test_tools_lazy_init_reports_auth_error(self, tmp_path, monkeypatch):- client = MagicMock()- client.peer.side_effect = Exception("Invalid or expired access token")- _wire_init(tmp_path, monkeypatch, client, recall_mode="tools")- provider = _initialized_provider()-- out = provider.handle_tool_call("honcho_profile", {})- assert "authentication failed" in out- assert "could not be initialized" not in outdef test_relogin_resumes_init_and_clears_failure(self, tmp_path, monkeypatch):client = _healthy_client()@@ -1209,24 +1160,3 @@ class TestClientGenerationGuard:assert mgr._sessions_cache["s"] is fresh_sessionassert resolutions == ["stale", "fresh"]- def test_dead_grant_check_fast_path_skips_path_resolution(self, monkeypatch):- """With no dead grants, _reauth_required must not resolve the config- path at all (it runs before every SDK call)."""- from plugins.memory.honcho import client as client_mod-- oauth._dead_grants.clear()-- # Recording spy, not a raising stub: _reauth_required swallows all- # exceptions, so a raise would be silently converted to False and the- # test would pass even without the fast path.- calls = []-- def _spy():- calls.append(1)- return Path("/nonexistent/honcho.json")-- monkeypatch.setattr(client_mod, "resolve_config_path", _spy)- cfg = HonchoClientConfig(host="hermes", api_key="hch-at-x", enabled=True)- mgr = HonchoSessionManager(config=cfg)- assert mgr._reauth_required() is False- assert calls == [], "resolve_config_path must not run on the fast path"diff --git a/tests/honcho_plugin/test_cli.py b/tests/honcho_plugin/test_cli.pyindex 8715667ac0c..7423bc93a52 100644--- a/tests/honcho_plugin/test_cli.py+++ b/tests/honcho_plugin/test_cli.py@@ -58,6 +58,15 @@ class TestCmdSetupLocalJwt:monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)monkeypatch.setattr(honcho_cli, "_host_key", lambda: "hermes")monkeypatch.setattr(honcho_cli, "_ensure_sdk_installed", lambda: True)+ # No gateway import, config.yaml write or real SDK connection attempt.+ monkeypatch.setattr(honcho_cli, "_gateway_platforms", lambda: [])+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: {"memory": {}}, raising=False)+ monkeypatch.setattr("hermes_cli.config.save_config", lambda c: None, raising=False)++ def _offline(*a, **k):+ raise ConnectionError("offline in tests")++ monkeypatch.setattr(honcho_cli, "_connect", _offline)written = {}@@ -159,65 +168,6 @@ class TestCmdStatus:assert "FAILED (Invalid API key)" in outassert "Connection... OK" not in out- def test_auth_line_detects_oauth_grant(self, monkeypatch, capsys, tmp_path):- import plugins.memory.honcho.cli as honcho_cli-- cfg_path = tmp_path / "honcho.json"- cfg_path.write_text("{}")-- class FakeConfig:- enabled = True- api_key = "hch-at-deadbeef"- workspace_id = "claude-code"- host = "hermes"- base_url = None- ai_peer = "hermes"- peer_name = "eri"- recall_mode = "hybrid"- user_observe_me = True- user_observe_others = False- ai_observe_me = False- ai_observe_others = True- write_frequency = "async"- session_strategy = "per-session"- context_tokens = None- dialectic_reasoning_level = "low"- reasoning_level_cap = "high"- reasoning_heuristic = True- raw = {- "hosts": {- "hermes": {- "apiKey": "hch-at-deadbeef",- "oauth": {- "refreshToken": "hch-rt-x",- "clientId": "hermes-agent",- "tokenEndpoint": "https://api.honcho.dev/oauth/token",- "expiresAt": 9999999999,- },- }- }- }-- def resolve_session_name(self):- return "hermes"-- monkeypatch.setattr(honcho_cli, "_read_config", lambda: {})- monkeypatch.setattr(honcho_cli, "_config_path", lambda: cfg_path)- monkeypatch.setattr(honcho_cli, "_local_config_path", lambda: cfg_path)- monkeypatch.setattr(honcho_cli, "_active_profile_name", lambda: "default")- monkeypatch.setattr(- "plugins.memory.honcho.client.HonchoClientConfig.from_global_config",- lambda host=None: FakeConfig(),- )- monkeypatch.setattr("plugins.memory.honcho.client.get_honcho_client", lambda cfg: object())- monkeypatch.setattr(honcho_cli, "_show_peer_cards", lambda hcfg, client: None)- monkeypatch.setitem(__import__("sys").modules, "honcho", SimpleNamespace())-- honcho_cli.cmd_status(SimpleNamespace(all=False))-- out = capsys.readouterr().out- assert "Auth: OAuth (hermes-agent" in out- assert "API key:" not in outclass TestCloneHonchoForProfile:@@ -516,9 +466,6 @@ class TestSetupWizardDeploymentShape:assert host["userPeerAliases"] == {"7654321": "eri"}- def test_mapping_step_points_at_peers_map(self, monkeypatch, tmp_path, capsys):- self._run_setup(monkeypatch, tmp_path, answers=["cloud", "", "eri", "hermetika", "hermes", "s"])- assert "hermes honcho peers map" in capsys.readouterr().outdef test_host_pin_user_peer_true_is_detected_as_single(self, monkeypatch, tmp_path):"""Host-level ``pinUserPeer: true`` must classify as ``single``.@@ -754,7 +701,6 @@ class TestCmdSetupDeviceFlow:cfg, calls, _ = self._run_setup(monkeypatch, tmp_path, answers=["cloud", "device"])assert len(calls) == 1assert calls[0]["apply_config"] is False- assert calls[0]["source"] == "hermes-cli"host = cfg["hosts"]["hermes"]assert host["apiKey"] == "hch-at-x"assert host["oauth"]["refreshToken"] == "hch-rt-x"@@ -798,14 +744,12 @@ class TestWriteRefusesUnparseableStore:lambda cli: cli.honcho_command(SimpleNamespace(honcho_command="mode", mode="tools", target_profile=None)),lambda cli: cli.cmd_setup(SimpleNamespace()),], ids=["command", "setup"])- def test_command_prints_one_sentence_asks_nothing_and_writes_nothing(self, monkeypatch, tmp_path, capsys, run):+ def test_command_asks_nothing_and_writes_nothing(self, monkeypatch, tmp_path, run):cfg_path = tmp_path / "honcho.json"cfg_path.write_text("{not json", encoding="utf-8")honcho_cli = _point_cli_at(monkeypatch, cfg_path, _host_key=lambda: "hermes_coder",_prompt=lambda *a, **k: pytest.fail("asked a question"))run(honcho_cli)- out = capsys.readouterr().out- assert "could not be read as JSON" in out and "Nothing was written" in outassert cfg_path.read_text(encoding="utf-8") == "{not json"@@ -872,22 +816,19 @@ class TestEnabledRequiresACredential:assert "apiKey" not in block and "oauth" not in blockassert block["aiPeer"] == "dreamer" and block["workspace"] == "hermes"- @pytest.mark.parametrize("cfg, env_key, profile, expect, enabled", [- ({"hosts": {"hermes_dreamer": {"workspace": "hermes"}}}, "hch-v3-from-env", "dreamer", ["setup"], False),- (_OAUTH_DEFAULT, None, "dreamer",- ["stays disabled", "hermes honcho setup --target-profile dreamer", "hosts.hermes_dreamer"], False),+ @pytest.mark.parametrize("cfg, env_key, profile, enabled", [+ ({"hosts": {"hermes_dreamer": {"workspace": "hermes"}}}, "hch-v3-from-env", "dreamer", False),+ (_OAUTH_DEFAULT, None, "dreamer", False),({"hosts": {"hermes_dreamer": {"enabled": True, "aiPeer": "dreamer", "workspace": "hermes"}}}, None, "dreamer",- ["stays disabled"], False),- ({"hosts": {}}, None, "default", ["Run 'hermes honcho setup' to sign in"], False),- ({"apiKey": "hch-v3-root", **_KEYLESS_DEFAULT}, None, "dreamer", ["Honcho enabled"], True),- ], ids=["env key only", "empty block", "legacy enabled keyless block", "default profile hint", "root key"])- def test_enable_writes_enabled_only_for_an_on_disk_credential(self, monkeypatch, tmp_path, capsys,- cfg, env_key, profile, expect, enabled):+ False),+ ({"hosts": {}}, None, "default", False),+ ({"apiKey": "hch-v3-root", **_KEYLESS_DEFAULT}, None, "dreamer", True),+ ], ids=["env key only", "empty block", "legacy enabled keyless block", "default profile", "root key"])+ def test_enable_writes_enabled_only_for_an_on_disk_credential(self, monkeypatch, tmp_path,+ cfg, env_key, profile, enabled):host = "hermes" if profile == "default" else "hermes_dreamer"honcho_cli, written = self._env(monkeypatch, tmp_path, cfg, env_key=env_key, host=host, profile=profile)honcho_cli.cmd_enable(SimpleNamespace())- out = capsys.readouterr().out- assert all(s in out for s in expect) and "already enabled" not in outassert written["cfg"]["hosts"][host]["enabled"] is True if enabled else written == {}diff --git a/tests/honcho_plugin/test_client.py b/tests/honcho_plugin/test_client.pyindex 6a4361dd34c..20ac85bde05 100644--- a/tests/honcho_plugin/test_client.py+++ b/tests/honcho_plugin/test_client.py@@ -19,24 +19,9 @@ from plugins.memory.honcho.client import (reset_honcho_client,resolve_active_host,resolve_config_path,- resolve_global_config_path,)-class TestHonchoClientConfigDefaults:- def test_default_values(self):- config = HonchoClientConfig()- assert config.host == "hermes"- assert config.workspace_id == "hermes"- assert config.api_key is None- assert config.environment == "production"- assert config.timeout is None- assert config.enabled is False- assert config.save_messages is True- assert config.session_strategy == "per-directory"- assert config.recall_mode == "hybrid"- assert config.session_peer_prefix is False- assert config.sessions == {}class TestFromEnv:@@ -47,14 +32,6 @@ class TestFromEnv:assert config.enabled is True- def test_defaults_without_env(self):- with patch.dict(os.environ, {}, clear=True):- # Remove HONCHO_API_KEY if it exists- os.environ.pop("HONCHO_API_KEY", None)- os.environ.pop("HONCHO_ENVIRONMENT", None)- config = HonchoClientConfig.from_env()- assert config.api_key is None- assert config.environment == "production"def test_enabled_without_api_key_when_base_url_set(self):@@ -313,23 +290,6 @@ class TestResolveActiveHost:assert resolve_active_host() == "hermes.coder"- def test_profiles_import_failure_falls_back(self):- import sys- with patch.dict(os.environ, {}, clear=False), patch(- "plugins.memory.honcho.client.resolve_config_path",- return_value=Path("/nonexistent/test-honcho-config.json"),- ):- os.environ.pop("HERMES_HONCHO_HOST", None)- # Temporarily remove hermes_cli.profiles to simulate import failure- saved = sys.modules.get("hermes_cli.profiles")- sys.modules["hermes_cli.profiles"] = None # type: ignore- try:- assert resolve_active_host() == "hermes"- finally:- if saved is not None:- sys.modules["hermes_cli.profiles"] = saved- else:- sys.modules.pop("hermes_cli.profiles", None)class TestProfileScopedConfig:@@ -354,12 +314,6 @@ class TestObservationModeMigration:cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)assert cfg.observation_mode == "unified"- def test_new_config_defaults_to_directional(self, tmp_path):- """Config with no host block and no credentials → 'directional' (new default)."""- cfg_file = tmp_path / "config.json"- cfg_file.write_text(json.dumps({}))- cfg = HonchoClientConfig.from_global_config(config_path=cfg_file)- assert cfg.observation_mode == "directional"def test_granular_observation_overrides_preset(self, tmp_path):@@ -456,70 +410,8 @@ class TestGetHonchoClient:assert mock_honcho.call_args.kwargs["api_key"] == "explicit-top-level-key"- @pytest.mark.skipif(- not importlib.util.find_spec("honcho"),- reason="honcho SDK not installed"- )- def test_passes_timeout_from_config(self):- fake_honcho = MagicMock(name="Honcho")- cfg = HonchoClientConfig(- api_key="test-key",- timeout=91.0,- workspace_id="hermes",- environment="production",- )-- with patch("honcho.Honcho", return_value=fake_honcho) as mock_honcho:- client = get_honcho_client(cfg)-- assert client is fake_honcho- mock_honcho.assert_called_once()- assert mock_honcho.call_args.kwargs["timeout"] == 91.0-- @pytest.mark.skipif(- not importlib.util.find_spec("honcho"),- reason="honcho SDK not installed"- )- def test_timeout_change_triggers_client_rebuild(self):- """Changing timeout config must rebuild the cached client."""- from hermes_constants import get_hermes_home-- cfg_yaml = get_hermes_home() / "config.yaml"- cfg_yaml.write_text("honcho:\n timeout: 30\n")-- fake_honcho_1 = MagicMock(name="Honcho_v1")- fake_honcho_2 = MagicMock(name="Honcho_v2")- cfg = HonchoClientConfig(- api_key="test-key",- workspace_id="hermes",- environment="production",- )-- with patch("honcho.Honcho", return_value=fake_honcho_1) as mock_h1:- client1 = get_honcho_client(cfg)-- assert client1 is fake_honcho_1- assert mock_h1.call_args.kwargs["timeout"] == 30.0-- # Same config — should return cached client (no rebuild)- with patch("honcho.Honcho", return_value=fake_honcho_2) as mock_h2:- client2 = get_honcho_client(cfg)-- assert client2 is fake_honcho_1 # still cached- mock_h2.assert_not_called()-- # Changed timeout — must rebuild- cfg_yaml.write_text("honcho:\n timeout: 300\n")- st = cfg_yaml.stat()- os.utime(cfg_yaml, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000))-- with patch("honcho.Honcho", return_value=fake_honcho_2) as mock_h3:- client3 = get_honcho_client(cfg)- assert client3 is fake_honcho_2 # rebuilt- mock_h3.assert_called_once()- assert mock_h3.call_args.kwargs["timeout"] == 300.0@pytest.mark.skipif(not importlib.util.find_spec("honcho"),@@ -727,18 +619,12 @@ class TestGetHonchoClientBaseUrlDoublePrefixFix:@pytest.mark.parametrize("raw_url, expected",[- # LAN IP self-host- ("http://10.0.0.5:8000/v3", "http://10.0.0.5:8000"),+ # LAN IP self-host with trailing slash("http://192.168.1.20:38000/v3/", "http://192.168.1.20:38000"),- # Tailscale / custom-domain self-host- ("https://honcho.my.ts.net/v3", "https://honcho.my.ts.net"),- ("https://honcho.lab.internal/v3", "https://honcho.lab.internal"),- ("https://honcho.fly.dev/v3", "https://honcho.fly.dev"),- # higher version segments are also stripped+ # custom domain, higher version segment("https://honcho.lab.internal/v12", "https://honcho.lab.internal"),# self-host without a version segment is left unchanged("https://honcho.my.ts.net", "https://honcho.my.ts.net"),- ("http://10.0.0.5:8000", "http://10.0.0.5:8000"),],)def test_self_hosted_base_url_version_stripped(self, raw_url, expected):diff --git a/tests/honcho_plugin/test_empty_profile_hint.py b/tests/honcho_plugin/test_empty_profile_hint.pyindex 6d703fa9540..7430ccdb19a 100644--- a/tests/honcho_plugin/test_empty_profile_hint.py+++ b/tests/honcho_plugin/test_empty_profile_hint.py@@ -35,16 +35,9 @@ class TestEmptyProfileHint:provider = _make_provider()raw = provider.handle_tool_call("honcho_profile", {})payload = json.loads(raw)- assert payload["result"] == "No profile facts available yet."- assert "hint" in payload- assert "not an error" in payload["hint"].lower()+ assert "error" not in payload+ assert payload["hint"]- def test_hint_mentions_warmup_when_turn_count_below_cadence(self):- provider = _make_provider(turn_count=1, dialectic_cadence=3)- raw = provider.handle_tool_call("honcho_profile", {})- payload = json.loads(raw)- assert "turn" in payload["hint"].lower()- assert "cadence" in payload["hint"].lower()def test_populated_card_returns_card_without_hint(self):diff --git a/tests/honcho_plugin/test_network_isolation.py b/tests/honcho_plugin/test_network_isolation.pyindex f59261b9d0d..580c118ded9 100644--- a/tests/honcho_plugin/test_network_isolation.py+++ b/tests/honcho_plugin/test_network_isolation.py@@ -5,7 +5,6 @@ messages (session cli-test, hello/hi) into the production workspace of a livelocal Honcho. These tests pin the isolation contract."""-import jsonimport socketimport threadingimport time@@ -59,28 +58,6 @@ class TestConstructorRace:class TestAmbientProductionConfig:- def test_ambient_live_config_produces_zero_requests(self, tmp_path, monkeypatch):- """Regression 2: ambient HERMES_HOME with a live URL must not leak- requests - hygiene (factory injection) keeps the suite green."""- home = tmp_path / "hermes-home"- home.mkdir()- (home / "honcho.json").write_text(json.dumps({- "baseUrl": "http://localhost:8000",- "workspace": "iris_curated_v1",- "hosts": {"hermes": {"apiKey": "live-looking-key", "saveMessages": True}},- }))- monkeypatch.setenv("HERMES_HOME", str(home))- fake = MagicMock()- monkeypatch.setattr(session_module, "get_honcho_client", lambda *a, **k: fake)- cfg = HonchoClientConfig(write_frequency="async", api_key="live-looking-key", enabled=True)- mgr = HonchoSessionManager(honcho=fake, config=cfg)- try:- sess = _session(sid="cli-test")- sess.add_message("user", "hello")- mgr.save(sess)- mgr.flush_all()- finally:- mgr.shutdown()# teardown-assert конфтеста дополнительно проверит network_attempts == []@pytest.mark.expect_network_attemptsdiff --git a/tests/honcho_plugin/test_oauth_flow.py b/tests/honcho_plugin/test_oauth_flow.pyindex f590932e022..837f5818158 100644--- a/tests/honcho_plugin/test_oauth_flow.py+++ b/tests/honcho_plugin/test_oauth_flow.py@@ -221,21 +221,8 @@ def test_state_mismatch_is_rejected(fake_as, tmp_path):)-def test_source_tags_the_authorize_link(fake_as):- endpoints = oauth_flow.resolve_endpoints()- url, _ = oauth_flow.begin_authorization(endpoints, source="hermes-cli")- assert "source=hermes-cli" in url- untagged, _ = oauth_flow.begin_authorization(endpoints)- assert "source=" not in untagged-def test_client_id_defaults_to_hermes_agent(monkeypatch):- # One client for every surface; the env var overrides for unusual deployments.- monkeypatch.delenv("HONCHO_OAUTH_CLIENT_ID", raising=False)- common = {"environment": "production", "base_url": "https://api.honcho.dev"}- assert oauth_flow.resolve_endpoints(**common).client_id == "hermes-agent"- monkeypatch.setenv("HONCHO_OAUTH_CLIENT_ID", "custom-id")- assert oauth_flow.resolve_endpoints(**common).client_id == "custom-id"def test_grant_persists_default_client_id(tmp_path, fake_as, monkeypatch):@@ -257,13 +244,6 @@ def test_grant_persists_default_client_id(tmp_path, fake_as, monkeypatch):assert saved["hosts"]["hermes"]["oauth"]["clientId"] == "hermes-agent"-def test_config_path_rides_the_authorize_link(fake_as):- endpoints = oauth_flow.resolve_endpoints()- url, _ = oauth_flow.begin_authorization(endpoints, config_path="~/.hermes/honcho.json")- q = parse_qs(urlparse(url).query)- assert q["config_path"][0] == "~/.hermes/honcho.json"- bare, _ = oauth_flow.begin_authorization(endpoints)- assert "config_path=" not in baredef test_display_config_path_never_leaks_absolute_path():diff --git a/tests/honcho_plugin/test_peers_map.py b/tests/honcho_plugin/test_peers_map.pyindex e2c7f6ca6a0..b2be9487fcf 100644--- a/tests/honcho_plugin/test_peers_map.py+++ b/tests/honcho_plugin/test_peers_map.py@@ -167,36 +167,7 @@ class TestCmdPeersMap:def test_nothing_changed_writes_nothing(self, monkeypatch, tmp_path, cfg, answers, kwargs):assert _run_map(monkeypatch, tmp_path, answers=answers, cfg=cfg, **kwargs) == {}- @pytest.mark.parametrize("cfg, answers, kwargs, expected", [- (_cfg(peerName="eri"), ["1", "fresh-name", ""], dict(db_rows=[_row("111", name="bob")], ws_peers=["eri", "111"]),- ["'fresh-name' is a new peer", "peer '111' keeps its existing history"]),- (_cfg(peerName="eri"), [""], dict(db_rows=[_row("111"), _row("222", "discord", "b", 50.0)], ws_peers=["eri", "111"]),- ["111 ✓", "222 ○ new"]),- (_cfg(), ["7654321", "eri", ""], {}, ["peers unavailable"]),- (_cfg(peerName="eri"), ["p2", ""], dict(ws_peers=["eri", "meow"]), ["(card of meow)"]),- (_cfg(peerName="eri"), [""], dict(ws_peers=[]), ["No peers here yet", "Wrong workspace?"]),- (_cfg(peerName="eri"), [""], dict(ws_peers=["stranger1", "stranger2"]),- ["None of these match your configured identity"]),- ({"apiKey": "***", "userPeerAliases": {},- "hosts": {"hermes": {"workspace": "hermes"}, "hermes.dreamer": {"workspace": "dreamland"}}},- ["222", "tek", "", "all"], {}, ["also apply in workspace 'dreamland'"]),- ({"apiKey": "***", "hosts": {"hermes": {"peerName": "eri", "userPeerAliases": {"111": "eri"}},- "hermes.dreamer": {"peerName": "eri", "userPeerAliases": {"111": "bob"}}}},- [""], dict(db_rows=[_row("111", name="x")]), ["≠ dreamer→bob"]),- ], ids=["new-peer-and-history-consequences", "exists-markers", "offline-typed-targets", "inspect-peer-card",- "empty-workspace-hint", "unrecognized-workspace-hint", "cross-workspace-root-write-warns",- "sibling-divergence-marked"])- def test_view_and_consequence_messages(self, monkeypatch, tmp_path, capsys, cfg, answers, kwargs, expected):- _run_map(monkeypatch, tmp_path, answers=answers, cfg=cfg, **kwargs)- out = capsys.readouterr().out- for text in expected:- assert text in out-- def test_peers_dispatches_map_action(self, monkeypatch):- called = {}- monkeypatch.setattr(honcho_cli, "cmd_peers_map", lambda a: called.update({"map": True}))- honcho_cli.cmd_peers(SimpleNamespace(peers_action="map"))- assert called == {"map": True}+class TestWorkspaceSwitch:diff --git a/tests/honcho_plugin/test_pin_peer_name.py b/tests/honcho_plugin/test_pin_peer_name.pyindex ce792139b8e..635d3ab3f2f 100644--- a/tests/honcho_plugin/test_pin_peer_name.py+++ b/tests/honcho_plugin/test_pin_peer_name.py@@ -31,10 +31,6 @@ from plugins.memory.honcho.session_peers import HonchoPeerUnresolvedErrorclass TestPinPeerNameConfigParsing:- def test_default_is_false(self):- """Default preserves existing behaviour — multi-user bots unaffected."""- config = HonchoClientConfig()- assert config.pin_peer_name is Falsedef test_root_level_true(self, tmp_path, monkeypatch):config_file = tmp_path / "honcho.json"@@ -79,10 +75,6 @@ class TestPinPeerNameConfigParsing:class TestRuntimePeerMappingConfigParsing:- def test_defaults_are_empty(self):- config = HonchoClientConfig()- assert config.user_peer_aliases == {}- assert config.runtime_peer_prefix == ""def test_malformed_alias_config_is_ignored(self, tmp_path):@@ -443,24 +435,6 @@ class TestCrossPlatformMemoryUnification:)-class TestPinUserPeerAlias:- """``pinUserPeer`` and ``pinPeerName`` both resolve to the same internal- ``pin_peer_name`` field. Precedence when both appear: host pinUserPeer →- host pinPeerName → root pinUserPeer → root pinPeerName → default.- """--- def test_pinPeerName_still_works_unchanged(self, tmp_path):- from plugins.memory.honcho.client import HonchoClientConfig- import json- config_file = tmp_path / "honcho.json"- config_file.write_text(json.dumps({- "apiKey": "***",- "peerName": "eri",- "hosts": {"hermes": {"pinPeerName": True}},- }))- config = HonchoClientConfig.from_global_config(config_path=config_file)- assert config.pin_peer_name is Trueclass TestPinTransition:diff --git a/tests/honcho_plugin/test_query_rewrite.py b/tests/honcho_plugin/test_query_rewrite.pyindex 233f9adcbd2..3c11bdf27b4 100644--- a/tests/honcho_plugin/test_query_rewrite.py+++ b/tests/honcho_plugin/test_query_rewrite.py@@ -1,7 +1,7 @@"""Behavior contract for Honcho's latest-message query rewrite."""from types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockimport pytest@@ -12,8 +12,6 @@ from plugins.memory.query_rewrite import (_normalize_rewrite,rewrite_memory_query,)-from hermes_cli.config import DEFAULT_CONFIG-from hermes_cli.main_provider_setup import _AUX_TASKSdef _response(text: str):@@ -145,8 +143,7 @@ def test_session_prewarm_can_skip_query_rewrite():)rewriter.assert_not_called()- sent_query = provider._manager.dialectic_query.call_args.args[1]- assert "current conversation" in sent_query+ provider._manager.dialectic_query.assert_called()def test_register_injects_query_rewriter():@@ -161,10 +158,3 @@ def test_register_injects_query_rewriter():assert provider._query_rewriter is rewrite_memory_query-def test_config_defaults_keep_rewrite_opt_in_and_bound_first_turn_waits():- from plugins.memory.honcho.client import HonchoClientConfig-- cfg = HonchoClientConfig(api_key="k", enabled=True)- assert cfg.query_rewrite is False- assert cfg.first_turn_base_wait == 3.0- assert cfg.first_turn_dialectic_wait == 2.0diff --git a/tests/honcho_plugin/test_save_messages.py b/tests/honcho_plugin/test_save_messages.pyindex d86d8b1d85f..7b88b5bc8d2 100644--- a/tests/honcho_plugin/test_save_messages.py+++ b/tests/honcho_plugin/test_save_messages.py@@ -22,11 +22,6 @@ def _provider(save_messages: bool) -> HonchoMemoryProvider:class TestSyncTurn:- def test_disabled_writes_nothing(self):- p = _provider(save_messages=False)- p.sync_turn('user says', 'assistant says')- p._manager.get_or_create.assert_not_called()- p._manager.save.assert_not_called()def test_enabled_routes_through_save(self):p = _provider(save_messages=True)@@ -37,29 +32,8 @@ class TestSyncTurn:# save() (not _flush_session) so writeFrequency batching is honoredp._manager.save.assert_called_once()- def test_enabled_writes(self):- p = _provider(save_messages=True)- p.sync_turn('user says', 'assistant says')- if p._sync_thread is not None:- p._sync_thread.join(timeout=5)- p._manager.get_or_create.assert_called_once()--class TestOnMemoryWrite:- def test_disabled_skips_conclusion_mirror(self):- p = _provider(save_messages=False)- p.on_memory_write('add', 'user', 'user likes coffee')- p._manager.create_conclusion.assert_not_called()- def test_enabled_mirrors(self):- import time-- p = _provider(save_messages=True)- p.on_memory_write('add', 'user', 'user likes coffee')- deadline = time.time() + 5- while time.time() < deadline and not p._manager.create_conclusion.called:- time.sleep(0.05)- p._manager.create_conclusion.assert_called_once()class TestOnSessionEnd:diff --git a/tests/honcho_plugin/test_session.py b/tests/honcho_plugin/test_session.pyindex 5534e24d025..ace23fcadd9 100644--- a/tests/honcho_plugin/test_session.py+++ b/tests/honcho_plugin/test_session.py@@ -6,7 +6,6 @@ import sysimport threadingimport time-from datetime import datetimefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -19,36 +18,6 @@ from plugins.memory.honcho.session import (from plugins.memory.honcho import HonchoMemoryProvider-# ----------------------------------------------------------------------------# HonchoSession dataclass-# ------------------------------------------------------------------------------class TestHonchoSession:- def _make_session(self):- return HonchoSession(- key="telegram:12345",- user_peer_id="user-telegram-12345",- assistant_peer_id="hermes-assistant",- honcho_session_id="telegram-12345",- )-- def test_initial_state(self):- session = self._make_session()- assert session.key == "telegram:12345"- assert session.messages == []- assert isinstance(session.created_at, datetime)- assert isinstance(session.updated_at, datetime)-- def test_add_message(self):- session = self._make_session()- session.add_message("user", "Hello!")- assert len(session.messages) == 1- assert session.messages[0]["role"] == "user"- assert session.messages[0]["content"] == "Hello!"- assert "timestamp" in session.messages[0]--# ---------------------------------------------------------------------------# HonchoSessionManager._sanitize_id# ---------------------------------------------------------------------------@@ -148,24 +117,6 @@ class TestConcludeToolDispatch:assert "oneOf" not in paramsassert "allOf" not in params- def test_honcho_conclude_defaults_to_user_peer(self):- provider = HonchoMemoryProvider()- provider._session_initialized = True- provider._session_key = "telegram:123"- provider._manager = MagicMock()- provider._manager.create_conclusion.return_value = True-- result = provider.handle_tool_call(- "honcho_conclude",- {"conclusion": "User prefers dark mode"},- )-- assert "Conclusion saved for user" in result- provider._manager.create_conclusion.assert_called_once_with(- "telegram:123",- "User prefers dark mode",- peer="user",- )def test_sync_turn_strips_leaked_memory_context_before_honcho_ingest(self):@@ -511,12 +462,6 @@ class TestDialecticCadenceDefaults:_settle_prewarm(provider)return provider- def test_unset_falls_back_to_1(self):- """Unset dialecticCadence falls back to 1 (every turn) for backwards- compatibility with existing configs that predate the setting. The- setup wizard writes 2 explicitly on new configs."""- provider = self._make_provider()- assert provider._dialectic_cadence == 1def test_first_turn_only_injection_disables_base_refresh(self):@@ -535,17 +480,6 @@ class TestDialecticCadenceDefaults:class TestBaseContextSummary:"""Base context injection should include session summary when available."""- def test_format_includes_summary(self):- """Session summary should appear first in the formatted context."""- provider = HonchoMemoryProvider()- ctx = {- "summary": "Testing Honcho tools and dialectic depth.",- "representation": "Eri is a developer.",- "card": "Name: Eri Barrett",- }- formatted = provider._format_first_turn_context(ctx)- assert "## Session Summary" in formatted- assert formatted.index("Session Summary") < formatted.index("User Representation")def test_timed_out_first_turn_context_surfaces_next_turn(self):@@ -643,10 +577,6 @@ class TestDialecticDepth:_settle_prewarm(provider)return provider- def test_default_depth_is_1(self):- """Default dialecticDepth should be 1 — single .chat() call."""- provider = self._make_provider()- assert provider._dialectic_depth == 1def test_depth_clamped_to_3(self):@@ -665,12 +595,6 @@ class TestDialecticDepth:assert provider._resolve_pass_level(1) == "high"- def test_cold_start_prompt(self):- """Cold start (no base context) uses general user query."""- provider = self._make_provider()- prompt = provider._build_dialectic_prompt(0, [], is_cold=True)- assert "preferences" in prompt.lower()- assert "session" not in prompt.lower()def test_signal_sufficient_short_response(self):@@ -680,18 +604,6 @@ class TestDialecticDepth:assert not HonchoMemoryProvider._signal_sufficient(None)- def test_run_dialectic_depth_single_pass(self):- """Depth 1 makes exactly one .chat() call."""- from unittest.mock import MagicMock- provider = self._make_provider(cfg_extra={"dialectic_depth": 1})- provider._manager = MagicMock()- provider._manager.dialectic_query.return_value = "user prefers zero-fluff"- provider._session_key = "test"- provider._base_context_cache = None # cold start-- result = provider._run_dialectic_depth("hello")- assert result == "user prefers zero-fluff"- assert provider._manager.dialectic_query.call_count == 1# ---------------------------------------------------------------------------@@ -726,22 +638,7 @@ class TestTrivialPromptHeuristic:for t in ("ok", "OK", " ok ", "y", "yes", "sure", "thanks", "lgtm", "/help", "", " "):assert HonchoMemoryProvider._is_trivial_prompt(t), f"expected trivial: {t!r}"- def test_classifier_catches_greetings(self):- """Greeting words must register as trivial so context injection is skipped."""- for t in ("hi", "HI", "hey", "hello", "yo", "sup", " hi ", "hey!", "hello."):- assert HonchoMemoryProvider._is_trivial_prompt(t), f"expected trivial: {t!r}"-- def test_prefetch_skips_on_trivial_prompt(self):- provider = self._make_provider()- provider._session_key = "test"- provider._base_context_cache = "cached base"- provider._last_dialectic_turn = 0- provider._turn_count = 5- assert provider.prefetch("ok") == ""- assert provider.prefetch("/help") == ""- # Dialectic should not have fired- assert provider._manager.dialectic_query.call_count == 0def test_trivial_prompt_injects_ready_pending_dialectic(self):@@ -812,18 +709,6 @@ class TestDialecticCadenceAdvancesOnSuccess:return provider- def test_non_empty_dialectic_result_advances_cadence(self):- provider = self._make_provider()- provider._session_key = "test"- provider._manager.dialectic_query.return_value = "real synthesis output"- provider._turn_count = 5- provider._last_dialectic_turn = 0-- provider.queue_prefetch("what changed in the repo today")- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=2.0)-- assert provider._last_dialectic_turn == 5def test_in_flight_thread_is_not_stacked(self):import threading as _threading@@ -851,58 +736,6 @@ class TestDialecticCadenceAdvancesOnSuccess:fresh.join(timeout=2.0)-class TestSessionStartDialecticPrewarm:- """Session-start prewarm fires a depth-aware dialectic whose result is- consumed by turn 1 — no duplicate .chat() and no dead-cache orphaning."""-- @staticmethod- def _make_provider(cfg_extra=None, dialectic_result="prewarm synthesis"):- from unittest.mock import patch, MagicMock- from plugins.memory.honcho.client import HonchoClientConfig-- defaults = dict(api_key="test-key", enabled=True, recall_mode="hybrid")- if cfg_extra:- defaults.update(cfg_extra)- cfg = HonchoClientConfig(**defaults)- provider = HonchoMemoryProvider()- mock_manager = MagicMock()- mock_manager.get_or_create.return_value = MagicMock(messages=[])- mock_manager.get_prefetch_context.return_value = None- mock_manager.pop_context_result.return_value = None- mock_manager.dialectic_query.return_value = dialectic_result-- with patch("plugins.memory.honcho.client.HonchoClientConfig.from_global_config", return_value=cfg), \- patch("plugins.memory.honcho.client.get_honcho_client", return_value=MagicMock()), \- patch("plugins.memory.honcho.session.HonchoSessionManager", return_value=mock_manager), \- patch("hermes_constants.get_hermes_home", return_value=MagicMock()):- provider.initialize(session_id="test-prewarm")- return provider-- def test_prewarm_populates_prefetch_result(self):- p = self._make_provider()- # Wait for prewarm thread to land- if p._prefetch_thread:- p._prefetch_thread.join(timeout=3.0)- with p._prefetch_lock:- assert p._prefetch_result == "prewarm synthesis"- assert p._last_dialectic_turn == 0--- def test_turn1_consumes_prewarm_without_duplicate_dialectic(self):- """With prewarm result already in _prefetch_result, turn 1 prefetch- should NOT fire another dialectic."""- p = self._make_provider()- if p._prefetch_thread:- p._prefetch_thread.join(timeout=3.0)- p._manager.dialectic_query.reset_mock()- p._session_key = "test-prewarm"- p._base_context_cache = ""- p._turn_count = 1-- result = p.prefetch("hello world")- assert "prewarm synthesis" in result- # The sync first-turn path must NOT have fired another .chat()- assert p._manager.dialectic_query.call_count == 0class TestDialecticLiveness:diff --git a/tests/honcho_plugin/test_session_ai_peer_prefix.py b/tests/honcho_plugin/test_session_ai_peer_prefix.pyindex 2ee19f8e888..049f506c9a8 100644--- a/tests/honcho_plugin/test_session_ai_peer_prefix.py+++ b/tests/honcho_plugin/test_session_ai_peer_prefix.py@@ -23,10 +23,6 @@ from plugins.memory.honcho.client import HonchoClientConfigclass TestSessionAiPeerPrefixConfigParsing:- def test_default_is_false(self):- """Default preserves existing behaviour."""- config = HonchoClientConfig()- assert config.session_ai_peer_prefix is Falsedef test_root_level_true(self, tmp_path, monkeypatch):config_file = tmp_path / "honcho.json"diff --git a/tests/integration/__init__.py b/tests/integration/__init__.pydeleted file mode 100644index e69de29bb2d..00000000000diff --git a/tests/integration/test_batch_runner.py b/tests/integration/test_batch_runner.pydeleted file mode 100644index 79300606239..00000000000--- a/tests/integration/test_batch_runner.py+++ /dev/null@@ -1,132 +0,0 @@-#!/usr/bin/env python3-"""-Test script for batch runner--This script tests the batch runner with a small sample dataset-to verify functionality before running large batches.-"""--import pytest-pytestmark = pytest.mark.integration--import json-import shutil-from pathlib import Path---def create_test_dataset():- """Create a small test dataset."""- test_file = Path("tests/test_dataset.jsonl")- test_file.parent.mkdir(exist_ok=True)-- prompts = [- {"prompt": "What is 2 + 2?"},- {"prompt": "What is the capital of France?"},- {"prompt": "Explain what Python is in one sentence."},- ]-- with open(test_file, 'w') as f:- for prompt in prompts:- f.write(json.dumps(prompt, ensure_ascii=False) + "\n")-- print(f"✅ Created test dataset: {test_file}")- return test_file---def cleanup_test_run(run_name):- """Clean up test run output."""- output_dir = Path("data") / run_name- if output_dir.exists():- shutil.rmtree(output_dir)- print(f"🗑️ Cleaned up test output: {output_dir}")---def verify_output(run_name):- """Verify that output files were created correctly."""- output_dir = Path("data") / run_name-- # Check directory exists- if not output_dir.exists():- print(f"❌ Output directory not found: {output_dir}")- return False-- # Check for checkpoint- checkpoint_file = output_dir / "checkpoint.json"- if not checkpoint_file.exists():- print(f"❌ Checkpoint file not found: {checkpoint_file}")- return False-- # Check for statistics- stats_file = output_dir / "statistics.json"- if not stats_file.exists():- print(f"❌ Statistics file not found: {stats_file}")- return False-- # Check for batch files- batch_files = list(output_dir.glob("batch_*.jsonl"))- if not batch_files:- print(f"❌ No batch files found in: {output_dir}")- return False-- print("✅ Output verification passed:")- print(f" - Checkpoint: {checkpoint_file}")- print(f" - Statistics: {stats_file}")- print(f" - Batch files: {len(batch_files)}")-- # Load and display statistics- with open(stats_file) as f:- stats = json.load(f)-- print("\n📊 Statistics Summary:")- print(f" - Total prompts: {stats['total_prompts']}")- print(f" - Total batches: {stats['total_batches']}")- print(f" - Duration: {stats['duration_seconds']}s")-- if stats.get('tool_statistics'):- print(" - Tool calls:")- for tool, tool_stats in stats['tool_statistics'].items():- print(f" • {tool}: {tool_stats['count']} calls, {tool_stats['success_rate']:.1f}% success")-- return True---def main():- """Run the test."""- print("🧪 Batch Runner Test")- print("=" * 60)-- run_name = "test_run"-- # Clean up any previous test run- cleanup_test_run(run_name)-- # Create test dataset- test_file = create_test_dataset()-- print("\n📝 To run the test manually:")- print(" python batch_runner.py \\")- print(f" --dataset_file={test_file} \\")- print(" --batch_size=2 \\")- print(f" --run_name={run_name} \\")- print(" --distribution=minimal \\")- print(" --num_workers=2")-- print("\n💡 Or test with different distributions:")- print(" python batch_runner.py --list_distributions")-- print("\n🔍 After running, you can verify output with:")- print(" python tests/test_batch_runner.py --verify")-- # Note: We don't actually run the batch runner here to avoid API calls during testing- # Users should run it manually with their API keys configured---if __name__ == "__main__":- import sys-- if "--verify" in sys.argv:- run_name = "test_run"- verify_output(run_name)- else:- main()-diff --git a/tests/integration/test_checkpoint_resumption.py b/tests/integration/test_checkpoint_resumption.pydeleted file mode 100644index 5a4820a88a4..00000000000--- a/tests/integration/test_checkpoint_resumption.py+++ /dev/null@@ -1,439 +0,0 @@-#!/usr/bin/env python3-"""-Test script to verify checkpoint behavior in batch_runner.py--This script simulates batch processing with intentional failures to test:-1. Whether checkpoints are saved incrementally during processing-2. Whether resume functionality works correctly after interruption-3. Whether data integrity is maintained across checkpoint cycles--Usage:- # Test current implementation- python tests/test_checkpoint_resumption.py --test_current-- # Test after fix is applied- python tests/test_checkpoint_resumption.py --test_fixed-- # Run full comparison- python tests/test_checkpoint_resumption.py --compare-"""--import pytest-pytestmark = pytest.mark.integration--import json-import shutil-import sys-import time-from pathlib import Path-from typing import List, Dict, Any-import traceback--# Add project root to path to import batch_runner-sys.path.insert(0, str(Path(__file__).parent.parent.parent))---def create_test_dataset(num_prompts: int = 20) -> Path:- """Create a small test dataset for checkpoint testing."""- test_data_dir = Path("tests/test_data")- test_data_dir.mkdir(parents=True, exist_ok=True)-- dataset_file = test_data_dir / "checkpoint_test_dataset.jsonl"-- with open(dataset_file, 'w', encoding='utf-8') as f:- for i in range(num_prompts):- entry = {- "prompt": f"Test prompt {i}: What is 2+2? Just answer briefly.",- "test_id": i- }- f.write(json.dumps(entry, ensure_ascii=False) + "\n")-- print(f"✅ Created test dataset: {dataset_file} ({num_prompts} prompts)")- return dataset_file---def monitor_checkpoint_during_run(checkpoint_file: Path, duration: int = 30) -> List[Dict[str, Any]]:- """- Monitor checkpoint file during a batch run to see when it gets updated.-- Args:- checkpoint_file: Path to checkpoint file to monitor- duration: How long to monitor (seconds)-- Returns:- List of checkpoint snapshots with timestamps- """- snapshots = []- start_time = time.time()- last_mtime = None-- print(f"\n🔍 Monitoring checkpoint file: {checkpoint_file}")- print(f" Duration: {duration}s")- print("-" * 70)-- while time.time() - start_time < duration:- if checkpoint_file.exists():- current_mtime = checkpoint_file.stat().st_mtime-- # Check if file was modified- if last_mtime is None or current_mtime != last_mtime:- elapsed = time.time() - start_time-- try:- with open(checkpoint_file, 'r') as f:- checkpoint_data = json.load(f)-- snapshot = {- "elapsed_seconds": round(elapsed, 2),- "completed_count": len(checkpoint_data.get("completed_prompts", [])),- "completed_prompts": checkpoint_data.get("completed_prompts", [])[:5], # First 5 for display- "timestamp": checkpoint_data.get("last_updated")- }-- snapshots.append(snapshot)-- print(f"[{elapsed:6.2f}s] Checkpoint updated: {snapshot['completed_count']} prompts completed")-- except Exception as e:- print(f"[{elapsed:6.2f}s] Error reading checkpoint: {e}")-- last_mtime = current_mtime- else:- if len(snapshots) == 0:- print(f"[{time.time() - start_time:6.2f}s] Checkpoint file not yet created...")-- time.sleep(0.5) # Check every 0.5 seconds-- return snapshots---def _cleanup_test_artifacts(*paths):- """Remove test-generated files and directories."""- for p in paths:- p = Path(p)- if p.is_dir():- shutil.rmtree(p, ignore_errors=True)- elif p.is_file():- p.unlink(missing_ok=True)---def test_current_implementation():- """Test the current checkpoint implementation."""- print("\n" + "=" * 70)- print("TEST 1: Current Implementation - Checkpoint Timing")- print("=" * 70)- print("\n📝 Testing whether checkpoints are saved incrementally during run...")-- # Setup- dataset_file = create_test_dataset(num_prompts=12)- run_name = "checkpoint_test_current"- output_dir = Path("data") / run_name-- # Clean up any existing test data- if output_dir.exists():- shutil.rmtree(output_dir)-- # Import here to avoid issues if module changes- from batch_runner import BatchRunner-- checkpoint_file = output_dir / "checkpoint.json"-- # Start monitoring in a separate process would be ideal, but for simplicity- # we'll just check before and after- print("\n▶️ Starting batch run...")- print(f" Dataset: {dataset_file}")- print(" Batch size: 3 (4 batches total)")- print(" Workers: 2")- print(" Expected behavior: If incremental, checkpoint should update during run")-- start_time = time.time()-- try:- runner = BatchRunner(- dataset_file=str(dataset_file),- batch_size=3,- run_name=run_name,- distribution="default",- max_iterations=3, # Keep it short- model="claude-opus-4-20250514",- num_workers=2,- verbose=False- )-- # Run with monitoring- import threading- snapshots = []-- def monitor():- nonlocal snapshots- snapshots = monitor_checkpoint_during_run(checkpoint_file, duration=60)-- monitor_thread = threading.Thread(target=monitor, daemon=True)- monitor_thread.start()-- runner.run(resume=False)-- monitor_thread.join(timeout=2)-- except Exception as e:- print(f"❌ Error during run: {e}")- traceback.print_exc()- return False- finally:- _cleanup_test_artifacts(dataset_file, output_dir)-- elapsed = time.time() - start_time-- # Analyze results- print("\n" + "=" * 70)- print("📊 TEST RESULTS")- print("=" * 70)- print(f"Total run time: {elapsed:.2f}s")- print(f"Checkpoint updates observed: {len(snapshots)}")-- if len(snapshots) == 0:- print("\n❌ ISSUE: No checkpoint updates observed during run")- print(" This suggests checkpoints are only saved at the end")- return False- elif len(snapshots) == 1:- print("\n⚠️ WARNING: Only 1 checkpoint update (likely at the end)")- print(" This confirms the bug - no incremental checkpointing")- return False- else:- print(f"\n✅ GOOD: Multiple checkpoint updates ({len(snapshots)}) observed")- print(" Checkpointing appears to be incremental")-- # Show timeline- print("\n📈 Checkpoint Timeline:")- for i, snapshot in enumerate(snapshots, 1):- print(f" {i}. [{snapshot['elapsed_seconds']:6.2f}s] "- f"{snapshot['completed_count']} prompts completed")-- return True---def test_interruption_and_resume():- """Test that resume actually works after interruption."""- print("\n" + "=" * 70)- print("TEST 2: Interruption and Resume")- print("=" * 70)- print("\n📝 Testing whether resume works after manual interruption...")-- # Setup- dataset_file = create_test_dataset(num_prompts=15)- run_name = "checkpoint_test_resume"- output_dir = Path("data") / run_name-- # Clean up any existing test data- if output_dir.exists():- shutil.rmtree(output_dir)-- from batch_runner import BatchRunner-- checkpoint_file = output_dir / "checkpoint.json"-- print("\n▶️ Starting first run (will process 5 prompts, then simulate interruption)...")-- temp_dataset = Path("tests/test_data/checkpoint_test_resume_partial.jsonl")- try:- # Create a modified dataset with only first 5 prompts for initial run- with open(dataset_file, 'r') as f:- lines = f.readlines()[:5]- with open(temp_dataset, 'w') as f:- f.writelines(lines)-- runner = BatchRunner(- dataset_file=str(temp_dataset),- batch_size=2,- run_name=run_name,- distribution="default",- max_iterations=3,- model="claude-opus-4-20250514",- num_workers=1,- verbose=False- )-- runner.run(resume=False)-- # Check checkpoint after first run- if not checkpoint_file.exists():- print("❌ ERROR: Checkpoint file not created after first run")- return False-- with open(checkpoint_file, 'r') as f:- checkpoint_data = json.load(f)-- initial_completed = len(checkpoint_data.get("completed_prompts", []))- print(f"✅ First run completed: {initial_completed} prompts saved to checkpoint")-- # Now try to resume with full dataset- print("\n▶️ Starting resume run with full dataset (15 prompts)...")-- runner2 = BatchRunner(- dataset_file=str(dataset_file),- batch_size=2,- run_name=run_name,- distribution="default",- max_iterations=3,- model="claude-opus-4-20250514",- num_workers=1,- verbose=False- )-- runner2.run(resume=True)-- # Check final checkpoint- with open(checkpoint_file, 'r') as f:- final_checkpoint = json.load(f)-- final_completed = len(final_checkpoint.get("completed_prompts", []))-- print("\n" + "=" * 70)- print("📊 TEST RESULTS")- print("=" * 70)- print(f"Initial completed: {initial_completed}")- print(f"Final completed: {final_completed}")- print("Expected: 15")-- if final_completed == 15:- print("\n✅ PASS: Resume successfully completed all prompts")- return True- else:- print(f"\n❌ FAIL: Expected 15 completed, got {final_completed}")- return False-- except Exception as e:- print(f"❌ Error during test: {e}")- traceback.print_exc()- return False- finally:- _cleanup_test_artifacts(dataset_file, temp_dataset, output_dir)---def test_simulated_crash():- """Test behavior when process crashes mid-execution."""- print("\n" + "=" * 70)- print("TEST 3: Simulated Crash During Execution")- print("=" * 70)- print("\n📝 This test would require running in a subprocess and killing it...")- print(" Skipping for safety - manual testing recommended")- return None---def print_test_plan():- """Print the detailed test and fix plan."""- print("\n" + "=" * 70)- print("CHECKPOINT FIX - DETAILED PLAN")- print("=" * 70)-- print("""-📋 PROBLEM SUMMARY--------------------Current implementation uses pool.map() which blocks until ALL batches complete.-Checkpoint is only saved after all batches finish (line 558-559).--If process crashes during batch processing:-- All progress is lost-- Resume does nothing (no incremental checkpoint was saved)--📋 PROPOSED SOLUTION----------------------Replace pool.map() with pool.imap_unordered() to get results as they complete.-Save checkpoint after EACH batch completes using a multiprocessing Lock.--Key changes:-1. Use Manager().Lock() for thread-safe checkpoint writes-2. Replace pool.map() with pool.imap_unordered()-3. Update checkpoint after each batch result-4. Maintain backward compatibility with existing checkpoints--📋 IMPLEMENTATION STEPS-------------------------1. Add Manager and Lock initialization before Pool creation-2. Pass shared checkpoint data and lock to workers (via Manager)-3. Replace pool.map() with pool.imap_unordered()-4. In result loop: save checkpoint after each batch-5. Add error handling for checkpoint write failures--📋 RISKS & MITIGATIONS------------------------Risk: Checkpoint file corruption if two processes write simultaneously-→ Mitigation: Use multiprocessing.Lock() for exclusive access--Risk: Performance impact from frequent checkpoint writes-→ Mitigation: Checkpoint writes are fast (small JSON), negligible impact--Risk: Breaking existing runs that are already checkpointed-→ Mitigation: Maintain checkpoint format, only change timing--Risk: Bugs in multiprocessing lock/manager code-→ Mitigation: Thorough testing with this test script--📋 TESTING STRATEGY---------------------1. Run test_current_implementation() - Confirm bug exists-2. Apply fix to batch_runner.py-3. Run test_current_implementation() again - Should see incremental updates-4. Run test_interruption_and_resume() - Verify resume works-5. Manual test: Start run, kill process mid-batch, resume--📋 ROLLBACK PLAN------------------If issues arise:-1. Git revert the changes-2. Original code is working (just missing incremental checkpoint)-3. No data corruption risk - checkpoints are write-only-""")---def main(- test_current: bool = False,- test_resume: bool = False,- test_crash: bool = False,- compare: bool = False,- show_plan: bool = False-):- """- Run checkpoint behavior tests.-- Args:- test_current: Test current implementation checkpoint timing- test_resume: Test interruption and resume functionality- test_crash: Test simulated crash scenario (manual)- compare: Run all tests and compare- show_plan: Show detailed fix plan- """- if show_plan or (not any([test_current, test_resume, test_crash, compare])):- print_test_plan()- return-- results = {}-- if test_current or compare:- results['current'] = test_current_implementation()-- if test_resume or compare:- results['resume'] = test_interruption_and_resume()-- if test_crash or compare:- results['crash'] = test_simulated_crash()-- # Summary- if results:- print("\n" + "=" * 70)- print("OVERALL TEST SUMMARY")- print("=" * 70)- for test_name, result in results.items():- if result is None:- status = "⏭️ SKIPPED"- elif result:- status = "✅ PASS"- else:- status = "❌ FAIL"- print(f"{status} - {test_name}")---if __name__ == "__main__":- import fire- fire.Fire(main)-diff --git a/tests/integration/test_daytona_terminal.py b/tests/integration/test_daytona_terminal.pydeleted file mode 100644index b8b72fb26cb..00000000000--- a/tests/integration/test_daytona_terminal.py+++ /dev/null@@ -1,123 +0,0 @@-"""Integration tests for the Daytona terminal backend.--Requires DAYTONA_API_KEY to be set. Run with:- TERMINAL_ENV=daytona pytest tests/integration/test_daytona_terminal.py -v-"""--import json-import os-import sys-from pathlib import Path--import pytest--pytestmark = pytest.mark.integration--# Skip entire module if no API key-if not os.getenv("DAYTONA_API_KEY"):- pytest.skip("DAYTONA_API_KEY not set", allow_module_level=True)--# Import terminal_tool via importlib to avoid tools/__init__.py side effects-import importlib.util--parent_dir = Path(__file__).parent.parent.parent-sys.path.insert(0, str(parent_dir))--spec = importlib.util.spec_from_file_location(- "terminal_tool", parent_dir / "tools" / "terminal_tool.py"-)-terminal_module = importlib.util.module_from_spec(spec)-spec.loader.exec_module(terminal_module)--terminal_tool = terminal_module.terminal_tool-cleanup_vm = terminal_module.cleanup_vm--[email protected](autouse=True)-def _force_daytona(monkeypatch):- monkeypatch.setenv("TERMINAL_ENV", "daytona")- monkeypatch.setenv("TERMINAL_CONTAINER_DISK", "10240")- monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "false")---def task_id(request):- """Provide a unique task_id and clean up the sandbox after the test."""- tid = f"daytona_test_{request.node.name}"- yield tid- cleanup_vm(tid)---def _run(command, task_id, **kwargs):- result = terminal_tool(command, task_id=task_id, **kwargs)- return json.loads(result)---class TestDaytonaBasic:- def test_echo(self, task_id):- r = _run("echo 'Hello from Daytona!'", task_id)- assert r["exit_code"] == 0- assert "Hello from Daytona!" in r["output"]-- def test_python_version(self, task_id):- r = _run("python3 --version", task_id)- assert r["exit_code"] == 0- assert "Python" in r["output"]-- def test_nonzero_exit(self, task_id):- r = _run("exit 42", task_id)- assert r["exit_code"] == 42-- def test_os_info(self, task_id):- r = _run("uname -a", task_id)- assert r["exit_code"] == 0- assert "Linux" in r["output"]---class TestDaytonaFilesystem:- def test_write_and_read_file(self, task_id):- _run("echo 'test content' > /tmp/daytona_test.txt", task_id)- r = _run("cat /tmp/daytona_test.txt", task_id)- assert r["exit_code"] == 0- assert "test content" in r["output"]-- def test_persistence_within_session(self, task_id):- _run("pip install cowsay 2>/dev/null", task_id, timeout=120)- r = _run('python3 -c "import cowsay; print(cowsay.__file__)"', task_id)- assert r["exit_code"] == 0- assert "cowsay" in r["output"]---class TestDaytonaPersistence:- def test_filesystem_survives_stop_and_resume(self):- """Write a file, stop the sandbox, resume it, assert the file persists."""- task = "daytona_test_persist"- try:- # Enable persistence for this test- os.environ["TERMINAL_CONTAINER_PERSISTENT"] = "true"-- # Write a marker file and stop the sandbox- _run("echo 'survive' > /tmp/persist_test.txt", task)- cleanup_vm(task) # stops (not deletes) because persistent=true-- # Resume with the same task_id — file should still exist- r = _run("cat /tmp/persist_test.txt", task)- assert r["exit_code"] == 0- assert "survive" in r["output"]- finally:- # Force-delete so the sandbox doesn't leak- os.environ["TERMINAL_CONTAINER_PERSISTENT"] = "false"- cleanup_vm(task)---class TestDaytonaIsolation:- def test_different_tasks_isolated(self):- task_a = "daytona_test_iso_a"- task_b = "daytona_test_iso_b"- try:- _run("echo 'secret' > /tmp/isolated.txt", task_a)- r = _run("cat /tmp/isolated.txt 2>&1 || echo NOT_FOUND", task_b)- assert "secret" not in r["output"] or "NOT_FOUND" in r["output"]- finally:- cleanup_vm(task_a)- cleanup_vm(task_b)diff --git a/tests/integration/test_ha_integration.py b/tests/integration/test_ha_integration.pydeleted file mode 100644index 9d0180c4c39..00000000000--- a/tests/integration/test_ha_integration.py+++ /dev/null@@ -1,313 +0,0 @@-"""Integration tests for Home Assistant (tool + gateway).--Spins up a real in-process fake HA server (HTTP + WebSocket) and exercises-the full adapter and tool handler paths over real TCP connections.-No mocks -- only real async I/O against a fake server.--Run with: uv run pytest tests/integration/test_ha_integration.py -v-"""--import asyncio--import pytest--pytestmark = pytest.mark.integration--from unittest.mock import AsyncMock--from gateway.config import Platform, PlatformConfig-from plugins.platforms.homeassistant.adapter import HomeAssistantAdapter-from tests.fakes.fake_ha_server import FakeHAServer, ENTITY_STATES-from tools.homeassistant_tool import (- _async_call_service,- _async_get_state,- _async_list_entities,-)---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _adapter_for(server: FakeHAServer, **extra) -> HomeAssistantAdapter:- """Create an adapter pointed at the fake server."""- config = PlatformConfig(- enabled=True,- token=server.token,- extra={"url": server.url, **extra},- )- return HomeAssistantAdapter(config)---# ----------------------------------------------------------------------------# 1. Gateway -- WebSocket lifecycle-# ------------------------------------------------------------------------------class TestGatewayWebSocket:- @pytest.mark.asyncio- async def test_connect_auth_subscribe(self):- """Full WS handshake succeeds: auth_required -> auth -> auth_ok -> subscribe -> ACK."""- async with FakeHAServer() as server:- adapter = _adapter_for(server)- connected = await adapter.connect()- assert connected is True- assert adapter._running is True- assert adapter._ws is not None- assert not adapter._ws.closed- await adapter.disconnect()-- @pytest.mark.asyncio- async def test_connect_auth_rejected(self):- """connect() returns False when the server rejects auth."""- async with FakeHAServer() as server:- server.reject_auth = True- adapter = _adapter_for(server)- connected = await adapter.connect()- assert connected is False-- @pytest.mark.asyncio- async def test_event_received_and_forwarded(self):- """Server pushes event -> adapter calls handle_message with correct MessageEvent."""- async with FakeHAServer() as server:- adapter = _adapter_for(server)- adapter.handle_message = AsyncMock()-- await adapter.connect()-- # Push a state_changed event- await server.push_event({- "data": {- "entity_id": "light.bedroom",- "old_state": {"state": "off", "attributes": {}},- "new_state": {- "state": "on",- "attributes": {"friendly_name": "Bedroom Light"},- },- }- })-- # Wait for the adapter to process it- for _ in range(50):- if adapter.handle_message.call_count > 0:- break- await asyncio.sleep(0.05)-- assert adapter.handle_message.call_count == 1- msg_event = adapter.handle_message.call_args[0][0]- assert "Bedroom Light" in msg_event.text- assert "turned on" in msg_event.text- assert msg_event.source.platform == Platform.HOMEASSISTANT-- await adapter.disconnect()-- @pytest.mark.asyncio- async def test_event_filtering_ignores_unwatched(self):- """Events outside watch_domains are silently dropped."""- async with FakeHAServer() as server:- adapter = _adapter_for(server, watch_domains=["climate"])- adapter.handle_message = AsyncMock()-- await adapter.connect()-- # Push a light event (not in watch_domains)- await server.push_event({- "data": {- "entity_id": "light.bedroom",- "old_state": {"state": "off", "attributes": {}},- "new_state": {- "state": "on",- "attributes": {"friendly_name": "Bedroom Light"},- },- }- })-- await asyncio.sleep(0.5)- assert adapter.handle_message.call_count == 0-- await adapter.disconnect()-- @pytest.mark.asyncio- async def test_disconnect_closes_cleanly(self):- """disconnect() cancels listener and closes WebSocket."""- async with FakeHAServer() as server:- adapter = _adapter_for(server)- await adapter.connect()- ws_ref = adapter._ws-- await adapter.disconnect()-- assert adapter._running is False- assert adapter._listen_task is None- assert adapter._ws is None- # The original WS reference should be closed- assert ws_ref.closed---# ----------------------------------------------------------------------------# 2. REST tool handlers (real HTTP against fake server)-# ------------------------------------------------------------------------------class TestToolRest:- """Call the async tool functions directly against the fake server.-- Note: we call ``_async_*`` instead of the sync ``_handle_*`` wrappers- because the sync wrappers use ``_run_async`` which blocks the event- loop, deadlocking with the in-process fake server. The async functions- are the real logic; the sync wrappers are trivial bridge code already- covered by unit tests.- """-- @pytest.mark.asyncio- async def test_list_entities_returns_all(self, monkeypatch):- """_async_list_entities returns all entities from the fake server."""- async with FakeHAServer() as server:- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token=server.token: (url, token))-- result = await _async_list_entities()-- assert result["count"] == len(ENTITY_STATES)- ids = {e["entity_id"] for e in result["entities"]}- assert "light.bedroom" in ids- assert "climate.thermostat" in ids-- @pytest.mark.asyncio- async def test_list_entities_domain_filter(self, monkeypatch):- """Domain filter is applied after fetching from server."""- async with FakeHAServer() as server:- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token=server.token: (url, token))-- result = await _async_list_entities(domain="light")-- assert result["count"] == 2- for e in result["entities"]:- assert e["entity_id"].startswith("light.")-- @pytest.mark.asyncio- async def test_get_state_single_entity(self, monkeypatch):- """_async_get_state returns full entity details."""- async with FakeHAServer() as server:- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token=server.token: (url, token))-- result = await _async_get_state("light.bedroom")-- assert result["entity_id"] == "light.bedroom"- assert result["state"] == "on"- assert result["attributes"]["brightness"] == 200- assert result["last_changed"] is not None-- @pytest.mark.asyncio- async def test_get_state_not_found(self, monkeypatch):- """Non-existent entity raises an aiohttp error (404)."""- import aiohttp as _aiohttp-- async with FakeHAServer() as server:- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token=server.token: (url, token))-- with pytest.raises(_aiohttp.ClientResponseError) as exc_info:- await _async_get_state("light.nonexistent")- assert exc_info.value.status == 404-- @pytest.mark.asyncio- async def test_call_service_turn_on(self, monkeypatch):- """_async_call_service sends correct payload and server records it."""- async with FakeHAServer() as server:- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token=server.token: (url, token))-- result = await _async_call_service(- domain="light",- service="turn_on",- entity_id="light.bedroom",- data={"brightness": 255},- )-- assert result["success"] is True- assert result["service"] == "light.turn_on"- assert len(result["affected_entities"]) == 1- assert result["affected_entities"][0]["state"] == "on"-- # Verify fake server recorded the call- assert len(server.received_service_calls) == 1- call = server.received_service_calls[0]- assert call["domain"] == "light"- assert call["service"] == "turn_on"- assert call["data"]["entity_id"] == "light.bedroom"- assert call["data"]["brightness"] == 255---# ----------------------------------------------------------------------------# 3. send() -- REST notification-# ------------------------------------------------------------------------------class TestSendNotification:- @pytest.mark.asyncio- async def test_send_notification_delivered(self):- """Adapter send() delivers notification to fake server REST endpoint."""- async with FakeHAServer() as server:- adapter = _adapter_for(server)-- result = await adapter.send("ha_events", "Test notification from agent")-- assert result.success is True- assert len(server.received_notifications) == 1- notif = server.received_notifications[0]- assert notif["title"] == "Hermes Agent"- assert notif["message"] == "Test notification from agent"-- @pytest.mark.asyncio- async def test_send_auth_failure(self):- """send() returns failure when token is wrong."""- async with FakeHAServer() as server:- config = PlatformConfig(- enabled=True,- token="wrong-token",- extra={"url": server.url},- )- adapter = HomeAssistantAdapter(config)-- result = await adapter.send("ha_events", "Should fail")-- assert result.success is False- assert "401" in result.error---# ----------------------------------------------------------------------------# 4. Auth and error cases-# ------------------------------------------------------------------------------class TestAuthAndErrors:- @pytest.mark.asyncio- async def test_rest_unauthorized(self, monkeypatch):- """Async function raises on 401 when token is wrong."""- import aiohttp as _aiohttp-- async with FakeHAServer() as server:- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token="bad-token": (url, token))-- with pytest.raises(_aiohttp.ClientResponseError) as exc_info:- await _async_list_entities()- assert exc_info.value.status == 401-- @pytest.mark.asyncio- async def test_rest_server_error(self, monkeypatch):- """Async function raises on 500 response."""- import aiohttp as _aiohttp-- async with FakeHAServer() as server:- server.force_500 = True- monkeypatch.setattr("tools.homeassistant_tool._get_config",- lambda url=server.url, token=server.token: (url, token))-- with pytest.raises(_aiohttp.ClientResponseError) as exc_info:- await _async_list_entities()- assert exc_info.value.status == 500diff --git a/tests/integration/test_modal_terminal.py b/tests/integration/test_modal_terminal.pydeleted file mode 100644index 024e6053fe6..00000000000--- a/tests/integration/test_modal_terminal.py+++ /dev/null@@ -1,285 +0,0 @@-#!/usr/bin/env python3-"""-Test Modal Terminal Tool--This script tests that the Modal terminal backend is correctly configured-and can execute commands in Modal sandboxes.--Usage:- # Run with Modal backend- TERMINAL_ENV=modal python tests/test_modal_terminal.py-- # Or run directly (will use whatever TERMINAL_ENV is set in .env)- python tests/test_modal_terminal.py-"""--import pytest-pytestmark = pytest.mark.integration--import os-import sys-import json-from pathlib import Path--# Try to load .env file if python-dotenv is available-try:- from dotenv import load_dotenv- load_dotenv()-except ImportError:- # Manually load .env if dotenv not available- env_file = Path(__file__).parent.parent.parent / ".env"- if env_file.exists():- with open(env_file) as f:- for line in f:- line = line.strip()- if line and not line.startswith('#') and '=' in line:- key, value = line.split('=', 1)- # Remove quotes if present- value = value.strip().strip('"').strip("'")- os.environ.setdefault(key.strip(), value)--# Add project root to path for imports-parent_dir = Path(__file__).parent.parent.parent-sys.path.insert(0, str(parent_dir))--from tools.terminal_tool import terminal_tool, check_terminal_requirements, _get_env_config # noqa: E402-from tools.terminal_tool_lifecycle import cleanup_vm # noqa: E402---def test_modal_requirements():- """Test that Modal requirements are met."""- print("\n" + "=" * 60)- print("TEST 1: Modal Requirements Check")- print("=" * 60)-- config = _get_env_config()- print(f"Current TERMINAL_ENV: {config['env_type']}")- print(f"Modal image: {config['modal_image']}")-- # Check for Modal authentication- modal_token = os.getenv("MODAL_TOKEN_ID")- modal_toml = Path.home() / ".modal.toml"-- print("\nModal authentication:")- print(f" MODAL_TOKEN_ID env var: {'✅ Set' if modal_token else '❌ Not set'}")- print(f" ~/.modal.toml file: {'✅ Exists' if modal_toml.exists() else '❌ Not found'}")-- if config['env_type'] != 'modal':- print(f"\n⚠️ TERMINAL_ENV is '{config['env_type']}', not 'modal'")- print(" Set TERMINAL_ENV=modal in .env or export it to test Modal backend")- return False-- requirements_met = check_terminal_requirements()- print(f"\nRequirements check: {'✅ Passed' if requirements_met else '❌ Failed'}")-- return requirements_met---def test_simple_command():- """Test executing a simple command."""- print("\n" + "=" * 60)- print("TEST 2: Simple Command Execution")- print("=" * 60)-- test_task_id = "modal_test_simple"-- print("Executing: echo 'Hello from Modal!'")- result = terminal_tool("echo 'Hello from Modal!'", task_id=test_task_id)- result_json = json.loads(result)-- print("\nResult:")- print(f" Output: {result_json.get('output', '')[:200]}")- print(f" Exit code: {result_json.get('exit_code')}")- print(f" Error: {result_json.get('error')}")-- success = result_json.get('exit_code') == 0 and 'Hello from Modal!' in result_json.get('output', '')- print(f"\nTest: {'✅ Passed' if success else '❌ Failed'}")-- # Cleanup- cleanup_vm(test_task_id)-- return success---def test_python_execution():- """Test executing Python code in Modal."""- print("\n" + "=" * 60)- print("TEST 3: Python Execution")- print("=" * 60)-- test_task_id = "modal_test_python"-- python_cmd = 'python3 -c "import sys; print(f\'Python {sys.version}\')"'- print(f"Executing: {python_cmd}")-- result = terminal_tool(python_cmd, task_id=test_task_id)- result_json = json.loads(result)-- print("\nResult:")- print(f" Output: {result_json.get('output', '')[:200]}")- print(f" Exit code: {result_json.get('exit_code')}")- print(f" Error: {result_json.get('error')}")-- success = result_json.get('exit_code') == 0 and 'Python' in result_json.get('output', '')- print(f"\nTest: {'✅ Passed' if success else '❌ Failed'}")-- # Cleanup- cleanup_vm(test_task_id)-- return success---def test_pip_install():- """Test installing a package with pip in Modal."""- print("\n" + "=" * 60)- print("TEST 4: Pip Install Test")- print("=" * 60)-- test_task_id = "modal_test_pip"-- # Install a small package and verify- print("Executing: pip install --break-system-packages cowsay && python3 -c \"import cowsay; cowsay.cow('Modal works!')\"")-- result = terminal_tool(- "pip install --break-system-packages cowsay && python3 -c \"import cowsay; cowsay.cow('Modal works!')\"",- task_id=test_task_id,- timeout=120- )- result_json = json.loads(result)-- print("\nResult:")- output = result_json.get('output', '')- print(f" Output (last 500 chars): ...{output[-500:] if len(output) > 500 else output}")- print(f" Exit code: {result_json.get('exit_code')}")- print(f" Error: {result_json.get('error')}")-- success = result_json.get('exit_code') == 0 and 'Modal works!' in result_json.get('output', '')- print(f"\nTest: {'✅ Passed' if success else '❌ Failed'}")-- # Cleanup- cleanup_vm(test_task_id)-- return success---def test_filesystem_persistence():- """Test that filesystem persists between commands in the same task."""- print("\n" + "=" * 60)- print("TEST 5: Filesystem Persistence")- print("=" * 60)-- test_task_id = "modal_test_persist"-- # Create a file- print("Step 1: Creating test file...")- result1 = terminal_tool("echo 'persistence test' > /tmp/modal_test.txt", task_id=test_task_id)- result1_json = json.loads(result1)- print(f" Exit code: {result1_json.get('exit_code')}")-- # Read the file back- print("Step 2: Reading test file...")- result2 = terminal_tool("cat /tmp/modal_test.txt", task_id=test_task_id)- result2_json = json.loads(result2)- print(f" Output: {result2_json.get('output', '')}")- print(f" Exit code: {result2_json.get('exit_code')}")-- success = (- result1_json.get('exit_code') == 0 and- result2_json.get('exit_code') == 0 and- 'persistence test' in result2_json.get('output', '')- )- print(f"\nTest: {'✅ Passed' if success else '❌ Failed'}")-- # Cleanup- cleanup_vm(test_task_id)-- return success---def test_environment_isolation():- """Test that different task_ids get isolated environments."""- print("\n" + "=" * 60)- print("TEST 6: Environment Isolation")- print("=" * 60)-- task1 = "modal_test_iso_1"- task2 = "modal_test_iso_2"-- # Create file in task1- print("Step 1: Creating file in task1...")- result1 = terminal_tool("echo 'task1 data' > /tmp/isolated.txt", task_id=task1)-- # Try to read from task2 (should not exist)- print("Step 2: Trying to read file from task2 (should not exist)...")- result2 = terminal_tool("cat /tmp/isolated.txt 2>&1 || echo 'FILE_NOT_FOUND'", task_id=task2)- result2_json = json.loads(result2)-- # The file should either not exist or be empty in task2- output = result2_json.get('output', '')- isolated = 'task1 data' not in output or 'FILE_NOT_FOUND' in output or 'No such file' in output-- print(f" Task2 output: {output[:200]}")- print(f"\nTest: {'✅ Passed (environments isolated)' if isolated else '❌ Failed (environments NOT isolated)'}")-- # Cleanup- cleanup_vm(task1)- cleanup_vm(task2)-- return isolated---def main():- """Run all Modal terminal tests."""- print("🧪 Modal Terminal Tool Test Suite")- print("=" * 60)-- # Check current config- config = _get_env_config()- print("\nCurrent configuration:")- print(f" TERMINAL_ENV: {config['env_type']}")- print(f" TERMINAL_MODAL_IMAGE: {config['modal_image']}")- print(f" TERMINAL_TIMEOUT: {config['timeout']}s")-- if config['env_type'] != 'modal':- print(f"\n⚠️ WARNING: TERMINAL_ENV is set to '{config['env_type']}', not 'modal'")- print(" To test Modal specifically, set TERMINAL_ENV=modal")- response = input("\n Continue testing with current backend? (y/n): ")- if response.lower() != 'y':- print("Aborting.")- return-- results = {}-- # Run tests- results['requirements'] = test_modal_requirements()-- if not results['requirements']:- print("\n❌ Requirements not met. Cannot continue with other tests.")- return-- results['simple_command'] = test_simple_command()- results['python_execution'] = test_python_execution()- results['pip_install'] = test_pip_install()- results['filesystem_persistence'] = test_filesystem_persistence()- results['environment_isolation'] = test_environment_isolation()-- # Summary- print("\n" + "=" * 60)- print("TEST SUMMARY")- print("=" * 60)-- passed = sum(1 for v in results.values() if v)- total = len(results)-- for test_name, passed_test in results.items():- status = "✅ PASSED" if passed_test else "❌ FAILED"- print(f" {test_name}: {status}")-- print(f"\nTotal: {passed}/{total} tests passed")-- return passed == total---if __name__ == "__main__":- success = main()- sys.exit(0 if success else 1)diff --git a/tests/integration/test_vision_docker_resolve.py b/tests/integration/test_vision_docker_resolve.pydeleted file mode 100644index 4ff3e46edea..00000000000--- a/tests/integration/test_vision_docker_resolve.py+++ /dev/null@@ -1,157 +0,0 @@-"""Docker integration tests for the vision image-source resolver.--Exercises the in-sandbox exec-read path that unit tests can only mock. Two-scenarios that ONLY the container filesystem can serve:-- * a tmpfs ``/workspace`` file with no host path at all, and- * a root-owned mode-600 file the host user cannot read,--both delivered by the resolver's ``base64`` exec-read fallback-(``tools/image_source._resolve_container_fallback``). This is the same path-that provides terminal-backend confinement for GHSA-gpxw-6wxv-w3qq: under a-non-local backend a non-cache path is read INSIDE the container, never on the-host.--Gating follows the repo convention: the ``integration`` marker excludes these-from the default suite (``addopts = -m 'not integration'`` in pyproject.toml);-they run under ``pytest -m integration`` when a Docker daemon is available and-skip cleanly when it is not. Container spin-up exceeds the 30s suite default,-so the timeout is bumped to 180s.--Run: pytest -m integration tests/integration/test_vision_docker_resolve.py-"""-import base64-import shutil-import subprocess--import pytest---def _docker_available() -> bool:- """True iff a docker CLI is on PATH and the daemon answers."""- if shutil.which("docker") is None:- return False- try:- return subprocess.run(- ["docker", "info"], capture_output=True, timeout=5- ).returncode == 0- except (subprocess.TimeoutExpired, OSError):- return False---pytestmark = [- pytest.mark.integration,- pytest.mark.timeout(180),- pytest.mark.skipif(not _docker_available(), reason="Docker daemon not available"),-]--# A real 1x1 PNG.-_TINY_PNG = base64.b64decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="-)---def docker_backend(request, monkeypatch):- """A live DockerEnvironment registered so ``get_active_env`` finds it.-- Unique task_id per test: DockerEnvironment derives the container name from- the task_id, so a shared id would make one test's teardown remove the- other's container.- """- from tools import terminal_tool- from tools.environments import docker as docker_env-- # The resolver keys the exec-read off TERMINAL_ENV=docker.- monkeypatch.setenv("TERMINAL_ENV", "docker")-- task_id = f"vision-docker-resolve-{request.node.name}"- env = docker_env.DockerEnvironment(- image="python:3.11-slim",- cwd="/workspace",- timeout=120,- task_id=task_id,- volumes=[],- network=False,- )- # Register under the raw task_id; get_active_env() falls back to the raw- # key after trying the _resolve_container_task_id() mapping.- with terminal_tool._env_lock:- terminal_tool._active_environments[task_id] = env- try:- env._task_id = task_id- yield env- finally:- with terminal_tool._env_lock:- terminal_tool._active_environments.pop(task_id, None)- try:- env.cleanup()- except Exception:- pass---def _write_png_in_container(env, path, *, mode=None):- b64 = base64.b64encode(_TINY_PNG).decode()- cmd = f"printf %s {b64} | base64 -d > {path}"- if mode:- cmd += f" && chmod {mode} {path}"- res = env.execute(cmd)- assert res.get("returncode", 1) == 0, res---async def test_resolves_tmpfs_workspace_file(docker_backend):- """A container-only path (no host file) is delivered via exec-read."""- from tools.image_source import ResolveContext, resolve_image_source-- _write_png_in_container(docker_backend, "/workspace/shot.png")- res = await resolve_image_source(- "/workspace/shot.png", ResolveContext(task_id=docker_backend._task_id))- assert res.origin == "container"- assert res.mime == "image/png"- assert res.data == _TINY_PNG---async def test_resolves_root_owned_mode600_file(docker_backend):- """Root-owned mode-600 (host user can't read it) is served in-container."""- from tools.image_source import ResolveContext, resolve_image_source-- _write_png_in_container(docker_backend, "/workspace/secret.png", mode="600")- res = await resolve_image_source(- "/workspace/secret.png", ResolveContext(task_id=docker_backend._task_id))- assert res.origin == "container"- assert res.mime == "image/png"- assert res.data == _TINY_PNG---async def test_host_secret_path_reads_container_not_host(docker_backend, tmp_path):- """The GHSA-gpxw invariant, end-to-end against real Docker.-- A path that exists on the HOST with secret bytes but does NOT exist in the- container must resolve to the container read (which fails to find it) —- never to the host bytes. Proves vision cannot exfiltrate a host file under- a sandbox backend even when the exact path is real on the host.- """- from tools.image_source import (- ImageResolutionError,- ResolveContext,- resolve_image_source,- )-- # A real host file outside any media cache, holding a secret.- host_secret = tmp_path / "id_rsa"- host_secret.write_bytes(b"HOST-PRIVATE-KEY-DO-NOT-LEAK")-- # That path does not exist inside the fresh container, so the exec-read- # finds nothing and the resolver refuses. The exact failure shape depends- # on the container's base64 build (some exit non-zero -> SourceNotFound,- # some print an error to stderr and exit 0 with empty stdout -> NotAnImage);- # both are ImageResolutionError. What matters for GHSA-gpxw: the resolver- # never returns the HOST bytes.- with pytest.raises(ImageResolutionError) as excinfo:- await resolve_image_source(- str(host_secret), ResolveContext(task_id=docker_backend._task_id))- # Belt and suspenders: the host secret must not appear anywhere in the error.- assert b"HOST-PRIVATE-KEY".decode() not in str(excinfo.value)diff --git a/tests/integration/test_voice_channel_flow.py b/tests/integration/test_voice_channel_flow.pydeleted file mode 100644index 4c6d5ae11cb..00000000000--- a/tests/integration/test_voice_channel_flow.py+++ /dev/null@@ -1,761 +0,0 @@-"""Integration tests for Discord voice channel audio flow.--Uses real NaCl encryption and Opus codec (no mocks for crypto/codec).-Does NOT require a Discord connection — tests the VoiceReceiver-packet processing pipeline end-to-end.--Requires: PyNaCl>=1.5.0, discord.py[voice] (opus codec)-"""--import struct-import time-import pytest--pytestmark = pytest.mark.integration--# Skip entire module if voice deps are missing-pytest.importorskip("nacl.secret", reason="PyNaCl required for voice integration tests")-discord = pytest.importorskip("discord", reason="discord.py required for voice integration tests")--import nacl.secret--try:- if not discord.opus.is_loaded():- import ctypes.util- opus_path = ctypes.util.find_library("opus")- if not opus_path:- for p in ("/opt/homebrew/lib/libopus.dylib", "/usr/local/lib/libopus.dylib"):- import os- if os.path.isfile(p):- opus_path = p- break- if opus_path:- discord.opus.load_opus(opus_path)- OPUS_AVAILABLE = discord.opus.is_loaded()-except Exception:- OPUS_AVAILABLE = False--from types import SimpleNamespace-from unittest.mock import MagicMock-from plugins.platforms.discord.adapter import VoiceReceiver---# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------def _make_secret_key():- """Generate a random 32-byte key."""- import os- return os.urandom(32)---def _build_encrypted_rtp_packet(secret_key, opus_payload, ssrc=100, seq=1, timestamp=960):- """Build a real NaCl-encrypted RTP packet matching Discord's format.-- Format: RTP header (12 bytes) + encrypted(opus) + 4-byte nonce- Encryption: aead_xchacha20_poly1305 with RTP header as AAD.- """- # RTP header: version=2, payload_type=0x78, no extension, no CSRC- header = struct.pack(">BBHII", 0x80, 0x78, seq, timestamp, ssrc)-- # Encrypt with NaCl AEAD- box = nacl.secret.Aead(secret_key)- nonce_counter = struct.pack(">I", seq) # 4-byte counter as nonce seed- # Full 24-byte nonce: counter in first 4 bytes, rest zeros- full_nonce = nonce_counter + b'\x00' * 20-- enc_msg = box.encrypt(opus_payload, header, full_nonce)- ciphertext = enc_msg.ciphertext # without nonce prefix-- # Discord format: header + ciphertext + 4-byte nonce- return header + ciphertext + nonce_counter---def _build_padded_rtp_packet(- secret_key, opus_payload, pad_len, ssrc=100, seq=1, timestamp=960,- declared_pad_len=None, ext_words=0,-):- """Build a NaCl-encrypted RTP packet with the P bit set and padding appended.-- Per RFC 3550 §5.1, the last padding byte declares how many trailing bytes- (including itself) to discard. ``pad_len`` is the actual padding appended;- ``declared_pad_len`` lets a test forge a mismatched declared length to- exercise the validation path. ``ext_words`` > 0 also sets the X bit and- prepends a synthetic extension block (4-byte preamble in cleartext header,- ext_words*4 bytes of encrypted extension data prepended to the payload).- """- if pad_len < 1:- raise ValueError("pad_len must be >= 1 (last byte includes itself)")- declared = pad_len if declared_pad_len is None else declared_pad_len- if declared < 0 or declared > 255:- raise ValueError("declared_pad_len must fit in one byte")-- has_extension = ext_words > 0- first_byte = 0xA0 | (0x10 if has_extension else 0) # V=2, P=1, [X=?], CC=0- fixed_header = struct.pack(">BBHII", first_byte, 0x78, seq, timestamp, ssrc)- if has_extension:- # 4-byte extension preamble: 2 bytes "defined by profile" + 2 bytes length-in-words- ext_preamble = struct.pack(">HH", 0xBEDE, ext_words)- header = fixed_header + ext_preamble- ext_data = b"\xab" * (ext_words * 4)- else:- header = fixed_header- ext_data = b""-- padding = b"\x00" * (pad_len - 1) + bytes([declared])- plaintext = ext_data + opus_payload + padding-- box = nacl.secret.Aead(secret_key)- nonce_counter = struct.pack(">I", seq)- full_nonce = nonce_counter + b"\x00" * 20-- enc_msg = box.encrypt(plaintext, header, full_nonce)- ciphertext = enc_msg.ciphertext-- return header + ciphertext + nonce_counter---def _make_voice_receiver(secret_key, dave_session=None, bot_ssrc=9999,- allowed_user_ids=None, members=None):- """Create a VoiceReceiver with real secret key."""- vc = MagicMock()- vc._connection.secret_key = list(secret_key)- vc._connection.dave_session = dave_session- vc._connection.ssrc = bot_ssrc- vc._connection.add_socket_listener = MagicMock()- vc._connection.remove_socket_listener = MagicMock()- vc._connection.hook = None- vc.user = SimpleNamespace(id=bot_ssrc)- vc.channel = MagicMock()- vc.channel.members = members or []- receiver = VoiceReceiver(vc, allowed_user_ids=allowed_user_ids)- receiver.start()- return receiver---# ----------------------------------------------------------------------------# Tests-# ------------------------------------------------------------------------------class TestRealNaClDecrypt:- """End-to-end: real NaCl encrypt → _on_packet decrypt → buffer."""-- def test_valid_encrypted_packet_buffered(self):- """Real NaCl encrypted packet → decrypted → buffered."""- key = _make_secret_key()- opus_silence = b'\xf8\xff\xfe'- receiver = _make_voice_receiver(key)-- packet = _build_encrypted_rtp_packet(key, opus_silence, ssrc=100)- receiver._on_packet(packet)-- assert 100 in receiver._buffers- assert len(receiver._buffers[100]) > 0-- def test_wrong_key_packet_dropped(self):- """Packet encrypted with wrong key → NaCl fails → not buffered."""- real_key = _make_secret_key()- wrong_key = _make_secret_key()- opus_silence = b'\xf8\xff\xfe'- receiver = _make_voice_receiver(real_key)-- packet = _build_encrypted_rtp_packet(wrong_key, opus_silence, ssrc=100)- receiver._on_packet(packet)-- assert len(receiver._buffers.get(100, b"")) == 0-- def test_bot_ssrc_ignored(self):- """Packet from bot's own SSRC → ignored."""- key = _make_secret_key()- receiver = _make_voice_receiver(key, bot_ssrc=9999)-- packet = _build_encrypted_rtp_packet(key, b'\xf8\xff\xfe', ssrc=9999)- receiver._on_packet(packet)-- assert len(receiver._buffers) == 0-- def test_multiple_packets_accumulate(self):- """Multiple valid packets → buffer grows."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)-- for seq in range(1, 6):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- assert 100 in receiver._buffers- buf_size = len(receiver._buffers[100])- assert buf_size > 0, "Multiple packets should accumulate in buffer"-- def test_different_ssrcs_separate_buffers(self):- """Packets from different SSRCs → separate buffers."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)-- for ssrc in [100, 200, 300]:- packet = _build_encrypted_rtp_packet(key, b'\xf8\xff\xfe', ssrc=ssrc)- receiver._on_packet(packet)-- assert len(receiver._buffers) == 3- for ssrc in [100, 200, 300]:- assert ssrc in receiver._buffers---class TestRealNaClWithDAVE:- """NaCl decrypt + DAVE passthrough scenarios with real crypto."""-- def test_dave_unknown_ssrc_passthrough(self):- """DAVE enabled but SSRC unknown → skip DAVE, buffer audio."""- key = _make_secret_key()- dave = MagicMock() # DAVE session present but SSRC not mapped- receiver = _make_voice_receiver(key, dave_session=dave)-- packet = _build_encrypted_rtp_packet(key, b'\xf8\xff\xfe', ssrc=100)- receiver._on_packet(packet)-- # DAVE decrypt not called (SSRC unknown)- dave.decrypt.assert_not_called()- # Audio still buffered via passthrough- assert 100 in receiver._buffers- assert len(receiver._buffers[100]) > 0-- def test_dave_unencrypted_error_passthrough(self):- """DAVE raises 'Unencrypted' → use NaCl-decrypted data as-is."""- key = _make_secret_key()- dave = MagicMock()- dave.decrypt.side_effect = Exception(- "DecryptionFailed(UnencryptedWhenPassthroughDisabled)"- )- receiver = _make_voice_receiver(key, dave_session=dave)- receiver.map_ssrc(100, 42)-- packet = _build_encrypted_rtp_packet(key, b'\xf8\xff\xfe', ssrc=100)- receiver._on_packet(packet)-- # DAVE was called but failed → passthrough- dave.decrypt.assert_called_once()- assert 100 in receiver._buffers- assert len(receiver._buffers[100]) > 0-- def test_dave_real_error_drops(self):- """DAVE raises non-Unencrypted error → packet dropped."""- key = _make_secret_key()- dave = MagicMock()- dave.decrypt.side_effect = Exception("KeyRotationFailed")- receiver = _make_voice_receiver(key, dave_session=dave)- receiver.map_ssrc(100, 42)-- packet = _build_encrypted_rtp_packet(key, b'\xf8\xff\xfe', ssrc=100)- receiver._on_packet(packet)-- assert len(receiver._buffers.get(100, b"")) == 0---class TestRTPPaddingStrip:- """RFC 3550 §5.1 — strip RTP padding before DAVE/Opus decode."""-- def test_padded_packet_stripped_and_buffered(self):- """P bit set → trailing padding stripped → opus payload decoded."""- key = _make_secret_key()- opus_silence = b"\xf8\xff\xfe"- receiver = _make_voice_receiver(key)-- # 5 bytes of padding (4 zeros + count byte = 5)- packet = _build_padded_rtp_packet(key, opus_silence, pad_len=5, ssrc=100)- receiver._on_packet(packet)-- assert 100 in receiver._buffers- assert len(receiver._buffers[100]) > 0-- def test_padded_packet_matches_unpadded_output(self):- """Same opus payload with/without padding → same decoded PCM."""- key = _make_secret_key()- opus_silence = b"\xf8\xff\xfe"-- recv_plain = _make_voice_receiver(key)- recv_plain._on_packet(- _build_encrypted_rtp_packet(key, opus_silence, ssrc=100)- )-- recv_padded = _make_voice_receiver(key)- recv_padded._on_packet(- _build_padded_rtp_packet(key, opus_silence, pad_len=7, ssrc=100)- )-- assert bytes(recv_plain._buffers[100]) == bytes(recv_padded._buffers[100])-- def test_padding_with_dave_passthrough(self):- """Padding stripped before DAVE → passthrough buffers cleanly."""- key = _make_secret_key()- opus_silence = b"\xf8\xff\xfe"- dave = MagicMock() # SSRC unmapped → DAVE skipped, passthrough used- receiver = _make_voice_receiver(key, dave_session=dave)-- packet = _build_padded_rtp_packet(key, opus_silence, pad_len=4, ssrc=100)- receiver._on_packet(packet)-- dave.decrypt.assert_not_called()- assert 100 in receiver._buffers- assert len(receiver._buffers[100]) > 0-- def test_invalid_padding_length_zero_dropped(self):- """Declared pad_len=0 is invalid (RFC requires count includes itself)."""- key = _make_secret_key()- opus_silence = b"\xf8\xff\xfe"- receiver = _make_voice_receiver(key)-- packet = _build_padded_rtp_packet(- key, opus_silence, pad_len=4, declared_pad_len=0, ssrc=100- )- receiver._on_packet(packet)-- assert len(receiver._buffers.get(100, b"")) == 0-- def test_invalid_padding_length_overflow_dropped(self):- """Declared pad_len > payload size → packet dropped."""- key = _make_secret_key()- opus_silence = b"\xf8\xff\xfe"- receiver = _make_voice_receiver(key)-- packet = _build_padded_rtp_packet(- key, opus_silence, pad_len=4, declared_pad_len=255, ssrc=100- )- receiver._on_packet(packet)-- assert len(receiver._buffers.get(100, b"")) == 0-- def test_padding_consuming_entire_payload_dropped(self):- """Padding consumes entire payload → no opus data → dropped."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)-- # Empty opus payload, 6 bytes of padding (count byte declares 6)- packet = _build_padded_rtp_packet(key, b"", pad_len=6, ssrc=100)- receiver._on_packet(packet)-- assert len(receiver._buffers.get(100, b"")) == 0-- def test_padding_with_extension_stripped_correctly(self):- """X+P bits both set → strip extension from start, padding from end."""- key = _make_secret_key()- opus_silence = b"\xf8\xff\xfe"-- # Same opus payload sent two ways: plain, and with both ext+padding- recv_plain = _make_voice_receiver(key)- recv_plain._on_packet(- _build_encrypted_rtp_packet(key, opus_silence, ssrc=100)- )-- recv_ext_pad = _make_voice_receiver(key)- recv_ext_pad._on_packet(- _build_padded_rtp_packet(- key, opus_silence, pad_len=5, ext_words=2, ssrc=100- )- )-- # Both must yield identical decoded PCM — ext data and padding both- # stripped before opus decode.- assert bytes(recv_plain._buffers[100]) == bytes(recv_ext_pad._buffers[100])---class TestFullVoiceFlow:- """End-to-end: encrypt → receive → buffer → silence detect → complete."""-- def test_single_utterance_flow(self):- """Encrypt packets → buffer → silence → check_silence returns utterance."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(100, 42)-- # Send enough packets to exceed MIN_SPEECH_DURATION (0.5s)- # At 48kHz stereo 16-bit, each Opus silence frame decodes to ~3840 bytes- # Need 96000 bytes = ~25 frames- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- # Simulate silence by setting last_packet_time in the past- receiver._last_packet_time[100] = time.monotonic() - 3.0-- completed = receiver.check_silence()- assert len(completed) == 1- user_id, pcm_data = completed[0]- assert user_id == 42- assert len(pcm_data) > 0-- def test_utterance_with_ssrc_automap(self):- """No SPEAKING event → auto-map sole allowed user → utterance processed."""- key = _make_secret_key()- members = [- SimpleNamespace(id=9999, name="Bot"),- SimpleNamespace(id=42, name="Alice"),- ]- receiver = _make_voice_receiver(- key, allowed_user_ids={"42"}, members=members- )- # No map_ssrc call — simulating missing SPEAKING event-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- receiver._last_packet_time[100] = time.monotonic() - 3.0-- completed = receiver.check_silence()- assert len(completed) == 1- assert completed[0][0] == 42 # auto-mapped to sole allowed user-- def test_pause_blocks_during_playback(self):- """Pause receiver → packets ignored → resume → packets accepted."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)-- # Pause (echo prevention during TTS playback)- receiver.pause()- packet = _build_encrypted_rtp_packet(key, b'\xf8\xff\xfe', ssrc=100)- receiver._on_packet(packet)- assert len(receiver._buffers.get(100, b"")) == 0-- # Resume- receiver.resume()- receiver._on_packet(packet)- assert 100 in receiver._buffers- assert len(receiver._buffers[100]) > 0-- def test_corrupted_packet_ignored(self):- """Corrupted/truncated packet → silently ignored."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)-- # Too short- receiver._on_packet(b"\x00" * 5)- assert len(receiver._buffers) == 0-- # Wrong RTP version- bad_header = struct.pack(">BBHII", 0x00, 0x78, 1, 960, 100)- receiver._on_packet(bad_header + b"\x00" * 20)- assert len(receiver._buffers) == 0-- # Wrong payload type- bad_pt = struct.pack(">BBHII", 0x80, 0x00, 1, 960, 100)- receiver._on_packet(bad_pt + b"\x00" * 20)- assert len(receiver._buffers) == 0-- def test_stop_cleans_everything(self):- """stop() clears all state cleanly."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(100, 42)-- for seq in range(1, 10):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- assert len(receiver._buffers[100]) > 0-- receiver.stop()- assert receiver._running is False- assert len(receiver._buffers) == 0- assert len(receiver._ssrc_to_user) == 0- assert len(receiver._decoders) == 0---class TestSPEAKINGHook:- """SPEAKING event hook correctly maps SSRC to user_id."""-- def test_speaking_hook_installed(self):- """start() installs speaking hook on connection."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- conn = receiver._vc._connection- # hook should be set (wrapped)- assert conn.hook is not None-- def test_map_ssrc_via_speaking(self):- """SPEAKING op 5 event maps SSRC to user_id."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(500, 12345)- assert receiver._ssrc_to_user[500] == 12345-- def test_map_ssrc_overwrites(self):- """New SPEAKING event for same SSRC overwrites old mapping."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(500, 111)- receiver.map_ssrc(500, 222)- assert receiver._ssrc_to_user[500] == 222-- def test_speaking_mapped_audio_processed(self):- """After SSRC is mapped, audio from that SSRC gets correct user_id."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(100, 42)-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- receiver._last_packet_time[100] = time.monotonic() - 3.0- completed = receiver.check_silence()- assert len(completed) == 1- assert completed[0][0] == 42---class TestAuthFiltering:- """Only allowed users' audio should be processed."""-- def test_allowed_user_audio_processed(self):- """Allowed user's utterance is returned by check_silence."""- key = _make_secret_key()- members = [- SimpleNamespace(id=9999, name="Bot"),- SimpleNamespace(id=42, name="Alice"),- ]- receiver = _make_voice_receiver(- key, allowed_user_ids={"42"}, members=members,- )- receiver.map_ssrc(100, 42)-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- receiver._last_packet_time[100] = time.monotonic() - 3.0- completed = receiver.check_silence()- assert len(completed) == 1- assert completed[0][0] == 42-- def test_automap_rejects_unallowed_user(self):- """Auto-map refuses to map SSRC to user not in allowed list."""- key = _make_secret_key()- members = [- SimpleNamespace(id=9999, name="Bot"),- SimpleNamespace(id=42, name="Alice"),- ]- receiver = _make_voice_receiver(- key, allowed_user_ids={"99"}, # Alice not allowed- members=members,- )- # No map_ssrc — SSRC unknown, auto-map should reject-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- receiver._last_packet_time[100] = time.monotonic() - 3.0- completed = receiver.check_silence()- assert len(completed) == 0-- def test_empty_allowlist_allows_all(self):- """Empty allowed_user_ids means no restriction."""- key = _make_secret_key()- members = [- SimpleNamespace(id=9999, name="Bot"),- SimpleNamespace(id=42, name="Alice"),- ]- receiver = _make_voice_receiver(- key, allowed_user_ids=None, members=members,- )-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- receiver._last_packet_time[100] = time.monotonic() - 3.0- completed = receiver.check_silence()- # Auto-mapped to sole non-bot member- assert len(completed) == 1- assert completed[0][0] == 42---class TestRejoinFlow:- """Leave and rejoin: state cleanup and fresh receiver."""-- def test_stop_then_new_receiver_clean_state(self):- """After stop(), a new receiver starts with empty state."""- key = _make_secret_key()- receiver1 = _make_voice_receiver(key)- receiver1.map_ssrc(100, 42)-- for seq in range(1, 10):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver1._on_packet(packet)-- assert len(receiver1._buffers[100]) > 0- receiver1.stop()-- # New receiver (simulates rejoin)- receiver2 = _make_voice_receiver(key)- assert len(receiver2._buffers) == 0- assert len(receiver2._ssrc_to_user) == 0- assert len(receiver2._decoders) == 0-- def test_rejoin_new_ssrc_works(self):- """After rejoin, user may get new SSRC — still works."""- key = _make_secret_key()- receiver1 = _make_voice_receiver(key)- receiver1.map_ssrc(100, 42) # old SSRC- receiver1.stop()-- receiver2 = _make_voice_receiver(key)- receiver2.map_ssrc(200, 42) # new SSRC after rejoin-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=200, seq=seq, timestamp=960 * seq- )- receiver2._on_packet(packet)-- receiver2._last_packet_time[200] = time.monotonic() - 3.0- completed = receiver2.check_silence()- assert len(completed) == 1- assert completed[0][0] == 42-- def test_rejoin_without_speaking_event_automap(self):- """Rejoin without SPEAKING event — auto-map sole allowed user."""- key = _make_secret_key()- members = [- SimpleNamespace(id=9999, name="Bot"),- SimpleNamespace(id=42, name="Alice"),- ]-- # First session- receiver1 = _make_voice_receiver(- key, allowed_user_ids={"42"}, members=members,- )- receiver1.stop()-- # Rejoin — new key (Discord may assign new secret_key)- new_key = _make_secret_key()- receiver2 = _make_voice_receiver(- new_key, allowed_user_ids={"42"}, members=members,- )- # No map_ssrc — simulating missing SPEAKING event-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- new_key, b'\xf8\xff\xfe', ssrc=300, seq=seq, timestamp=960 * seq- )- receiver2._on_packet(packet)-- receiver2._last_packet_time[300] = time.monotonic() - 3.0- completed = receiver2.check_silence()- assert len(completed) == 1- assert completed[0][0] == 42---class TestMultiGuildIsolation:- """Each guild has independent voice state."""-- def test_separate_receivers_independent(self):- """Two receivers (different guilds) don't interfere."""- key1 = _make_secret_key()- key2 = _make_secret_key()-- receiver1 = _make_voice_receiver(key1, bot_ssrc=1111)- receiver2 = _make_voice_receiver(key2, bot_ssrc=2222)-- receiver1.map_ssrc(100, 42)- receiver2.map_ssrc(200, 99)-- # Send to receiver1- for seq in range(1, 10):- packet = _build_encrypted_rtp_packet(- key1, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver1._on_packet(packet)-- # receiver2 should be empty- assert len(receiver2._buffers) == 0- assert 100 in receiver1._buffers-- def test_stop_one_doesnt_affect_other(self):- """Stopping one receiver doesn't affect another."""- key1 = _make_secret_key()- key2 = _make_secret_key()-- receiver1 = _make_voice_receiver(key1)- receiver2 = _make_voice_receiver(key2)-- receiver1.map_ssrc(100, 42)- receiver2.map_ssrc(200, 99)-- for seq in range(1, 10):- packet = _build_encrypted_rtp_packet(- key2, b'\xf8\xff\xfe', ssrc=200, seq=seq, timestamp=960 * seq- )- receiver2._on_packet(packet)-- receiver1.stop()-- # receiver2 still has data- assert receiver2._running is True- assert len(receiver2._buffers[200]) > 0---class TestEchoPreventionFlow:- """Receiver pause/resume during TTS playback prevents echo."""-- def test_audio_during_pause_ignored(self):- """Audio arriving while paused is completely ignored."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(100, 42)- receiver.pause()-- for seq in range(1, 30):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- assert len(receiver._buffers.get(100, b"")) == 0-- def test_audio_after_resume_processed(self):- """Audio arriving after resume is processed normally."""- key = _make_secret_key()- receiver = _make_voice_receiver(key)- receiver.map_ssrc(100, 42)-- # Pause → send packets → resume → send more packets- receiver.pause()- for seq in range(1, 5):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)- assert len(receiver._buffers.get(100, b"")) == 0-- receiver.resume()- for seq in range(5, 35):- packet = _build_encrypted_rtp_packet(- key, b'\xf8\xff\xfe', ssrc=100, seq=seq, timestamp=960 * seq- )- receiver._on_packet(packet)-- assert len(receiver._buffers[100]) > 0- receiver._last_packet_time[100] = time.monotonic() - 3.0- completed = receiver.check_silence()- assert len(completed) == 1- assert completed[0][0] == 42diff --git a/tests/integration/test_web_tools.py b/tests/integration/test_web_tools.pydeleted file mode 100644index 11fade5ee16..00000000000--- a/tests/integration/test_web_tools.py+++ /dev/null@@ -1,505 +0,0 @@-#!/usr/bin/env python3-"""-Comprehensive Test Suite for Web Tools Module--This script tests all web tools functionality to ensure they work correctly.-Run this after any updates to the web_tools.py module or backend libraries.--Usage:- python test_web_tools.py # Run all tests- python test_web_tools.py --no-llm # Skip LLM processing tests- python test_web_tools.py --verbose # Show detailed output--Requirements:- - PARALLEL_API_KEY or FIRECRAWL_API_KEY environment variable must be set- - An auxiliary LLM provider (OPENROUTER_API_KEY or Nous Portal auth) (optional, for LLM tests)-"""--import pytest-pytestmark = pytest.mark.integration--import json-import asyncio-import sys-import os-import argparse-from datetime import datetime-from typing import List--# Import the web tools to test (updated path after moving tools/)-from tools.web_tools import (- web_search_tool,- web_extract_tool,- check_firecrawl_api_key,- check_web_api_key,- _get_backend,-)---class Colors:- """ANSI color codes for terminal output"""- HEADER = '\033[95m'- BLUE = '\033[94m'- CYAN = '\033[96m'- GREEN = '\033[92m'- WARNING = '\033[93m'- FAIL = '\033[91m'- ENDC = '\033[0m'- BOLD = '\033[1m'- UNDERLINE = '\033[4m'---def print_header(text: str):- """Print a formatted header"""- print(f"\n{Colors.HEADER}{Colors.BOLD}{'='*60}{Colors.ENDC}")- print(f"{Colors.HEADER}{Colors.BOLD}{text}{Colors.ENDC}")- print(f"{Colors.HEADER}{Colors.BOLD}{'='*60}{Colors.ENDC}")---def print_section(text: str):- """Print a formatted section header"""- print(f"\n{Colors.CYAN}{Colors.BOLD}📌 {text}{Colors.ENDC}")- print(f"{Colors.CYAN}{'-'*50}{Colors.ENDC}")---def print_success(text: str):- """Print success message"""- print(f"{Colors.GREEN}✅ {text}{Colors.ENDC}")---def print_error(text: str):- """Print error message"""- print(f"{Colors.FAIL}❌ {text}{Colors.ENDC}")---def print_warning(text: str):- """Print warning message"""- print(f"{Colors.WARNING}⚠️ {text}{Colors.ENDC}")---def print_info(text: str, indent: int = 0):- """Print info message"""- indent_str = " " * indent- print(f"{indent_str}{Colors.BLUE}ℹ️ {text}{Colors.ENDC}")---class WebToolsTester:- """Test suite for web tools"""-- def __init__(self, verbose: bool = False, test_llm: bool = True):- self.verbose = verbose- self.test_llm = test_llm- self.test_results = {- "passed": [],- "failed": [],- "skipped": []- }- self.start_time = None- self.end_time = None-- def log_result(self, test_name: str, status: str, details: str = ""):- """Log test result"""- result = {- "test": test_name,- "status": status,- "details": details,- "timestamp": datetime.now().isoformat()- }-- if status == "passed":- self.test_results["passed"].append(result)- print_success(f"{test_name}: {details}" if details else test_name)- elif status == "failed":- self.test_results["failed"].append(result)- print_error(f"{test_name}: {details}" if details else test_name)- elif status == "skipped":- self.test_results["skipped"].append(result)- print_warning(f"{test_name} skipped: {details}" if details else f"{test_name} skipped")-- def test_environment(self) -> bool:- """Test environment setup and API keys"""- print_section("Environment Check")-- # Check web backend API key (Parallel or Firecrawl)- if not check_web_api_key():- self.log_result("Web Backend API Key", "failed", "PARALLEL_API_KEY or FIRECRAWL_API_KEY not set")- return False- else:- backend = _get_backend()- self.log_result("Web Backend API Key", "passed", f"Using {backend} backend")-- # Auxiliary LLM summarization was removed — web_extract is now- # truncate-and-store (no LLM). Keep the flag off so any residual- # LLM-path assertions stay skipped.- self.log_result("Auxiliary LLM", "skipped", "web_extract no longer uses an LLM (truncate-and-store)")- self.test_llm = False-- return True-- def test_web_search(self) -> List[str]:- """Test web search functionality"""- print_section("Test 1: Web Search")-- test_queries = [- ("Python web scraping tutorial", 5),- ("Firecrawl API documentation", 3),- ("inflammatory arthritis symptoms treatment", 8) # Test medical query from your example- ]-- extracted_urls = []-- for query, limit in test_queries:- try:- print(f"\n Testing search: '{query}' (limit={limit})")-- if self.verbose:- print(f" Calling web_search_tool(query='{query}', limit={limit})")-- # Perform search- result = web_search_tool(query, limit)-- # Parse result- try:- data = json.loads(result)- except json.JSONDecodeError as e:- self.log_result(f"Search: {query[:30]}...", "failed", f"Invalid JSON: {e}")- if self.verbose:- print(f" Raw response (first 500 chars): {result[:500]}...")- continue-- if "error" in data:- self.log_result(f"Search: {query[:30]}...", "failed", f"API error: {data['error']}")- continue-- # Check structure- if "success" not in data or "data" not in data:- self.log_result(f"Search: {query[:30]}...", "failed", "Missing success or data fields")- if self.verbose:- print(f" Response keys: {list(data.keys())}")- continue-- web_results = data.get("data", {}).get("web", [])-- if not web_results:- self.log_result(f"Search: {query[:30]}...", "failed", "Empty web results array")- if self.verbose:- print(f" data.web content: {data.get('data', {}).get('web')}")- continue-- # Validate each result- valid_results = 0- missing_fields = []-- for i, result in enumerate(web_results):- required_fields = ["url", "title", "description"]- has_all_fields = all(key in result for key in required_fields)-- if has_all_fields:- valid_results += 1- # Collect URLs for extraction test- if len(extracted_urls) < 3:- extracted_urls.append(result["url"])-- if self.verbose:- print(f" Result {i+1}: ✓ {result['title'][:50]}...")- print(f" URL: {result['url'][:60]}...")- else:- missing = [f for f in required_fields if f not in result]- missing_fields.append(f"Result {i+1} missing: {missing}")- if self.verbose:- print(f" Result {i+1}: ✗ Missing fields: {missing}")-- # Log results- if valid_results == len(web_results):- self.log_result(- f"Search: {query[:30]}...",- "passed",- f"All {valid_results} results valid"- )- else:- self.log_result(- f"Search: {query[:30]}...",- "failed",- f"Only {valid_results}/{len(web_results)} valid. Issues: {'; '.join(missing_fields[:3])}"- )-- except Exception as e:- self.log_result(f"Search: {query[:30]}...", "failed", f"Exception: {type(e).__name__}: {str(e)}")- if self.verbose:- import traceback- print(f" Traceback: {traceback.format_exc()}")-- if self.verbose and extracted_urls:- print(f"\n URLs collected for extraction test: {len(extracted_urls)}")- for url in extracted_urls:- print(f" - {url}")-- return extracted_urls-- async def test_web_extract(self, urls: List[str] = None):- """Test web content extraction"""- print_section("Test 2: Web Extract (without LLM)")-- # Use provided URLs or defaults- if not urls:- urls = [- "https://docs.firecrawl.dev/introduction",- "https://www.python.org/about/"- ]- print(" Using default URLs for testing")- else:- print(f" Using {len(urls)} URLs from search results")-- # Test extraction- if urls:- try:- test_urls = urls[:2] # Test with max 2 URLs- print(f"\n Extracting content from {len(test_urls)} URL(s)...")- for url in test_urls:- print(f" - {url}")-- if self.verbose:- print(f" Calling web_extract_tool(urls={test_urls}, format='markdown')")-- result = await web_extract_tool(- test_urls,- format="markdown",- )-- # Parse result- try:- data = json.loads(result)- except json.JSONDecodeError as e:- self.log_result("Extract (no LLM)", "failed", f"Invalid JSON: {e}")- if self.verbose:- print(f" Raw response (first 500 chars): {result[:500]}...")- return-- if "error" in data:- self.log_result("Extract (no LLM)", "failed", f"API error: {data['error']}")- return-- results = data.get("results", [])-- if not results:- self.log_result("Extract (no LLM)", "failed", "No results in response")- if self.verbose:- print(f" Response keys: {list(data.keys())}")- return-- # Validate each result- valid_results = 0- failed_results = 0- total_content_length = 0- extraction_details = []-- for i, result in enumerate(results):- title = result.get("title", "No title")- content = result.get("content", "")- error = result.get("error")-- if error:- failed_results += 1- extraction_details.append(f"Page {i+1}: ERROR - {error}")- if self.verbose:- print(f" Page {i+1}: ✗ Error - {error}")- elif content:- content_len = len(content)- total_content_length += content_len- valid_results += 1- extraction_details.append(f"Page {i+1}: {title[:40]}... ({content_len} chars)")- if self.verbose:- print(f" Page {i+1}: ✓ {title[:50]}... - {content_len} characters")- print(f" First 100 chars: {content[:100]}...")- else:- extraction_details.append(f"Page {i+1}: {title[:40]}... (EMPTY)")- if self.verbose:- print(f" Page {i+1}: ⚠ {title[:50]}... - Empty content")-- # Log results- if valid_results > 0:- self.log_result(- "Extract (no LLM)",- "passed",- f"{valid_results}/{len(results)} pages extracted, {total_content_length} total chars"- )- else:- self.log_result(- "Extract (no LLM)",- "failed",- f"No valid content. {failed_results} errors, {len(results) - failed_results} empty"- )- if self.verbose:- print("\n Extraction details:")- for detail in extraction_details:- print(f" {detail}")-- except Exception as e:- self.log_result("Extract (no LLM)", "failed", f"Exception: {type(e).__name__}: {str(e)}")- if self.verbose:- import traceback- print(f" Traceback: {traceback.format_exc()}")-- async def test_web_extract_with_llm(self, urls: List[str] = None):- """Test web extraction with LLM processing"""- print_section("Test 3: Web Extract (with Gemini LLM)")-- if not self.test_llm:- self.log_result("Extract (with LLM)", "skipped", "LLM testing disabled")- return-- # Use a URL likely to have substantial content- test_url = urls[0] if urls else "https://docs.firecrawl.dev/features/scrape"-- try:- print(f"\n Extracting and processing: {test_url}")-- result = await web_extract_tool(- [test_url],- format="markdown",- char_limit=1000, # small budget to force truncation in the test- )-- data = json.loads(result)-- if "error" in data:- self.log_result("Extract (with LLM)", "failed", data["error"])- return-- results = data.get("results", [])-- if not results:- self.log_result("Extract (with LLM)", "failed", "No results returned")- return-- result = results[0]- content = result.get("content", "")-- if content:- content_len = len(content)-- # Check if content was actually processed (should be shorter than typical raw content)- if content_len > 0:- self.log_result(- "Extract (with LLM)",- "passed",- f"Content processed: {content_len} chars"- )-- if self.verbose:- print("\n First 300 chars of processed content:")- print(f" {content[:300]}...")- else:- self.log_result("Extract (with LLM)", "failed", "No content after processing")- else:- self.log_result("Extract (with LLM)", "failed", "No content field in result")-- except json.JSONDecodeError as e:- self.log_result("Extract (with LLM)", "failed", f"Invalid JSON: {e}")- except Exception as e:- self.log_result("Extract (with LLM)", "failed", str(e))-- async def run_all_tests(self):- """Run all tests"""- self.start_time = datetime.now()-- print_header("WEB TOOLS TEST SUITE")- print(f"Started at: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}")-- # Test environment- if not self.test_environment():- print_error("\nCannot proceed without required API keys!")- return False-- # Test search and collect URLs- urls = self.test_web_search()-- # Test extraction- await self.test_web_extract(urls if urls else None)-- # Test extraction with LLM- if self.test_llm:- await self.test_web_extract_with_llm(urls if urls else None)-- # Print summary- self.end_time = datetime.now()- duration = (self.end_time - self.start_time).total_seconds()-- print_header("TEST SUMMARY")- print(f"Duration: {duration:.2f} seconds")- print(f"\n{Colors.GREEN}Passed: {len(self.test_results['passed'])}{Colors.ENDC}")- print(f"{Colors.FAIL}Failed: {len(self.test_results['failed'])}{Colors.ENDC}")- print(f"{Colors.WARNING}Skipped: {len(self.test_results['skipped'])}{Colors.ENDC}")-- # List failed tests- if self.test_results["failed"]:- print(f"\n{Colors.FAIL}{Colors.BOLD}Failed Tests:{Colors.ENDC}")- for test in self.test_results["failed"]:- print(f" - {test['test']}: {test['details']}")-- # Save results to file- self.save_results()-- return len(self.test_results["failed"]) == 0-- def save_results(self):- """Save test results to a JSON file"""- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- filename = f"test_results_web_tools_{timestamp}.json"-- results = {- "test_suite": "Web Tools",- "start_time": self.start_time.isoformat() if self.start_time else None,- "end_time": self.end_time.isoformat() if self.end_time else None,- "duration_seconds": (self.end_time - self.start_time).total_seconds() if self.start_time and self.end_time else None,- "summary": {- "passed": len(self.test_results["passed"]),- "failed": len(self.test_results["failed"]),- "skipped": len(self.test_results["skipped"])- },- "results": self.test_results,- "environment": {- "web_backend": _get_backend() if check_web_api_key() else None,- "firecrawl_api_key": check_firecrawl_api_key(),- "parallel_api_key": bool(os.getenv("PARALLEL_API_KEY")),- "auxiliary_model": False,- }- }-- try:- with open(filename, 'w') as f:- json.dump(results, f, indent=2, ensure_ascii=False)- print_info(f"Test results saved to: {filename}")- except Exception as e:- print_warning(f"Failed to save results: {e}")---async def main():- """Main entry point"""- parser = argparse.ArgumentParser(description="Test Web Tools Module")- parser.add_argument("--no-llm", action="store_true", help="Skip LLM processing tests")- parser.add_argument("--verbose", "-v", action="store_true", help="Show detailed output")- parser.add_argument("--debug", action="store_true", help="Enable debug mode for web tools")-- args = parser.parse_args()-- # Set debug mode if requested- if args.debug:- os.environ["WEB_TOOLS_DEBUG"] = "true"- print_info("Debug mode enabled for web tools")-- # Create tester- tester = WebToolsTester(- verbose=args.verbose,- test_llm=not args.no_llm- )-- # Run tests- success = await tester.run_all_tests()-- # Exit with appropriate code- sys.exit(0 if success else 1)---if __name__ == "__main__":- asyncio.run(main())diff --git a/tests/monitoring/test_cron_health_export.py b/tests/monitoring/test_cron_health_export.pyindex 5ea801fefd3..4d0f8d691b0 100644--- a/tests/monitoring/test_cron_health_export.py+++ b/tests/monitoring/test_cron_health_export.py@@ -125,12 +125,3 @@ def test_registered_observable_metric_names_cover_snapshot_metrics(monkeypatch):assert not missing, f"gauges emitted but NOT registered in metric_names (will be silently dropped): {sorted(missing)}"-def test_monitoring_docs_distinguish_relay_health_scope_and_terminal_flush():- from pathlib import Path-- text = Path("website/docs/developer-guide/gateway-monitoring.md").read_text(encoding="utf-8")-- assert "Hermes Agent-owned Relay transport health" in text- assert "authoritative shared connector/platform state" in text- assert "up to one second" in text- assert "terminal" in textdiff --git a/tests/monitoring/test_emitter.py b/tests/monitoring/test_emitter.pyindex 6c4883072c4..d3c3a341252 100644--- a/tests/monitoring/test_emitter.py+++ b/tests/monitoring/test_emitter.py@@ -2,7 +2,6 @@from __future__ import annotations-import timefrom agent.monitoring.emitter import MonitoringEmitter@@ -55,12 +54,3 @@ def test_unsubscribe_stops_delivery():-def test_hot_path_is_fast():- em = MonitoringEmitter()- start = time.perf_counter()- for _ in range(1_000):- em.emit({"event": "gateway_health", "name": "gateway.health_snapshot"})- elapsed = time.perf_counter() - start- em.close()- # 1000 emits should be far under a second even on slow CI.- assert elapsed < 1.0diff --git a/tests/openviking_plugin/test_openviking.py b/tests/openviking_plugin/test_openviking.pyindex b01e7d70bb9..1edfce1bd22 100644--- a/tests/openviking_plugin/test_openviking.py+++ b/tests/openviking_plugin/test_openviking.py@@ -3,7 +3,6 @@import jsonimport osimport threading-import timefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom typing import Any, castfrom urllib.parse import parse_qs, urlparse@@ -269,36 +268,6 @@ class TestOpenVikingSkillQuerySafety:class TestOpenVikingConfigSchema:- def test_recall_policy_options_are_exposed_in_setup_schema(self):- provider = OpenVikingMemoryProvider()-- schema = provider.get_config_schema()- fields = {entry["key"]: entry for entry in schema}- env_vars = {entry.get("env_var") for entry in schema}-- assert "OPENVIKING_RECALL_LIMIT" in env_vars- assert "OPENVIKING_RECALL_SCORE_THRESHOLD" in env_vars- assert "OPENVIKING_RECALL_MAX_INJECTED_CHARS" in env_vars- assert "OPENVIKING_RECALL_TIMEOUT_SECONDS" in env_vars- assert "OPENVIKING_RECALL_REQUEST_TIMEOUT_SECONDS" in env_vars- assert "OPENVIKING_RECALL_FULL_READ_LIMIT" in env_vars- assert "OPENVIKING_RECALL_PREFER_ABSTRACT" in env_vars- assert "OPENVIKING_RECALL_RESOURCES" in env_vars- assert fields["recall_limit"]["type"] == "integer"- assert fields["recall_limit"]["minimum"] == 1- assert fields["recall_limit"]["maximum"] == 100- assert fields["recall_score_threshold"]["type"] == "number"- assert fields["recall_prefer_abstract"]["type"] == "boolean"- assert provider._recall_config() == {- "limit": 6,- "score_threshold": 0.15,- "max_injected_chars": 4000,- "timeout_seconds": 4.0,- "request_timeout_seconds": 3.0,- "full_read_limit": 2,- "prefer_abstract": False,- "resources": False,- }def test_recall_config_reads_from_config_yaml(self, monkeypatch, tmp_path):"""_recall_config() reads memory.openviking values from config.yaml when@@ -1297,142 +1266,8 @@ class TestEnsureClientFailureHardening:assert built.endpoint == "https://up.example"-class TestUnavailableWarningsPromiseRetry:- """Every "OpenViking is unavailable" warning must describe what actually- happens next.-- ``_ensure_client()`` rebuilds and re-probes the client whenever the- resolved config changes or the failed-config cooldown has elapsed, so no- warning may tell the user memory is off for the rest of the run — that- reads as "it never recovers" and sends people restarting hermes for- nothing (#5721).- """-- @staticmethod- def _assert_promises_retry(message: str) -> None:- assert "for this Hermes run" not in message, message- assert "will retry on a later access" in message, message- assert "when the config changes" in message, message-- @staticmethod- def _stub_client(health_result):- class _StubClient:- def __init__(self, endpoint, api_key="", account="", user="", agent=""):- self.endpoint = endpoint-- def health(self):- return health_result-- return _StubClient-- def test_local_autostart_timeout_warning(self):- self._assert_promises_retry(- openviking_plugin._runtime_openviking_timeout_message("http://127.0.0.1:1934")- )-- def test_remote_unreachable_warning(self):- provider = OpenVikingMemoryProvider()- provider._endpoint = "https://remote.example"- warnings: list[str] = []-- provider._handle_runtime_openviking_unreachable(warning_callback=warnings.append)-- assert provider._client is None- assert len(warnings) == 1- self._assert_promises_retry(warnings[0])-- def test_local_autostart_refused_warning(self, monkeypatch):- monkeypatch.setattr(- openviking_plugin,- "_start_local_openviking_server",- lambda endpoint: (- openviking_plugin._LOCAL_SERVER_FAILED,- "openviking-server was not found on PATH.",- ),- )- provider = OpenVikingMemoryProvider()- provider._endpoint = "http://127.0.0.1:1934"- warnings: list[str] = []-- provider._handle_runtime_openviking_unreachable(warning_callback=warnings.append)-- assert provider._client is None- assert len(warnings) == 1- self._assert_promises_retry(warnings[0])-- def test_still_unhealthy_after_autostart_warning(self, monkeypatch):- monkeypatch.setattr(openviking_plugin, "_VikingClient", self._stub_client(False))- monkeypatch.setattr(- openviking_plugin, "_wait_for_openviking_health", lambda endpoint, **kwargs: True- )- provider = OpenVikingMemoryProvider()- provider._endpoint = "http://127.0.0.1:1934"- warnings: list[str] = []-- provider._finish_runtime_openviking_start(warning_callback=warnings.append)-- assert provider._client is None- assert len(warnings) == 1- self._assert_promises_retry(warnings[0])-- def test_attach_failure_after_autostart_warning(self, monkeypatch):- def _explode(*args, **kwargs):- raise RuntimeError("connection reset by peer")-- monkeypatch.setattr(openviking_plugin, "_VikingClient", _explode)- monkeypatch.setattr(- openviking_plugin, "_wait_for_openviking_health", lambda endpoint, **kwargs: True- )- provider = OpenVikingMemoryProvider()- provider._endpoint = "http://127.0.0.1:1934"- warnings: list[str] = []-- provider._finish_runtime_openviking_start(warning_callback=warnings.append)-- assert provider._client is None- assert len(warnings) == 1- self._assert_promises_retry(warnings[0])-- def test_initialize_responded_unhealthy_warning(self, monkeypatch, tmp_path):- class _UnhealthyClient:- def __init__(self, endpoint, api_key="", account="", user="", agent=""):- self.endpoint = endpoint-- def health_payload(self):- return {"healthy": False}-- def health(self):- return False-- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- monkeypatch.setenv("OPENVIKING_ENDPOINT", "https://sick.example")- monkeypatch.setattr(openviking_plugin, "_VikingClient", _UnhealthyClient)- provider = OpenVikingMemoryProvider()- warnings: list[str] = []-- provider.initialize("session-1", platform="cli", warning_callback=warnings.append)-- assert provider._client is None- assert len(warnings) == 1- self._assert_promises_retry(warnings[0])-- def test_ensure_client_responded_unhealthy_warning(self, monkeypatch, caplog):- class _UnhealthyClient:- def __init__(self, endpoint, api_key="", account="", user="", agent=""):- self.endpoint = endpoint-- def health_payload(self):- return {"healthy": False}-- monkeypatch.setenv("OPENVIKING_ENDPOINT", "https://sick.example")- monkeypatch.setattr(openviking_plugin, "_VikingClient", _UnhealthyClient)- provider = OpenVikingMemoryProvider()- provider._env_refresh_enabled = True-- with caplog.at_level("WARNING", logger=openviking_plugin.__name__):- assert provider._ensure_client() is None-- self._assert_promises_retry(caplog.text)+class TestUnavailableRecovery:+ """A startup health failure must not disable OpenViking for the whole run (#5721)."""def test_startup_failure_really_does_reconnect_on_a_later_access(self, monkeypatch, tmp_path@@ -1457,7 +1292,6 @@ class TestUnavailableWarningsPromiseRetry:provider.initialize("session-1", platform="cli", warning_callback=warnings.append)assert provider._client is Noneassert len(warnings) == 1- self._assert_promises_retry(warnings[0])# A startup failure arms no cooldown, so the very next access re-probes.client = provider._ensure_client()diff --git a/tests/perf_guards/test_pattern_b_scaling.py b/tests/perf_guards/test_pattern_b_scaling.pydeleted file mode 100644index fce2d94c5a1..00000000000--- a/tests/perf_guards/test_pattern_b_scaling.py+++ /dev/null@@ -1,213 +0,0 @@-"""Pattern-B perf-regression guards: hot paths must not degrade to O(N²)/O(N·Q).--Pattern B ("rebuild everything per delta/turn") has no lintable signature —-``s += frag`` is quadratic in a hot loop and harmless elsewhere — so unlike-the Pattern-A ruff gate (ASYNC*), the only durable guard is behavioral:-pin the *scaling shape* of each known hot path and fail CI when it regresses.--Guard design rules (to stay CI-stable):-1. Prefer deterministic operation counts (SQL statements via sqlite trace- callbacks) over timing. Counts cannot flake.-2. Where only timing exists, assert a *self-normalizing ratio* — time at 4N- over time at N — never absolute wall-clock. Linear paths give ~4 (with- allocator noise), quadratic paths give ~16. Thresholds sit between the- measured-good and measured-bad values with ≥2x separation on both sides.-3. min-of-K timing samples to reject scheduler noise.--Baseline measurements (2026-08-28, macOS arm64, Python 3.12):-- streamed-text accumulation on main: 4N/N ratio ≈ 9.6 (superlinear —- ``+=`` through the attribute copies the whole reply per delta).- With PR #92166 (parts list + join): ratio ≈ 4 (linear).-- list_sessions_rich on main: ~2 writer-conn statements per listed session- (per-root compression-tip walk = N+1). With PR #95380 (batched edge- query): bounded constant.--The xfail markers are the ratchet: they document today's known-bad main and-flip to plain assertions when the fix PRs land. Remove a marker in the same-PR that merges its fix (or immediately after).-"""--from __future__ import annotations--import time-from pathlib import Path--import pytest---def _min_time(fn, *, repeat: int = 5) -> float:- """Best-of-``repeat`` wall time for ``fn()`` — rejects scheduler noise."""- best = float("inf")- for _ in range(repeat):- t0 = time.perf_counter()- fn()- best = min(best, time.perf_counter() - t0)- return best---# ----------------------------------------------------------------------------# Guard 1 — streamed assistant text accumulation must be linear (#92166).-# ------------------------------------------------------------------------------class TestStreamedTextAccumulationLinear:- """A long streamed reply must cost O(len), not O(len²), to accumulate.-- Regression shape: ``self._current_streamed_assistant_text += text`` on an- attribute copies the entire reply on every delta. A 2MB reply then does- ~2TB of memcpy across the stream — visible as CLI/desktop stream lag.- """-- N_SMALL = 4_000- N_LARGE = 16_000 # 4x — linear ratio ≈ 4, quadratic ≈ 16- DELTA = "x" * 50- # main measured 9.6; parts-list impl measured ~4. Midpoint with margin.- MAX_RATIO = 7.0-- def _accumulate(self, n: int) -> None:- from run_agent import AIAgent-- agent = AIAgent.__new__(AIAgent)- agent._current_streamed_assistant_text = ""- for _ in range(n):- agent._record_streamed_assistant_text(self.DELTA)- # The accumulated value must be faithful regardless of representation.- assert len(agent._current_streamed_assistant_text) == n * len(self.DELTA)-- @pytest.mark.xfail(- reason="known-quadratic on main until PR #92166 (streamed-text parts "- "list) merges; remove this marker when it lands",- strict=False,- )- def test_4x_input_costs_about_4x_time(self):- t_small = _min_time(lambda: self._accumulate(self.N_SMALL))- t_large = _min_time(lambda: self._accumulate(self.N_LARGE))- ratio = t_large / max(t_small, 1e-9)- assert ratio < self.MAX_RATIO, (- f"streamed-text accumulation is superlinear: 4x deltas cost "- f"{ratio:.1f}x time (linear ≈ 4, quadratic ≈ 16). The reply is "- f"being recopied per delta — see PR #92166 for the fix shape."- )---# ----------------------------------------------------------------------------# Guard 2 — list_sessions_rich must not issue O(N) per-row queries (#95380).-# ------------------------------------------------------------------------------class TestListSessionsRichQueryBound:- """Listing sessions must not walk compression chains one query at a time.-- Regression shape: ``get_compression_tip()`` per compression root = one- (or more) writer-connection statements per listed session, all under the- global write lock. Deterministic guard: count statements via sqlite's- trace callback — zero timing involved.- """-- N_CHAINS = 12- # Batched implementation needs a small constant number of statements.- # main measures ~2 per session (26 for 12 chains, 50 for 24).- MAX_STATEMENTS = 8-- @pytest.fixture()- def chain_db(self, tmp_path: Path):- from hermes_state import SessionDB-- db = SessionDB(db_path=tmp_path / "state.db")- for i in range(self.N_CHAINS):- root, child = f"root_{i}", f"child_{i}"- db.create_session(root, source="cli")- db.create_session(child, source="cli", parent_session_id=root)- db.end_session(root, end_reason="compression")- yield db- db.close()-- @staticmethod- def _count_writer_statements(db):- """Rows from ``list_sessions_rich`` plus the writer-conn statement count.-- Uses the house trace-callback idiom (``statements.append`` — see- tests/hermes_state/test_hermes_state.py) so failures can dump the captured SQL.- """- statements: list[str] = []- db._conn.set_trace_callback(statements.append)- try:- rows = db.list_sessions_rich(limit=50)- finally:- db._conn.set_trace_callback(None)- return rows, statements-- @pytest.mark.xfail(- reason="known N+1 on main until PR #95380 (batched compression-edge "- "query) merges; remove this marker when it lands",- strict=False,- )- def test_statement_count_bounded_regardless_of_session_count(self, chain_db):- rows, statements = self._count_writer_statements(chain_db)-- assert len(rows) == self.N_CHAINS- assert len(statements) <= self.MAX_STATEMENTS, (- f"list_sessions_rich issued {len(statements)} writer-connection "- f"statements for {self.N_CHAINS} sessions (bound: "- f"{self.MAX_STATEMENTS}). Per-row chain walking is back — see "- f"PR #95380 for the batched-edge fix shape. Captured SQL: "- f"{[s[:80] for s in statements[:10]]}"- )-- def test_statement_count_does_not_scale_with_sessions(self, chain_db):- """Weaker invariant that must hold TODAY on main: statements may be- O(N) but must never exceed a per-session budget of 4 — catching a- regression from N+1 to N·M (nested walks, per-hop re-queries).- """- rows, statements = self._count_writer_statements(chain_db)-- assert len(rows) == self.N_CHAINS- budget = 4 * self.N_CHAINS + 8- assert len(statements) <= budget, (- f"list_sessions_rich issued {len(statements)} statements for "- f"{self.N_CHAINS} sessions — beyond even the legacy N+1 budget "- f"({budget}). A nested per-row walk has been introduced."- )---# ----------------------------------------------------------------------------# Guard 3 — streamed tool-call fragment assembly must stay linear (#92242).-# ------------------------------------------------------------------------------class TestToolCallFragmentAssemblyLinear:- """Assembling a fragmented tool call must cost O(bytes), not O(bytes²).-- Exercises the same shape as the SSE accumulator in- ``chat_completion_helpers``: fragments arrive one at a time and are- accumulated into a per-call buffer keyed in a dict. Guards the *pattern*- (dict-field `+=` defeats CPython's in-place-growth optimization when- refcount > 1) via a pure-python model faithful to the accumulator's- structure, so the guard runs without a live provider stream.- """-- FRAG = "y" * 64- # Sized so the small case takes ≥2ms even on fast hardware: sub-ms bases- # make the ratio jitter on noisy CI runners (measured 0.185ms at 8k).- N_SMALL = 128_000- N_LARGE = 512_000- MAX_RATIO = 8.0 # linear ≈ 4; dict-field quadratic measured >> 10-- @staticmethod- def _assemble_dict_field(n_frags: int, frag: str) -> int:- """Accumulator model: buffered parts, joined once (fixed shape)."""- acc = {0: {"function": {"name": "tool", "arguments_parts": []}}}- entry = acc[0]- for _ in range(n_frags):- entry["function"]["arguments_parts"].append(frag)- return len("".join(entry["function"]["arguments_parts"]))-- def test_4x_fragments_cost_about_4x_time(self):- t_small = _min_time(lambda: self._assemble_dict_field(self.N_SMALL, self.FRAG), repeat=3)- t_large = _min_time(lambda: self._assemble_dict_field(self.N_LARGE, self.FRAG), repeat=3)- ratio = t_large / max(t_small, 1e-9)- assert ratio < self.MAX_RATIO, (- f"tool-call fragment assembly is superlinear: 4x fragments cost "- f"{ratio:.1f}x time. Fragments must be buffered in a list and "- f"joined once (PR #92242 shape), never `+=` into a dict field."- )diff --git a/tests/plugins/browser/test_browser_provider_plugins.py b/tests/plugins/browser/test_browser_provider_plugins.pyindex 7bbfafe755d..8d98f0f6372 100644--- a/tests/plugins/browser/test_browser_provider_plugins.py+++ b/tests/plugins/browser/test_browser_provider_plugins.py@@ -71,81 +71,6 @@ def _isolate_env(monkeypatch: pytest.MonkeyPatch) -> None:# ----------------------------------------------------------------------------class TestBundledPluginsRegister:- """All three bundled browser plugins discover and register correctly."""-- def test_all_three_plugins_present_in_registry(self) -> None:- _ensure_plugins_loaded()- from agent.browser_registry import list_providers-- names = sorted(p.name for p in list_providers())- assert names == ["browser-use", "browserbase", "firecrawl"]-- @pytest.mark.parametrize(- "plugin_name,expected_display",- [- ("browserbase", "Browserbase"),- ("browser-use", "Browser Use"),- ("firecrawl", "Firecrawl"),- ],- )- def test_each_plugin_has_name_and_display_name(- self, plugin_name: str, expected_display: str- ) -> None:- _ensure_plugins_loaded()- from agent.browser_registry import get_provider-- provider = get_provider(plugin_name)- assert provider is not None, f"plugin {plugin_name!r} not registered"- assert provider.name == plugin_name- assert provider.display_name == expected_display-- @pytest.mark.parametrize(- "plugin_name",- ["browserbase", "firecrawl"],- )- def test_each_plugin_has_setup_schema(self, plugin_name: str) -> None:- """``get_setup_schema()`` returns a dict the picker can consume."""- _ensure_plugins_loaded()- from agent.browser_registry import get_provider-- provider = get_provider(plugin_name)- assert provider is not None- schema = provider.get_setup_schema()- assert isinstance(schema, dict)- assert "name" in schema- assert "env_vars" in schema- # Every cloud-browser plugin carries a post-setup hook so the- # picker can auto-install its CLI dependency on selection.- assert schema.get("post_setup")-- def test_browser_use_hidden_from_picker(self) -> None:- _ensure_plugins_loaded()- from agent.browser_registry import get_provider-- provider = get_provider("browser-use")- assert provider is not None- assert provider.get_setup_schema() is None-- @pytest.mark.parametrize(- "plugin_name",- ["browserbase", "browser-use", "firecrawl"],- )- def test_each_plugin_implements_full_lifecycle(self, plugin_name: str) -> None:- """The ABC's three lifecycle methods are all overridden."""- _ensure_plugins_loaded()- from agent.browser_provider import BrowserProvider- from agent.browser_registry import get_provider-- provider = get_provider(plugin_name)- assert provider is not None- # Each method must be a real override, not the ABC's NotImplementedError- # default — we check by comparing the function reference.- assert type(provider).create_session is not BrowserProvider.create_session- assert type(provider).close_session is not BrowserProvider.close_session- assert (- type(provider).emergency_cleanup is not BrowserProvider.emergency_cleanup- )@@ -251,8 +176,14 @@ class TestPickerIntegration:_ensure_plugins_loaded()from hermes_cli.tools_config import _plugin_browser_providers+ from agent.browser_registry import list_providers+rows = _plugin_browser_providers()names = sorted(r.get("browser_provider") for r in rows)- assert names == ["browserbase", "firecrawl"]+ # Picker rows are exactly the registered plugins that expose a setup schema.+ expected = sorted(+ p.name for p in list_providers() if p.get_setup_schema() is not None+ )+ assert names and names == expecteddiff --git a/tests/plugins/dashboard_auth/test_basic_provider.py b/tests/plugins/dashboard_auth/test_basic_provider.pyindex cbb4112c051..9d16ccf1969 100644--- a/tests/plugins/dashboard_auth/test_basic_provider.py+++ b/tests/plugins/dashboard_auth/test_basic_provider.py@@ -80,8 +80,6 @@ class TestProvider:def test_protocol_compliant(self, basic):assert assert_protocol_compliance(basic.BasicAuthProvider) is None- def test_supports_password_true(self, basic):- assert basic.BasicAuthProvider.supports_password is Truedef test_login_mints_session(self, basic):p = self._make(basic)@@ -125,9 +123,6 @@ class TestProvider:s = p1.complete_password_login(username="admin", password="hunter2")assert p2.verify_session(access_token=s.access_token) is None- def test_revoke_is_silent(self, basic):- p = self._make(basic)- p.revoke_session(refresh_token="anything") # must not raisedef test_oauth_methods_raise_not_implemented(self, basic):p = self._make(basic)diff --git a/tests/plugins/dashboard_auth/test_drain_provider.py b/tests/plugins/dashboard_auth/test_drain_provider.pyindex 424ddd2af25..482b4b437d4 100644--- a/tests/plugins/dashboard_auth/test_drain_provider.py+++ b/tests/plugins/dashboard_auth/test_drain_provider.py@@ -71,9 +71,6 @@ class TestProvider:def test_protocol_compliance(self, drain):assert_protocol_compliance(drain.DrainSecretProvider)- def test_supports_token_flag(self, drain):- p = drain.DrainSecretProvider(secret=_strong_secret())- assert p.supports_token is Truedef test_is_non_interactive(self, drain):# Excluded from interactive surfaces via list_session_providers().diff --git a/tests/plugins/dashboard_auth/test_nous_provider.py b/tests/plugins/dashboard_auth/test_nous_provider.pyindex 09dbef6593b..816748f0473 100644--- a/tests/plugins/dashboard_auth/test_nous_provider.py+++ b/tests/plugins/dashboard_auth/test_nous_provider.py@@ -17,7 +17,6 @@ All HTTP is mocked: nothing in this file talks to a real Portal.from __future__ import annotationsimport base64-import hashlibimport jsonimport timeimport urllib.parse@@ -31,12 +30,9 @@ from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsaimport plugins.dashboard_auth.nous as nous_plugin-from plugins.dashboard_auth._shared import JWKS_CACHE_SECONDSfrom hermes_cli.dashboard_auth import (InvalidCodeError,- LoginStart,ProviderError,- RefreshExpiredError,Session,assert_protocol_compliance,)@@ -138,24 +134,8 @@ class TestConstruction:def test_protocol_compliance(self):assert_protocol_compliance(nous_plugin.NousDashboardAuthProvider)- def test_name_and_display(self):- p = nous_plugin.NousDashboardAuthProvider(- client_id="agent:inst1", portal_url="https://portal.example.com"- )- assert p.name == "nous"- assert p.display_name == "Nous Research"- def test_extracts_agent_instance_id(self):- p = nous_plugin.NousDashboardAuthProvider(- client_id="agent:abc-123", portal_url="https://portal.example.com"- )- assert p._agent_instance_id == "abc-123"- def test_strips_trailing_slash_from_portal_url(self):- p = nous_plugin.NousDashboardAuthProvider(- client_id="agent:x", portal_url="https://portal.example.com/"- )- assert p._portal_url == "https://portal.example.com"def test_rejects_malformed_client_id(self):with pytest.raises(ValueError, match="agent:"):@@ -276,25 +256,6 @@ class TestConfigYamlSource:)- def test_neither_source_skips_with_helpful_reason(- self, patch_config, monkeypatch- ):- """Neither env nor config.yaml set — skip with a reason that- mentions BOTH surfaces so operators don't guess wrong about- which one to populate."""- monkeypatch.delenv("HERMES_DASHBOARD_OAUTH_CLIENT_ID", raising=False)- patch_config(None)- ctx = MagicMock()- nous_plugin.register(ctx)- ctx.register_dashboard_auth_provider.assert_not_called()- # Old behaviour: skip reason mentions the env var.- assert "HERMES_DASHBOARD_OAUTH_CLIENT_ID" in nous_plugin.LAST_SKIP_REASON- # New behaviour: skip reason ALSO mentions the config.yaml path- # so the user knows it's a valid alternative.- assert "dashboard.oauth.client_id" in nous_plugin.LAST_SKIP_REASON, (- f"skip reason omits the config.yaml surface — operators "- f"won't know it exists. got: {nous_plugin.LAST_SKIP_REASON!r}"- )# ---------------------------------------------------------------------------@@ -309,11 +270,6 @@ class TestStartLogin:client_id="agent:inst1", portal_url="https://portal.example.com")- def test_returns_login_start(self, provider):- result = provider.start_login(- redirect_uri="https://hermes.fly.dev/auth/callback"- )- assert isinstance(result, LoginStart)def test_redirect_url_targets_portal_authorize(self, provider):result = provider.start_login(@@ -493,26 +449,6 @@ class TestCompleteLogin:redirect_uri="https://hermes.fly.dev/auth/callback",)- def test_captures_refresh_token_if_present_forward_compat(- self, provider, rsa_keypair- ):- """Forward-compat: contract V1 doesn't issue, but if a future Portal- does, we should preserve it in the Session for later use."""- access_token = _mint_token(rsa_keypair)- mock_resp = self._mock_post(- 200,- {- "access_token": access_token,- "token_type": "Bearer",- "refresh_token": "rt-opaque",- },- )- with patch("plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp):- session = provider.complete_login(- code="x", state="s", code_verifier="v",- redirect_uri="https://hermes.fly.dev/auth/callback",- )- assert session.refresh_token == "rt-opaque"# ---------------------------------------------------------------------------@@ -529,22 +465,6 @@ class TestVerifySession:_patched_jwks(p, rsa_keypair)return p- def test_jwks_client_sends_explicit_http_headers(self, provider):- """Constructor-contract regression: the JWKS fetch must send an- explicit Accept + User-Agent so it isn't blocked by the Portal WAF- (same fix as the self_hosted provider)."""- provider._jwks_client = None- with patch("jwt.PyJWKClient") as client_cls:- provider._get_jwks_client()- client_cls.assert_called_once_with(- provider._jwks_url,- cache_keys=True,- lifespan=JWKS_CACHE_SECONDS,- headers={- "Accept": "application/json",- "User-Agent": "HermesAgent/1.0",- },- )def test_expired_token_returns_none(self, provider, rsa_keypair):token = _mint_token(rsa_keypair, ttl_seconds=-1)@@ -660,7 +580,3 @@ class TestRefreshAndRevoke:assert kwargs["headers"]["x-nous-refresh-token"] == "rt_old_value"- def test_revoke_is_noop(self, provider):- # Must not raise; returns None implicitly.- assert provider.revoke_session(refresh_token="anything") is None- assert provider.revoke_session(refresh_token="") is Nonediff --git a/tests/plugins/dashboard_auth/test_self_hosted_provider.py b/tests/plugins/dashboard_auth/test_self_hosted_provider.pyindex a1595c86873..7b451ec17d7 100644--- a/tests/plugins/dashboard_auth/test_self_hosted_provider.py+++ b/tests/plugins/dashboard_auth/test_self_hosted_provider.py@@ -16,7 +16,6 @@ All HTTP is mocked: nothing here talks to a real IDP.from __future__ import annotationsimport base64-import hashlibimport jsonimport timeimport urllib.parse@@ -30,12 +29,9 @@ from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsaimport plugins.dashboard_auth.self_hosted as oidc_plugin-from plugins.dashboard_auth._shared import JWKS_CACHE_SECONDSfrom hermes_cli.dashboard_auth import (InvalidCodeError,- LoginStart,ProviderError,- RefreshExpiredError,Session,assert_protocol_compliance,)@@ -191,11 +187,6 @@ class TestConstruction:assert_protocol_compliance(oidc_plugin.SelfHostedOIDCProvider)- def test_strips_trailing_slash_from_issuer(self):- p = oidc_plugin.SelfHostedOIDCProvider(- issuer=_ISSUER + "/", client_id=_CLIENT_ID- )- assert p._issuer == _ISSUERdef test_requires_issuer(self):with pytest.raises(ValueError, match="issuer"):@@ -324,7 +315,6 @@ class TestDiscoveryRealRedirect:"""def _serve(self, handler_cls):- import http.serverimport socketserverimport threading@@ -443,11 +433,6 @@ class TestStartLogin:def provider(self, rsa_keypair):return _make_provider(rsa_keypair)- def test_returns_login_start(self, provider):- result = provider.start_login(- redirect_uri="https://hermes.example/auth/callback"- )- assert isinstance(result, LoginStart)def test_authorize_url_has_required_params(self, provider):@@ -724,25 +709,6 @@ class TestVerifySession:with pytest.raises(ProviderError, match="JWKS"):provider.verify_session(access_token=token)- def test_jwks_client_sends_explicit_http_headers(self):- provider = oidc_plugin.SelfHostedOIDCProvider(- issuer=_ISSUER, client_id=_CLIENT_ID- )- provider._discovery = dict(_DISCOVERY_DOC)- provider._discovery_fetched_at = time.time()-- with patch("jwt.PyJWKClient") as client_cls:- provider._get_jwks_client()-- client_cls.assert_called_once_with(- _DISCOVERY_DOC["jwks_uri"],- cache_keys=True,- lifespan=JWKS_CACHE_SECONDS,- headers={- "Accept": "application/json",- "User-Agent": "HermesAgent/1.0",- },- )# ---------------------------------------------------------------------------@@ -750,10 +716,6 @@ class TestVerifySession:# ----------------------------------------------------------------------------class TestRefreshAndRevoke:- @pytest.fixture- def provider(self, rsa_keypair):- return _make_provider(rsa_keypair)# ---------------------------------------------------------------------------diff --git a/tests/plugins/image_gen/test_deepinfra_provider.py b/tests/plugins/image_gen/test_deepinfra_provider.pyindex d088ea25531..aeaca47d532 100644--- a/tests/plugins/image_gen/test_deepinfra_provider.py+++ b/tests/plugins/image_gen/test_deepinfra_provider.py@@ -99,8 +99,3 @@ def test_generate_calls_openai_sdk_with_deepinfra_base_url(monkeypatch):assert captured["kwargs"]["model"] == "vendor/test-img"-def test_capabilities_advertise_text_to_image_only():- assert deepinfra_plugin.DeepInfraImageGenProvider().capabilities() == {- "modalities": ["text"],- "max_reference_images": 0,- }diff --git a/tests/plugins/image_gen/test_fal_provider.py b/tests/plugins/image_gen/test_fal_provider.pyindex 7f41688063c..d4cde51d40c 100644--- a/tests/plugins/image_gen/test_fal_provider.py+++ b/tests/plugins/image_gen/test_fal_provider.py@@ -23,15 +23,7 @@ from unittest.mock import MagicMockclass TestFalImageGenProviderSurface:- def test_name(self):- from plugins.image_gen.fal import FalImageGenProvider-- assert FalImageGenProvider().name == "fal"- def test_display_name(self):- from plugins.image_gen.fal import FalImageGenProvider-- assert FalImageGenProvider().display_name == "FAL.ai"def test_default_model_matches_legacy(self):from plugins.image_gen.fal import FalImageGenProvider@@ -53,23 +45,8 @@ class TestFalImageGenProviderSurface:for field in ("id", "display", "speed", "strengths", "price"):assert field in entry- def test_setup_schema_advertises_fal_key(self):- from plugins.image_gen.fal import FalImageGenProvider- schema = FalImageGenProvider().get_setup_schema()- assert schema["name"] == "FAL.ai"- assert schema["badge"] == "paid"- env_keys = {entry["key"] for entry in schema.get("env_vars", [])}- assert "FAL_KEY" in env_keys---class TestFalImageGenProviderAvailability:- def test_is_available_when_legacy_check_passes(self, monkeypatch):- import tools.image_generation_tool as image_tool- from plugins.image_gen.fal import FalImageGenProvider- monkeypatch.setattr(image_tool, "check_fal_api_key", lambda: True)- assert FalImageGenProvider().is_available() is True# ---------------------------------------------------------------------------diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.pyindex 32c7ae45750..a6630e1a537 100644--- a/tests/plugins/image_gen/test_krea_provider.py+++ b/tests/plugins/image_gen/test_krea_provider.py@@ -58,15 +58,7 @@ def _poll_response(body: dict):class TestKreaImageGenProvider:- def test_name(self):- from plugins.image_gen.krea import KreaImageGenProvider-- assert KreaImageGenProvider().name == "krea"-- def test_display_name(self):- from plugins.image_gen.krea import KreaImageGenProvider- assert KreaImageGenProvider().display_name == "Krea"def test_is_available_with_key(self, monkeypatch):monkeypatch.setenv("KREA_API_KEY", "sk-test")@@ -75,34 +67,8 @@ class TestKreaImageGenProvider:assert KreaImageGenProvider().is_available() is True- def test_list_models(self):- from plugins.image_gen.krea import KreaImageGenProvider-- models = KreaImageGenProvider().list_models()- ids = {m["id"] for m in models}- assert {"krea-2-medium", "krea-2-large"} <= ids- # Each entry carries the picker fields the registry expects.- for m in models:- assert m["display"]- assert m["speed"]- assert m["strengths"]- assert m["price"]-- def test_default_model_is_medium(self):- from plugins.image_gen.krea import KreaImageGenProvider-- assert KreaImageGenProvider().default_model() == "krea-2-medium"- def test_get_setup_schema(self):- from plugins.image_gen.krea import KreaImageGenProvider- schema = KreaImageGenProvider().get_setup_schema()- assert schema["name"] == "Krea"- assert schema["badge"] == "paid"- env_vars = schema["env_vars"]- assert len(env_vars) == 1- assert env_vars[0]["key"] == "KREA_API_KEY"- assert "krea.ai" in env_vars[0]["url"]# ---------------------------------------------------------------------------@@ -121,10 +87,6 @@ class TestModelResolution:assert meta["path"] == "large"- def test_creativity_default(self):- from plugins.image_gen.krea import _resolve_creativity-- assert _resolve_creativity(None) == "medium"# ---------------------------------------------------------------------------@@ -667,16 +629,6 @@ class TestUpscalePass:assert result["image"].endswith("native.png")assert mock_post.call_count == 1 # only the generation submit- def test_large_skips_upscale_by_default(self):- """krea-2-large: no automatic Enhance pass either."""- result, mock_post, _ = self._run_generate(- upscale=None, enhance_job=None, model="krea-2-large",- )-- assert result["success"] is True- assert result["upscaled"] is False- assert result["image"].endswith("native.png")- assert mock_post.call_count == 1 # only the generation submitdef test_explicit_false_disables_default(self):"""Explicit upscale=False matches the off default."""diff --git a/tests/plugins/image_gen/test_meta_ai_provider.py b/tests/plugins/image_gen/test_meta_ai_provider.pyindex 3ff129a539a..4fc87c8863e 100644--- a/tests/plugins/image_gen/test_meta_ai_provider.py+++ b/tests/plugins/image_gen/test_meta_ai_provider.py@@ -65,18 +65,9 @@ def _patched_openai(fake_client: MagicMock):class TestMetadata:- def test_name(self, provider):- assert provider.name == "meta-ai"- def test_display_name(self, provider):- assert provider.display_name == "Meta Model API"- def test_default_model(self, provider):- assert provider.default_model() == "muse-image-1.0"- def test_list_models(self, provider):- ids = [m["id"] for m in provider.list_models()]- assert ids == ["muse-image-1.0"]def test_catalog_entries_have_display_speed_strengths_price(self, provider):for entry in provider.list_models():@@ -85,10 +76,6 @@ class TestMetadata:assert entry["strengths"]assert entry["price"]- def test_text_only_capabilities(self, provider):- caps = provider.capabilities()- assert caps["modalities"] == ["text"]- assert caps["max_reference_images"] == 0# ── Availability ────────────────────────────────────────────────────────────@@ -117,8 +104,6 @@ class TestResolution:monkeypatch.setenv("MODEL_API_KEY", "first")assert meta_plugin._resolve_api_key() == "first"- def test_default_base_url(self):- assert meta_plugin._resolve_base_url() == "https://api.meta.ai/v1"def test_base_url_override(self, monkeypatch):monkeypatch.setenv("META_BASE_URL", "https://proxy.internal/v1")@@ -129,15 +114,12 @@ class TestResolution:class TestModelResolution:- def test_default(self):- model_id, _meta = meta_plugin._resolve_model()- assert model_id == "muse-image-1.0"def test_env_var_override_ignores_unknown(self, monkeypatch):monkeypatch.setenv("META_IMAGE_MODEL", "not-a-real-model")model_id, _meta = meta_plugin._resolve_model()# Unknown id is ignored; falls through to the default.- assert model_id == "muse-image-1.0"+ assert model_id == meta_plugin.DEFAULT_MODELdef test_caller_model_kwarg_wins(self, monkeypatch):# The dispatcher forwards top-level image_gen.model as the `model`@@ -153,7 +135,7 @@ class TestModelResolution:def test_caller_model_unknown_falls_through(self):model_id, _meta = meta_plugin._resolve_model("not-a-real-model")- assert model_id == "muse-image-1.0"+ assert model_id == meta_plugin.DEFAULT_MODEL# ── Generate ──────────────────────────────────────────────────────────────────@@ -175,8 +157,6 @@ class TestGenerate:fake_client.images.generate.call_args.kwargs["model"] == "muse-image-test")- def test_badge_is_standard_paid(self, provider):- assert provider.get_setup_schema()["badge"] == "paid"def test_empty_prompt_rejected(self, provider):result = provider.generate("", aspect_ratio="square")diff --git a/tests/plugins/image_gen/test_openai_codex_provider.py b/tests/plugins/image_gen/test_openai_codex_provider.pyindex 962165c1a78..31599c41081 100644--- a/tests/plugins/image_gen/test_openai_codex_provider.py+++ b/tests/plugins/image_gen/test_openai_codex_provider.py@@ -82,18 +82,9 @@ def codex_backend(monkeypatch):class TestMetadata:- def test_name(self, provider):- assert provider.name == "openai-codex"- def test_display_name(self, provider):- assert provider.display_name == "OpenAI (Codex auth)"- def test_default_model(self, provider):- assert provider.default_model() == "gpt-image-2-medium"- def test_list_models_three_tiers(self, provider):- ids = [m["id"] for m in provider.list_models()]- assert ids == ["gpt-image-2-low", "gpt-image-2-medium", "gpt-image-2-high"]def test_setup_schema_has_no_required_env_vars(self, provider):"""#102144: the keyless row must declare the shared Codex OAuth bootstrap hook (otherwise setup@@ -195,10 +186,6 @@ class TestGenerate:body = json.loads(codex_backend["requests"][0].content)assert body["images"] == [{"image_url": "data:image/png;base64," + _b64_png()}]- def test_capabilities_advertise_image_inputs(self, provider):- caps = provider.capabilities()- assert caps["modalities"] == ["text", "image"]- assert caps["max_reference_images"] == 16def test_rejects_non_image_local_source(self, provider, codex_backend, tmp_path):text_path = tmp_path / "not-image.txt"diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.pyindex 90327d2b66d..783c086b8f7 100644--- a/tests/plugins/image_gen/test_openai_provider.py+++ b/tests/plugins/image_gen/test_openai_provider.py@@ -51,22 +51,13 @@ def _patched_openai(fake_client: MagicMock):class TestMetadata:- def test_name(self, provider):- assert provider.name == "openai"- def test_default_model(self, provider):- assert provider.default_model() == "gpt-image-2-medium"def test_picker_matches_resolvable_catalog(self, provider):ids = [m["id"] for m in provider.list_models()]assert set(ids) == set(provider.models)assert provider.default_model() in ids- def test_catalog_entries_have_display_speed_strengths(self, provider):- for entry in provider.list_models():- assert entry["display"].startswith("GPT Image 2")- assert entry["speed"]- assert entry["strengths"]# ── Availability ────────────────────────────────────────────────────────────diff --git a/tests/plugins/image_gen/test_openrouter_compat_provider.py b/tests/plugins/image_gen/test_openrouter_compat_provider.pyindex 09ad4ffb359..15a572898e1 100644--- a/tests/plugins/image_gen/test_openrouter_compat_provider.py+++ b/tests/plugins/image_gen/test_openrouter_compat_provider.py@@ -3,7 +3,6 @@from __future__ import annotations-import base64from pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -64,18 +63,7 @@ def _openrouter():class TestProviderClass:- def test_names(self):- from plugins.image_gen.openrouter import _build_providers-- names = {p.name for p in _build_providers()}- assert names == {"openrouter", "nous"}- def test_display_names(self):- from plugins.image_gen.openrouter import _build_providers-- by_name = {p.name: p for p in _build_providers()}- assert by_name["openrouter"].display_name == "OpenRouter"- assert by_name["nous"].display_name == "Nous Portal"def test_capabilities_support_image_input(self):caps = _openrouter().capabilities()@@ -87,13 +75,6 @@ class TestProviderClass:assert _openrouter().is_available() is True- def test_default_model(self):- from plugins.image_gen.openrouter import DEFAULT_MODEL-- with patch("plugins.image_gen.openrouter._load_image_gen_config", return_value={}):- assert _openrouter().default_model() == DEFAULT_MODEL- # Default must be an image-output model id (provider/model form).- assert "/" in DEFAULT_MODEL and "image" in DEFAULT_MODELdef test_default_model_ignores_runtime_overrides(self, monkeypatch):"""Catalog defaults must not inherit another provider's saved model."""@@ -809,14 +790,9 @@ class TestImageApiSurface:by_name = {p.name: p for p in _build_providers()}openrouter_ids = {m["id"] for m in by_name["openrouter"].list_models()}nous_ids = {m["id"] for m in by_name["nous"].list_models()}- assert "openai/gpt-image-2" in openrouter_idsassert set(_IMAGE_API_MODELS) <= openrouter_idsassert not (set(_IMAGE_API_MODELS) & nous_ids)- def test_default_model_is_unchanged_by_the_new_surface(self):- from plugins.image_gen.openrouter import DEFAULT_MODEL-- assert _openrouter_image_api().default_model() == DEFAULT_MODELclass TestRegistration:diff --git a/tests/plugins/image_gen/test_xai_provider.py b/tests/plugins/image_gen/test_xai_provider.pyindex d7a5e9bd32f..a86539b2eb8 100644--- a/tests/plugins/image_gen/test_xai_provider.py+++ b/tests/plugins/image_gen/test_xai_provider.py@@ -3,8 +3,6 @@from __future__ import annotations-import json-from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest@@ -54,17 +52,7 @@ def _no_live_catalog(monkeypatch):class TestXAIImageGenProvider:- def test_name(self):- from plugins.image_gen.xai import XAIImageGenProvider-- provider = XAIImageGenProvider()- assert provider.name == "xai"- def test_display_name(self):- from plugins.image_gen.xai import XAIImageGenProvider-- provider = XAIImageGenProvider()- assert provider.display_name == "xAI (Grok)"def test_is_available_with_key(self, monkeypatch):monkeypatch.setenv("XAI_API_KEY", "sk-xxx")@@ -74,39 +62,19 @@ class TestXAIImageGenProvider:assert provider.is_available() is True- def test_list_models(self):- from plugins.image_gen.xai import XAIImageGenProvider-- provider = XAIImageGenProvider()- models = provider.list_models()- assert len(models) >= 1- assert models[0]["id"] == "grok-imagine-image"- def test_default_model(self):- from plugins.image_gen.xai import XAIImageGenProvider-- provider = XAIImageGenProvider()- assert provider.default_model() == "grok-imagine-image"def test_get_setup_schema(self):from plugins.image_gen.xai import XAIImageGenProviderprovider = XAIImageGenProvider()schema = provider.get_setup_schema()- assert schema["name"] == "xAI Grok Imagine (image)"- assert schema["badge"] == "paid"# Auth resolution is delegated to the shared "xai_grok" post_setup# hook so the picker doesn't blindly prompt for XAI_API_KEY when the# user is already signed in via xAI Grok OAuth.assert schema["env_vars"] == []assert schema["post_setup"] == "xai_grok"- def test_capabilities_expose_total_source_image_limit(self):- from plugins.image_gen.xai import XAIImageGenProvider-- caps = XAIImageGenProvider().capabilities()- assert caps["max_reference_images"] == 2- assert caps["max_source_images"] == 3# ---------------------------------------------------------------------------@@ -117,12 +85,6 @@ class TestXAIImageGenProvider:class TestConfig:- def test_custom_model(self, monkeypatch):- monkeypatch.setenv("XAI_IMAGE_MODEL", "grok-imagine-image")- from plugins.image_gen.xai import _resolve_model-- model_id, _ = _resolve_model()- assert model_id == "grok-imagine-image"def test_caller_model_overrides_env(self, monkeypatch):"""caller_model (from image_gen.model config key) must take priority@@ -168,12 +130,6 @@ class TestConfig:class TestLiveCatalog:- def test_static_catalog_includes_image_2_0(self):- """Curated table carries the 2.0 model even offline."""- from plugins.image_gen.xai import XAIImageGenProvider-- ids = [m["id"] for m in XAIImageGenProvider().list_models()]- assert "grok-imagine-image-2.0" in idsdef test_unknown_live_model_appears_in_catalog(self, monkeypatch):"""A model xAI ships tomorrow shows up without a code change."""@@ -189,7 +145,7 @@ class TestLiveCatalog:catalog = xai_mod._catalog()assert "grok-imagine-image-3.0" in catalog# Curated metadata survives the merge for known models.- assert catalog["grok-imagine-image"]["display"] == "Grok Imagine Image"+ assert catalog["grok-imagine-image"]["display"] == xai_mod._MODELS["grok-imagine-image"]["display"]# And the new model is selectable end to end.monkeypatch.setenv("XAI_IMAGE_MODEL", "grok-imagine-image-3.0")model_id, _ = xai_mod._resolve_model()@@ -214,12 +170,6 @@ class TestLiveCatalog:monkeypatch.setenv("XAI_IMAGE_MODEL", "grok-imagine-image-2.0")assert xai_mod._resolve_edit_model() == "grok-imagine-image-2.0"- def test_edit_model_defaults_to_quality(self, monkeypatch):- import plugins.image_gen.xai as xai_mod-- monkeypatch.setattr(xai_mod, "_LIVE_CACHE", None)- monkeypatch.delenv("XAI_IMAGE_MODEL", raising=False)- assert xai_mod._resolve_edit_model() == "grok-imagine-image-quality"def test_edit_model_honors_caller_kwarg(self, monkeypatch):"""The dispatched model kwarg reaches the edit path too."""diff --git a/tests/plugins/memory/test_config_schema.py b/tests/plugins/memory/test_config_schema.pyindex db4d999710a..82dee0fb8dc 100644--- a/tests/plugins/memory/test_config_schema.py+++ b/tests/plugins/memory/test_config_schema.py@@ -8,13 +8,8 @@ def test_unknown_provider_is_none():assert get_provider_config_schema("builtin") is None-def test_plugin_without_schema_is_none():- # mem0 is a real plugin dir that declares no config_schema.py.- assert get_provider_config_schema("mem0") is None-def test_schemas_are_cached_per_provider():- assert get_provider_config_schema("honcho") is get_provider_config_schema("honcho")def test_cache_keys_on_schema_path_not_name(monkeypatch, tmp_path):diff --git a/tests/plugins/memory/test_holographic_retrieval.py b/tests/plugins/memory/test_holographic_retrieval.pyindex ce8e3f7bae6..cb8fa5c0dcc 100644--- a/tests/plugins/memory/test_holographic_retrieval.py+++ b/tests/plugins/memory/test_holographic_retrieval.py@@ -107,39 +107,6 @@ def test_prefetch_recovers_prose_query(retriever_with_facts):from plugins.memory.holographic import holographic as hrr-def hoisted_retriever(tmp_path):- """30 facts with HRR vectors, default dim (smaller dims trip an- inhomogeneous-shape edge in the fact encoder).-- NOTE: a real tmp_path db, NOT ":memory:" — MemoryStore resolves the- path and shares one process-wide connection per file, so ":memory:"- becomes a literal ./:memory: file that leaks state across runs (and- the NULL-vector test below would permanently corrupt it)."""- store = MemoryStore(str(tmp_path / "hoist_store.db"))- for i in range(30):- store.add_fact(- content=f"deploy target {i} setting alpha beta gamma option {i % 7}",- category="fact" if i % 2 else "preference",- tags=f"entity_{i % 5} deploy",- )- retriever = FactRetriever(store=store)- yield retriever- store.close()---def _counting_spy(monkeypatch, attr):- calls = []- real = getattr(hrr, attr)-- def wrapper(*args, **kwargs):- calls.append(args)- return real(*args, **kwargs)-- monkeypatch.setattr(hrr, attr, wrapper)- return calls--def test_encode_functions_are_deterministic():"""Soundness premise of the hoists: same input -> identical vector."""import numpy as np@@ -150,91 +117,11 @@ def test_encode_functions_are_deterministic():hrr.encode_atom("__hrr_role_content__", 1024))-def test_search_encodes_query_vector_once(hoisted_retriever, monkeypatch):- calls = _counting_spy(monkeypatch, "encode_text")- results = hoisted_retriever.search("deploy target setting")- assert results # the HRR path actually engaged- assert len(calls) == 1, (- f"query vector encoded {len(calls)}x in one search() — "- "loop-invariant hoist regressed"- )-def test_search_results_bit_identical_to_unhoisted(hoisted_retriever):- """Parity: hoisted search() must produce the exact pre-fix results.- Replicates the pre-fix loop (query vector encoded per candidate) as the- reference and compares full scored output for exact equality.- """- r = hoisted_retriever- query = "deploy target setting"- new_results = r.search(query)-- # --- pre-fix reference ---- candidates = r._fts_candidates(query, None, 0.3, 10 * 3)- query_tokens = r._tokenize(query)- scored = []- for fact in candidates:- content_tokens = r._tokenize(fact["content"])- tag_tokens = r._tokenize(fact.get("tags", ""))- all_tokens = content_tokens | tag_tokens- jaccard = r._jaccard_similarity(query_tokens, all_tokens)- fts_score = fact.get("fts_rank", 0.0)- if r.hrr_weight > 0 and fact.get("hrr_vector"):- fact_vec = hrr.bytes_to_phases(fact["hrr_vector"])- query_vec = hrr.encode_text(query, r.hrr_dim) # per-candidate- hrr_sim = (hrr.similarity(query_vec, fact_vec) + 1.0) / 2.0- else:- hrr_sim = 0.5- relevance = (r.fts_weight * fts_score- + r.jaccard_weight * jaccard- + r.hrr_weight * hrr_sim)- fact["score"] = relevance * fact["trust_score"]- scored.append(fact)- scored.sort(key=lambda x: x["score"], reverse=True)- old_results = scored[:10]- for fact in old_results:- fact.pop("hrr_vector", None)-- assert new_results == old_results---def test_related_encodes_role_atoms_once(hoisted_retriever, monkeypatch):- calls = _counting_spy(monkeypatch, "encode_atom")- results = hoisted_retriever.related("entity_1")- assert results- role_calls = [a for a in calls- if a and str(a[0]).startswith("__hrr_role_")]- assert len(role_calls) == 2, (- f"role atoms encoded {len(role_calls)}x in one related() — "- "expected exactly 2 (role_entity + role_content, hoisted)"- )-def test_probe_encodes_role_atom_once(hoisted_retriever, monkeypatch):- calls = _counting_spy(monkeypatch, "encode_atom")- results = hoisted_retriever.probe("entity_1")- assert results- role_content_calls = [a for a in calls- if a and a[0] == "__hrr_role_content__"]- assert len(role_content_calls) == 1, (- f"role_content atom encoded {len(role_content_calls)}x in one "- "probe() — loop-invariant hoist regressed"- )-def test_search_without_vectors_never_encodes(hoisted_retriever, monkeypatch):- """Migrated DBs can have FTS candidates with NULL hrr_vector- (MemoryStore._init_db adds the column without backfilling existing- facts). The lazy hoist must not encode a query vector nothing will- use — pre-fix main encoded only beneath fact.get('hrr_vector')."""- store = hoisted_retriever.store- store._conn.execute("UPDATE facts SET hrr_vector = NULL")- store._conn.commit()- calls = _counting_spy(monkeypatch, "encode_text")- results = hoisted_retriever.search("deploy target setting")- assert results # candidates exist; neutral hrr_sim=0.5 path- assert calls == [], (- f"encode_text called {len(calls)}x with zero vector candidates — "- "lazy hoist regressed to eager"- )+diff --git a/tests/plugins/memory/test_holographic_store.py b/tests/plugins/memory/test_holographic_store.pyindex 9fa17728410..d65928dd79f 100644--- a/tests/plugins/memory/test_holographic_store.py+++ b/tests/plugins/memory/test_holographic_store.py@@ -97,15 +97,6 @@ class TestSharedConnection:a.close()b.close()- def test_schema_initialised_once_per_connection(self, db_path):- a = MemoryStore(db_path)- b = MemoryStore(db_path) # must not re-run schema init / WAL probe- try:- assert MemoryStore._shared[str(a.db_path)]["ready"] is True- b.add_fact("schema still works")- finally:- a.close()- b.close()class TestCloseSemantics:@@ -207,21 +198,4 @@ class TestConcurrency:sibling.close()-class TestProviderShutdown:- """The provider's shutdown() must release its shared connection, not just- drop the reference. Leaving finalization to GC keeps the connection (and- its write lock) alive on a long-running gateway, which is exactly the- "database is locked" contention the shared-connection registry removes."""-- def test_shutdown_releases_shared_connection(self, db_path):- from plugins.memory.holographic import HolographicMemoryProvider-- provider = HolographicMemoryProvider(config={"db_path": str(db_path)})- provider.initialize("session-shutdown")- assert MemoryStore._shared[str(db_path)]["refs"] == 1-- provider.shutdown()-- assert provider._store is None- assert MemoryStore._shared == {}diff --git a/tests/plugins/memory/test_honcho_config_schema.py b/tests/plugins/memory/test_honcho_config_schema.pyindex a8434f088bf..9cb4d7aa266 100644--- a/tests/plugins/memory/test_honcho_config_schema.py+++ b/tests/plugins/memory/test_honcho_config_schema.py@@ -1,11 +1,7 @@"""Tests for Honcho's declared config surface."""from plugins.memory.config_schema import (- KIND_BOOL,- KIND_JSON,- KIND_NUMBER,KIND_SECRET,- KIND_SELECT,STORAGE_HONCHO_HOST_BLOCK,get_provider_config_schema,)@@ -34,41 +30,10 @@ def test_honcho_is_declared():assert INLINE_KEYS <= set(keys)-def test_inline_fields_are_the_curated_subset():- provider = get_provider_config_schema("honcho")- assert provider is not None-- assert {field.key for field in provider.inline_fields()} == INLINE_KEYS- # The modal-only fields are a non-empty remainder.- non_inline = {f.key for f in provider.fields} - INLINE_KEYS- assert {"writeFrequency", "recallMode", "userPeerAliases"} <= non_inline---def test_declares_the_new_field_kinds():- provider = get_provider_config_schema("honcho")- assert provider is not None-- by_key = {f.key: f for f in provider.fields}- assert by_key["saveMessages"].kind == KIND_BOOL- assert by_key["a2aSessions"].kind == KIND_BOOL- assert by_key["a2aSessions"].default == "true"- assert by_key["dialecticMaxChars"].kind == KIND_NUMBER- assert by_key["userPeerAliases"].kind == KIND_JSON- assert by_key["recallMode"].allowed_values() == {"hybrid", "context", "tools"}- assert by_key["observationMode"].allowed_values() == {"directional", "unified"}-def test_selects_constrain_their_values():- provider = get_provider_config_schema("honcho")- assert provider is not None- environment = next(f for f in provider.fields if f.key == "environment")- assert environment.kind == KIND_SELECT- # Honcho SDK only accepts local/production; "demo" is not a valid environment.- assert environment.allowed_values() == {"production", "local"}- strategy = next(f for f in provider.fields if f.key == "sessionStrategy")- assert strategy.allowed_values() == {"per-directory", "per-repo", "per-session", "global"}def test_api_key_is_a_secret_bound_to_env():diff --git a/tests/plugins/memory/test_mem0_backend.py b/tests/plugins/memory/test_mem0_backend.pyindex e30903672ed..77cc45603d0 100644--- a/tests/plugins/memory/test_mem0_backend.py+++ b/tests/plugins/memory/test_mem0_backend.py@@ -12,7 +12,6 @@ from types import SimpleNamespaceimport pytestfrom plugins.memory.mem0._backend import (- Mem0Backend,PlatformBackend,OSSBackend,SelfHostedBackend,@@ -53,13 +52,6 @@ class TestPlatformBackend:backend._client = clientreturn backend, client- def test_search_forwards_params(self):- backend, client = self._make()- result = backend.search("test query", filters={"user_id": "u1"}, top_k=5)- assert client.calls[0][0] == "search"- assert client.calls[0][1] == "test query"- assert client.calls[0][2]["filters"] == {"user_id": "u1"}- assert client.calls[0][2]["top_k"] == 5def test_add_forwards_kwargs(self):@@ -74,15 +66,7 @@ class TestPlatformBackend:assert "metadata" not in call[2]- def test_update_forwards(self):- backend, client = self._make()- backend.update("m1", "new text")- assert client.calls[0][1] == {"memory_id": "m1", "text": "new text"}- def test_delete_forwards(self):- backend, client = self._make()- backend.delete("m1")- assert client.calls[0][1] == {"memory_id": "m1"}class FakeOSSMemory:diff --git a/tests/plugins/memory/test_mem0_setup.py b/tests/plugins/memory/test_mem0_setup.pyindex d265c3bbbe0..4174d539791 100644--- a/tests/plugins/memory/test_mem0_setup.py+++ b/tests/plugins/memory/test_mem0_setup.py@@ -3,9 +3,6 @@import jsonimport sysimport types-import pytest-from pathlib import Path-from unittest.mock import patch, MagicMockfrom plugins.memory.mem0._setup import (parse_flags,@@ -14,8 +11,6 @@ from plugins.memory.mem0._setup import (_prompt_api_key,post_setup,_check_qdrant_path,- _check_ollama,- _check_pgvector,)@@ -41,35 +36,10 @@ def _inject_fake_hermes_cli(monkeypatch):return fake_config_mod-class TestParseFlags:-- def test_mode_platform(self):- flags = parse_flags(["--mode", "platform", "--api-key", "sk-test"])- assert flags["mode"] == "platform"- assert flags["api_key"] == "sk-test"--- def test_no_flags_returns_empty_mode(self):- flags = parse_flags([])- assert flags["mode"] == ""-- def test_oss_vector_path_flag(self):- flags = parse_flags(["--mode", "oss", "--oss-vector-path", "/data/qdrant"])- assert flags["oss_vector_path"] == "/data/qdrant"class TestBuildOSSConfig:- def test_openai_defaults(self):- flags = parse_flags(["--mode", "oss", "--oss-llm-key", "sk-oai"])- oss, env_writes = build_oss_config(flags)- assert oss["llm"]["provider"] == "openai"- assert oss["llm"]["config"]["model"] == "gpt-5-mini"- assert oss["llm"]["config"]["is_reasoning_model"] is True- assert oss["embedder"]["provider"] == "openai"- assert oss["embedder"]["config"]["model"] == "text-embedding-3-small"- assert oss["vector_store"]["provider"] == "qdrant"- assert env_writes["OPENAI_API_KEY"] == "sk-oai"def test_explicit_gpt_5_mini_is_reasoning_model(self):@@ -239,11 +209,6 @@ class TestPostSetup:assert mem0_json["user_id"] == "hermes-user"-class TestDryRun:-- def test_dry_run_flag_parsed(self):- flags = parse_flags(["--mode", "oss", "--oss-llm-key", "sk-oai", "--dry-run"])- assert flags["dry_run"] is Trueclass TestConnectivityChecks:diff --git a/tests/plugins/memory/test_mem0_v3.py b/tests/plugins/memory/test_mem0_v3.pyindex 9babf5b3f23..c895b15a94e 100644--- a/tests/plugins/memory/test_mem0_v3.py+++ b/tests/plugins/memory/test_mem0_v3.py@@ -2,7 +2,6 @@import jsonimport threading-import timeimport pytestfrom agent import secret_scope@@ -54,11 +53,6 @@ class TestMem0V3Tools:provider._backend = backendreturn provider- def test_search_returns_ids(self, monkeypatch):- backend = FakeBackend(search_results=[{"id": "mem-1", "memory": "foo", "score": 0.9}])- provider = self._make_provider(monkeypatch, backend)- result = json.loads(provider.handle_tool_call("mem0_search", {"query": "test"}))- assert result["results"][0]["id"] == "mem-1"def test_add_uses_content_param(self, monkeypatch):@@ -73,13 +67,6 @@ class TestMem0V3Tools:assert "event_id" in result- def test_old_tool_names_return_unknown(self, monkeypatch):- backend = FakeBackend()- provider = self._make_provider(monkeypatch, backend)- result = json.loads(provider.handle_tool_call("mem0_profile", {}))- assert "error" in result- result = json.loads(provider.handle_tool_call("mem0_conclude", {}))- assert "error" in resultclass TestMem0UpdateDelete:@@ -114,17 +101,6 @@ class TestMem0UpdateDelete:assert result["result"] == "Memory deleted."-class TestMem0ErrorHandling:-- def _make_provider(self, monkeypatch, backend):- provider = Mem0MemoryProvider()- provider.initialize("test-session")- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._backend = backend- return provider--class TestMem0V3Internal:def _make_provider(self, monkeypatch, backend):@@ -312,25 +288,6 @@ class TestMem0Prefetch:assert backend.captured == []-class TestMem0V3Config:-- def test_tool_schemas_four_tools(self):- provider = Mem0MemoryProvider()- schemas = provider.get_tool_schemas()- names = [s["name"] for s in schemas]- assert names == ["mem0_search", "mem0_add", "mem0_update", "mem0_delete"]-- def test_system_prompt_new_tool_names(self):- provider = Mem0MemoryProvider()- provider._user_id = "test"- block = provider.system_prompt_block()- assert "mem0_search" in block- assert "mem0_add" in block- assert "mem0_update" in block- assert "mem0_delete" in block- assert "mem0_list" not in block- assert "mem0_profile" not in block- assert "mem0_conclude" not in blockclass TestMem0ModeSwitch:@@ -409,12 +366,6 @@ class TestMem0ModeSwitch:assert mem0_plugin._load_config()["api_key"] == "file-key"- def test_default_mode_is_platform(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.setenv("MEM0_API_KEY", "test-key")- provider = Mem0MemoryProvider()- provider.initialize("test")- assert provider._mode == "platform"def test_missing_mode_key_defaults_platform(self, monkeypatch, tmp_path):"""Backward compat: old mem0.json without mode key works."""@@ -481,20 +432,6 @@ class TestMem0UserIdResolution:assert provider._user_id == "123456789"-class TestMem0WriteMetadata:- """Writes carry metadata.channel so per-channel filtered views are possible- without coupling identity to the channel.- """-- def _make_provider(self, channel: str = "cli"):- provider = Mem0MemoryProvider()- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._channel = channel- provider._backend = FakeBackend()- return provider--class _SentinelBackend:def __init__(self, *args):self.args = argsdiff --git a/tests/plugins/memory/test_memory_lazy_install.py b/tests/plugins/memory/test_memory_lazy_install.pyindex 52dcbbf057b..49d12ab540f 100644--- a/tests/plugins/memory/test_memory_lazy_install.py+++ b/tests/plugins/memory/test_memory_lazy_install.py@@ -44,34 +44,6 @@ MEMORY_FEATURES = ("memory.supermemory", "memory.mem0")# ----------------------------------------------------------------------------class TestAllowlistEntries:- @pytest.mark.parametrize("feature", MEMORY_FEATURES)- def test_feature_is_allowlisted(self, feature):- # Without an allowlist entry, ensure() raises FeatureUnavailable with- # "not in LAZY_DEPS" — which is exactly why the SDK never installed on- # a hosted instance before this fix.- assert feature in ld.LAZY_DEPS, (- f"{feature!r} missing from LAZY_DEPS — its SDK can never "- f"lazy-install on a sealed Docker venv."- )--- def test_supermemory_spec_package(self):- specs = ld.LAZY_DEPS["memory.supermemory"]- assert any(ld._pkg_name_from_spec(s) == "supermemory" for s in specs)-- def test_mem0_spec_package(self):- # mem0's pip package is ``mem0ai`` (imports as ``mem0``).- specs = ld.LAZY_DEPS["memory.mem0"]- assert any(ld._pkg_name_from_spec(s) == "mem0ai" for s in specs)-- @pytest.mark.parametrize("feature", MEMORY_FEATURES)- def test_unknown_feature_would_raise_without_entry(self, feature, monkeypatch):- # Demonstrate the failure mode the allowlist entry prevents: a feature- # NOT in LAZY_DEPS raises rather than installing.- monkeypatch.setattr(ld, "_allow_lazy_installs", lambda: True)- with pytest.raises(ld.FeatureUnavailable, match="not in LAZY_DEPS"):- ld.ensure(feature + ".typo", prompt=False)# ---------------------------------------------------------------------------diff --git a/tests/plugins/memory/test_openviking_provider.py b/tests/plugins/memory/test_openviking_provider.pyindex 5f986592785..64d685b3751 100644--- a/tests/plugins/memory/test_openviking_provider.py+++ b/tests/plugins/memory/test_openviking_provider.py@@ -71,37 +71,6 @@ def _allow_setup_validation(monkeypatch, *, root_access: bool = False):)-def test_openviking_provider_config_loader_uses_readonly_config(monkeypatch):- import hermes_cli.config as config_mod-- calls = []- backing_config = {- "memory": {- "openviking": {- "endpoint": "http://127.0.0.1:19472",- "api_key": "test-key",- }- }- }-- def load_config_readonly():- calls.append("readonly")- return backing_config-- def load_config():- raise AssertionError("OpenViking config loader should use readonly config")-- monkeypatch.setattr(config_mod, "load_config_readonly", load_config_readonly)- monkeypatch.setattr(config_mod, "load_config", load_config)-- config = openviking_module._load_hermes_openviking_config()-- assert calls == ["readonly"]- assert config == {- "endpoint": "http://127.0.0.1:19472",- "api_key": "test-key",- }- assert config is not backing_config["memory"]["openviking"]def test_connection_settings_read_dashboard_config_file(tmp_path, monkeypatch):@@ -320,47 +289,6 @@ def test_post_setup_existing_profile_picker_validates_and_links_saved_profile(assert json.loads(saved_path.read_text(encoding="utf-8")) == saved_values-def test_local_setup_recommends_user_api_key_before_unauthenticated_mode(monkeypatch):- monkeypatch.setattr(- openviking_module,- "_validate_openviking_reachability",- lambda endpoint: (True, ""),- )- monkeypatch.setattr(- openviking_module,- "_validate_openviking_setup_values",- lambda values, *, require_api_key=False: (True, "", "user"),- )- credential_menu = {}-- def select(title, options, *, default=0, cancel_returns=None):- assert title == " OpenViking credential"- credential_menu["options"] = options- credential_menu["default"] = default- return 0-- def prompt(label, default=None, secret=False):- if label == "OpenViking server URL":- return default- if label == "OpenViking user API key":- assert secret is True- return "user-key"- raise AssertionError(f"Unexpected prompt: {label}")-- values = openviking_module._setup._prompt_manual_connection_values(- prompt,- select,- -1,- )-- assert [label for label, _description in credential_menu["options"]] == [- "User API key",- "Root API key",- "No API key",- ]- assert credential_menu["default"] == 0- assert values["api_key"] == "user-key"- assert values["api_key_type"] == "user"def test_start_local_openviking_server_uses_endpoint_host_and_port(monkeypatch):@@ -719,13 +647,6 @@ def test_tool_add_resource_rejects_hermes_credential_file_upload(tmp_path, monkeprovider._client.post.assert_not_called()-def test_get_tool_schemas_omits_profile_and_keeps_narrow_forget_tools():- provider = OpenVikingMemoryProvider()-- names = [schema["name"] for schema in provider.get_tool_schemas()]-- assert "viking_profile" not in names- assert "viking_forget" in namesdef test_viking_client_delete_uses_identity_headers(monkeypatch):@@ -1729,22 +1650,6 @@ def test_in_place_compression_lifecycle_allows_a_later_commit():f"{provider._client.post.call_args_list}")-def test_resolve_connection_settings_reads_config_yaml_non_secret_fields(monkeypatch):- """#68209: non-secret fields saved to config.yaml feed the resolution chain."""- _clear_openviking_env(monkeypatch)- provider_config = {- "endpoint": "http://saved.test:1933",- "account": "cfg-account",- "user": "cfg-user",- "agent": "cfg-agent",- }-- settings = openviking_module._resolve_connection_settings(provider_config)-- assert settings["endpoint"] == "http://saved.test:1933"- assert settings["account"] == "cfg-account"- assert settings["user"] == "cfg-user"- assert settings["agent"] == "cfg-agent"def test_env_overrides_config_yaml_non_secret_fields(monkeypatch):diff --git a/tests/plugins/memory/test_retaindb_provider.py b/tests/plugins/memory/test_retaindb_provider.pyindex ea50a7ea19b..9367e8aeb50 100644--- a/tests/plugins/memory/test_retaindb_provider.py+++ b/tests/plugins/memory/test_retaindb_provider.py@@ -114,29 +114,6 @@ def _capture_initialized_client(monkeypatch, tmp_path):return retaindb_module, captured-def test_retaindb_config_loader_uses_readonly_config(monkeypatch):- import hermes_cli.config as config_mod- import plugins.memory.retaindb as retaindb_module-- backing_config = {- "memory": {- "retaindb": {- "base_url": "https://saved.example",- "project": "saved-project",- }- }- }- monkeypatch.setattr(config_mod, "load_config_readonly", lambda: backing_config)- monkeypatch.setattr(- config_mod,- "load_config",- MagicMock(side_effect=AssertionError("read-only provider path must not load a mutable copy")),- )-- config = retaindb_module._load_retaindb_config()-- assert config == backing_config["memory"]["retaindb"]- assert config is not backing_config["memory"]["retaindb"]def test_initialize_reads_real_dashboard_config_file(tmp_path, monkeypatch):@@ -161,21 +138,6 @@ memory:assert captured["project"] == "dashboard-project"-def test_initialize_reads_base_url_and_project_from_config_yaml(tmp_path, monkeypatch):- """#68209: non-secret base_url/project come from config.yaml when env is unset."""- for var in ("RETAINDB_API_KEY", "RETAINDB_BASE_URL", "RETAINDB_PROJECT"):- monkeypatch.delenv(var, raising=False)- retaindb_module, captured = _capture_initialized_client(monkeypatch, tmp_path)- monkeypatch.setattr(- retaindb_module,- "_load_retaindb_config",- lambda: {"base_url": "https://retaindb.example.com/", "project": "cfg-project"},- )-- RetainDBMemoryProvider().initialize("sess-1")-- assert captured["base_url"] == "https://retaindb.example.com" # trailing slash stripped- assert captured["project"] == "cfg-project"def test_initialize_env_overrides_config_yaml(tmp_path, monkeypatch):diff --git a/tests/plugins/memory/test_supermemory_provider.py b/tests/plugins/memory/test_supermemory_provider.pyindex 0ad25a2a159..641a98b2c71 100644--- a/tests/plugins/memory/test_supermemory_provider.py+++ b/tests/plugins/memory/test_supermemory_provider.py@@ -13,7 +13,6 @@ from plugins.memory.supermemory import (_MAX_PENDING_TURNS,_capture_custom_id,_clean_text_for_capture,- _format_connection_summary,_format_prefetch_context,_load_supermemory_config,_probe_supermemory_connection,@@ -408,10 +407,6 @@ def test_shutdown_joins_threads_and_flushes_buffer(provider, monkeypatch, frozenassert provider._pending_turns == []-def test_store_tool_returns_saved_payload(provider):- result = json.loads(provider.handle_tool_call("supermemory_store", {"content": "Jordan likes concise docs"}))- assert result["saved"] is True- assert result["id"] == "mem_123"def test_search_tool_formats_results(provider):@@ -538,20 +533,11 @@ def test_multi_container_disabled_by_default(provider):assert "container_tag" not in s["parameters"]["properties"]-def test_get_config_schema_minimal():- """get_config_schema only returns the API key field."""- p = SupermemoryMemoryProvider()- schema = p.get_config_schema()- assert len(schema) == 1- assert schema[0]["key"] == "api_key"- assert schema[0]["secret"] is Truedef test_probe_supermemory_connection_missing_key(tmp_path):status = _probe_supermemory_connection("", str(tmp_path))assert status["ok"] is False- assert status["error"] == "SUPERMEMORY_API_KEY not set"- assert status["container_tag"] == "hermes"def _stub_supermemory_importable(monkeypatch):@@ -577,7 +563,7 @@ def _stub_supermemory_importable(monkeypatch):monkeypatch.setattr(builtins, "__import__", fake_import)-def test_post_setup_writes_config_and_prints_summary(monkeypatch, tmp_path, capsys):+def test_post_setup_writes_config_and_env(monkeypatch, tmp_path):config: dict = {"memory": {}}monkeypatch.setenv("SUPERMEMORY_API_KEY", "")monkeypatch.setattr(@@ -609,11 +595,6 @@ def test_post_setup_writes_config_and_prints_summary(monkeypatch, tmp_path, capsenv_text = (tmp_path / ".env").read_text(encoding="utf-8")assert "SUPERMEMORY_API_KEY=new-api-key" in env_text- out = capsys.readouterr().out- assert "✓ Connected" in out- assert "3 profile facts" in out- assert "Memory provider: supermemory" in out-@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits not enforced on Windows")def test_save_config_sets_owner_only_permissions(tmp_path):diff --git a/tests/plugins/model_providers/test_commandcode_profile.py b/tests/plugins/model_providers/test_commandcode_profile.pyindex f33e58fd161..d5a1fe75855 100644--- a/tests/plugins/model_providers/test_commandcode_profile.py+++ b/tests/plugins/model_providers/test_commandcode_profile.py@@ -45,44 +45,6 @@ def commandcode_anthropic_profile():# ── Chat Completions profile ──────────────────────────────────────────────────-class TestCommandCodeProfileIdentity:- """Profile metadata matches the declared contract."""-- def test_name(self, commandcode_profile):- assert commandcode_profile.name == "commandcode"-- def test_api_mode(self, commandcode_profile):- assert commandcode_profile.api_mode == "chat_completions"-- def test_aliases(self, commandcode_profile):- assert "commandcode-chat" in commandcode_profile.aliases-- def test_env_vars(self, commandcode_profile):- assert "COMMANDCODE_API_KEY" in commandcode_profile.env_vars-- def test_base_url(self, commandcode_profile):- assert commandcode_profile.base_url == "https://api.commandcode.ai/provider/v1"-- def test_display_name(self, commandcode_profile):- assert "CommandCode" in commandcode_profile.display_name-- def test_has_fallback_models(self, commandcode_profile):- assert len(commandcode_profile.fallback_models) >= 5- # Should include the major families- names = " ".join(commandcode_profile.fallback_models)- assert "deepseek" in names- assert "Qwen" in names- assert "Kimi" in names- assert "gemini" in names-- def test_default_aux_model(self, commandcode_profile):- assert commandcode_profile.default_aux_model == "deepseek/deepseek-v4-flash"-- def test_signup_url(self, commandcode_profile):- assert "commandcode" in commandcode_profile.signup_url.lower()-- def test_hostname_derived_from_base_url(self, commandcode_profile):- assert commandcode_profile.get_hostname() == "api.commandcode.ai"class TestCommandCodeReasoningWireControls:@@ -113,20 +75,10 @@ class TestCommandCodeReasoningWireControls:class TestCommandCodeAnthropicProfileIdentity:"""Anthropic-compatible profile metadata."""- def test_name(self, commandcode_anthropic_profile):- assert commandcode_anthropic_profile.name == "commandcode-anthropic"- def test_api_mode(self, commandcode_anthropic_profile):- assert commandcode_anthropic_profile.api_mode == "anthropic_messages"- def test_aliases(self, commandcode_anthropic_profile):- assert "commandcode-claude" in commandcode_anthropic_profile.aliases- def test_env_vars(self, commandcode_anthropic_profile):- assert "COMMANDCODE_API_KEY" in commandcode_anthropic_profile.env_vars- def test_base_url(self, commandcode_anthropic_profile):- assert commandcode_anthropic_profile.base_url == "https://api.commandcode.ai/provider/v1"def test_fallback_models_are_claude_family(self, commandcode_anthropic_profile):for model in commandcode_anthropic_profile.fallback_models:@@ -134,15 +86,8 @@ class TestCommandCodeAnthropicProfileIdentity:f"All anthropic fallback models should be claude-*: got {model}")- def test_default_aux_model(self, commandcode_anthropic_profile):- assert commandcode_anthropic_profile.default_aux_model == "claude-haiku-4-5-20251001"- def test_display_name_distinct_from_chat(self, commandcode_anthropic_profile):- # The Anthropic profile should be distinguishable in /model picker- assert "(Anthropic)" in commandcode_anthropic_profile.display_name- def test_hostname_derived_from_base_url(self, commandcode_anthropic_profile):- assert commandcode_anthropic_profile.get_hostname() == "api.commandcode.ai"# ── Bearer Auth Recognition ───────────────────────────────────────────────────@@ -176,60 +121,10 @@ class TestCommandCodeAnthropicBearerAuth:# ── Registry integrity ───────────────────────────────────────────────────────-class TestCommandCodeRegistryIntegrity:- """Both profiles are discoverable and distinct."""-- def test_both_profiles_registered(self):- import model_tools # noqa: F401- import providers-- chat = providers.get_provider_profile("commandcode")- anth = providers.get_provider_profile("commandcode-anthropic")- assert chat is not None- assert anth is not None- assert chat is not anth # distinct profile instances-- def test_alias_lookup(self):- import model_tools # noqa: F401- import providers-- assert providers.get_provider_profile("commandcode-chat") is not None- assert providers.get_provider_profile("commandcode-claude") is not None-- def test_unknown_returns_none(self):- import model_tools # noqa: F401- import providers-- assert providers.get_provider_profile("commandcode-nonexistent") is None# ── Model list filtering ──────────────────────────────────────────────────────-class TestCommandCodeModelFiltering:- """``fetch_models`` filtering contracts."""-- def test_anthropic_profile_filters_to_claude(self):- """If we mock a response with mixed models, anthropic profile- should only return claude-* models.- """- from plugins.model_providers.commandcode import CommandCodeAnthropicProfile-- profile = CommandCodeAnthropicProfile(- name="test-cc-anth",- api_mode="anthropic_messages",- env_vars=("COMMANDCODE_API_KEY",),- base_url="https://api.commandcode.ai/provider/v1",- )-- # Don't actually hit the network — just test the filter logic.- # The class has a fetch_models override that filters.- # We verify the filter works by inspecting the method.- import inspect-- source = inspect.getsource(profile.fetch_models)- assert "startswith(\"claude-\")" in source or '"claude-" in m' in source, (- "CommandCodeAnthropicProfile.fetch_models should filter to claude-* models"- )# ── Picker contract ──────────────────────────────────────────────────────────@@ -244,16 +139,6 @@ class TestCommandCodeFetchModelsPickerContract:was swallowed, leaving the provider with zero models."""- @pytest.mark.parametrize("profile_name", ["commandcode", "commandcode-anthropic"])- def test_accepts_base_url_kwarg(self, profile_name):- import inspect-- import model_tools # noqa: F401 — triggers discovery- import providers-- profile = providers.get_provider_profile(profile_name)- assert profile is not None- assert "base_url" in inspect.signature(profile.fetch_models).parametersdef test_resolve_provider_full(self):"""Both profiles must resolve through the model-switch path.diff --git a/tests/plugins/model_providers/test_deepseek_profile.py b/tests/plugins/model_providers/test_deepseek_profile.pyindex d56d68cb8db..0bf26149503 100644--- a/tests/plugins/model_providers/test_deepseek_profile.py+++ b/tests/plugins/model_providers/test_deepseek_profile.py@@ -190,15 +190,14 @@ class TestDeepSeekAuxModel:system."""- def test_profile_advertises_deepseek_flash(self, deepseek_profile):- assert deepseek_profile.default_aux_model == "deepseek-flash"def test_fallback_models_are_current_ids(self, deepseek_profile):from hermes_cli.model_normalize import _normalize_for_deepseek# Every advertised id must survive normalization unchanged (no retired alias in the picker).assert all(_normalize_for_deepseek(m) == m for m in deepseek_profile.fallback_models)- def test_consumer_api_returns_deepseek_flash(self):+ def test_consumer_api_matches_profile_aux_model(self, deepseek_profile):from agent.auxiliary_client import _get_aux_model_for_provider- assert _get_aux_model_for_provider("deepseek") == "deepseek-flash"+ assert deepseek_profile.default_aux_model+ assert _get_aux_model_for_provider("deepseek") == deepseek_profile.default_aux_modeldiff --git a/tests/plugins/model_providers/test_fireworks_profile.py b/tests/plugins/model_providers/test_fireworks_profile.pyindex cb12cbff86e..50d348733ed 100644--- a/tests/plugins/model_providers/test_fireworks_profile.py+++ b/tests/plugins/model_providers/test_fireworks_profile.py@@ -22,21 +22,6 @@ def fireworks_profile():return profile-class TestFireworksIdentity:- def test_core_fields(self, fireworks_profile):- p = fireworks_profile- assert p.name == "fireworks"- assert p.auth_type == "api_key"- assert p.base_url == "https://api.fireworks.ai/inference/v1"- assert "FIREWORKS_API_KEY" in p.env_vars- assert "FIREWORKS_BASE_URL" not in p.env_vars-- def test_display_metadata_present(self, fireworks_profile):- # Prominence copy is surfaced in the picker; keep it non-empty rather- # than pinning exact marketing wording (that's expected to change).- assert fireworks_profile.display_name- assert fireworks_profile.description- assert fireworks_profile.signup_url.startswith("https://")class TestFireworksHeaders:@@ -58,18 +43,6 @@ class TestFireworksHeaders:assert fireworks_profile.default_headers["User-Agent"].startswith("HermesAgent/")-class TestFireworksAliases:- @pytest.mark.parametrize("alias", ["fireworks-ai", "fw"])- def test_alias_resolves_via_registry(self, fireworks_profile, alias):- import providers-- resolved = providers.get_provider_profile(alias)- assert resolved is not None- assert resolved.name == "fireworks"-- def test_aliases_declared_on_profile(self, fireworks_profile):- assert "fireworks-ai" in fireworks_profile.aliases- assert "fw" in fireworks_profile.aliasesclass TestFireworksModelDefaults:diff --git a/tests/plugins/model_providers/test_kimi_profile.py b/tests/plugins/model_providers/test_kimi_profile.pyindex df969233000..33115d60ab9 100644--- a/tests/plugins/model_providers/test_kimi_profile.py+++ b/tests/plugins/model_providers/test_kimi_profile.py@@ -129,20 +129,5 @@ class TestKimiModelDiscovery:assert models == ["kimi-k2.6"]-class TestKimiFullKwargsIntegration:- """The transport's full kwargs carry at most one reasoning knob."""-- def _build(self, kimi_profile, reasoning_config):- from agent.transports.chat_completions import ChatCompletionsTransport-- return ChatCompletionsTransport().build_kwargs(- model="kimi-k2-turbo-preview",- messages=[{"role": "user", "content": "ping"}],- tools=None,- provider_profile=kimi_profile,- reasoning_config=reasoning_config,- base_url="https://api.moonshot.ai/v1",- provider_name="kimi-coding",- )diff --git a/tests/plugins/model_providers/test_minimax_profile.py b/tests/plugins/model_providers/test_minimax_profile.pyindex 75c8d016391..27f4e4e1b6c 100644--- a/tests/plugins/model_providers/test_minimax_profile.py+++ b/tests/plugins/model_providers/test_minimax_profile.py@@ -52,32 +52,6 @@ class TestMinimaxAuxModelM3:catalog order rather than the pre-M3 era."""- @pytest.mark.parametrize(- "provider_id,expected",- [- ("minimax", "MiniMax-M3"),- ("minimax-cn", "MiniMax-M3"),- # minimax-oauth sticks with M2.7: the OAuth / Coding Plan- # tier historically used -highspeed (PR #6082 collapsed that- # to plain M2.7 to avoid the 2x TPS surcharge). M3 is not on- # the OAuth/Coding Plan tier per platform docs as of this PR,- # so the safe choice is the cheapest generally-available- # M2.7 — matching PR #6082's intent.- ("minimax-oauth", "MiniMax-M2.7"),- ],- )- def test_profile_advertises_expected_aux_model(- self, provider_id, expected- ):- import model_tools # noqa: F401- import providers-- profile = providers.get_provider_profile(provider_id)- assert profile is not None- assert profile.default_aux_model == expected, (- f"{provider_id} default_aux_model drifted to "- f"{profile.default_aux_model!r}, expected {expected!r}"- )def test_consumer_api_returns_non_empty_for_each_provider(self, minimax_profile):from agent.auxiliary_client import _get_aux_model_for_provider@@ -97,27 +71,6 @@ class TestMinimaxAuxModelM3:)-class TestMinimaxAuxModelNotHighspeed:- """Regression guard against re-introducing the M2.7-highspeed aux default.-- PR #6082 collapsed the highspeed aux choice to plain M2.7 because the- highspeed variant costs 2x with no real benefit for compression / vision /- session-search aux tasks. None of the three MiniMax profiles should- silently re-introduce that 2x-cost path.- """-- @pytest.mark.parametrize("provider_id", ["minimax", "minimax-cn", "minimax-oauth"])- def test_default_aux_model_is_not_highspeed(self, provider_id):- import model_tools # noqa: F401- import providers-- profile = providers.get_provider_profile(provider_id)- assert profile is not None- assert "highspeed" not in profile.default_aux_model.lower(), (- f"{provider_id} default_aux_model={profile.default_aux_model!r} "- "is a -highspeed variant — that costs 2x for the same model and "- "broke #4082 the first time. Revert to plain M2.7 or M3."- )class TestMinimaxM3OpenAIReasoningWireShape:diff --git a/tests/plugins/model_providers/test_ollama_cloud_profile.py b/tests/plugins/model_providers/test_ollama_cloud_profile.pyindex e93a09ce7d0..2144ad35d4e 100644--- a/tests/plugins/model_providers/test_ollama_cloud_profile.py+++ b/tests/plugins/model_providers/test_ollama_cloud_profile.py@@ -227,8 +227,3 @@ class TestOllamaModelSupportsThinking:)-class TestOllamaCloudAuxModel:- """Ollama Cloud aux model is set on the profile."""-- def test_profile_advertises_aux_model(self, ollama_cloud_profile):- assert ollama_cloud_profile.default_aux_model == "nemotron-3-nano:30b"diff --git a/tests/plugins/model_providers/test_opencode_go_profile.py b/tests/plugins/model_providers/test_opencode_go_profile.pyindex 7f50c4da896..5505427c3bc 100644--- a/tests/plugins/model_providers/test_opencode_go_profile.py+++ b/tests/plugins/model_providers/test_opencode_go_profile.py@@ -266,7 +266,7 @@ def test_opencode_go_plan_windows_reach_usage_through_profile_hook(opencode_go_p"""The Go plan's rolling/weekly/monthly windows feed /usage via the profile hook — no core table entry."""from datetime import datetime, timezone- from agent.account_usage import fetch_account_usage, render_account_usage_lines+ from agent.account_usage import fetch_account_usageclass _Response:status_code = 200@@ -309,4 +309,3 @@ def test_opencode_go_plan_windows_reach_usage_through_profile_hook(opencode_go_passert [(w.label, w.used_percent) for w in snapshot.windows] == [("Rolling window", 3.0), ("Weekly", 2.0), ("Monthly", 2.0)]assert snapshot.windows[0].reset_at == datetime(2026, 9, 16, 21, 44, 55, 176000, tzinfo=timezone.utc)- assert "97% remaining (3% used)" in "\n".join(render_account_usage_lines(snapshot))diff --git a/tests/plugins/model_providers/test_upstage_profile.py b/tests/plugins/model_providers/test_upstage_profile.pyindex bc7120e7026..22697f49ec0 100644--- a/tests/plugins/model_providers/test_upstage_profile.py+++ b/tests/plugins/model_providers/test_upstage_profile.py@@ -28,22 +28,8 @@ def upstage_profile():class TestUpstageProfile:- def test_identity_and_endpoint(self, upstage_profile):- assert upstage_profile.name == "upstage"- assert upstage_profile.api_mode == "chat_completions"- assert upstage_profile.auth_type == "api_key"- assert upstage_profile.base_url == "https://api.upstage.ai/v1"- assert upstage_profile.get_hostname() == "api.upstage.ai"- def test_solar_alias_resolves(self):- import model_tools # noqa: F401- import providers- assert providers.get_provider_profile("solar") is upstage_profile_singleton()-- def test_env_vars(self, upstage_profile):- # API key first, optional base-url override second (priority order).- assert upstage_profile.env_vars == ("UPSTAGE_API_KEY", "UPSTAGE_BASE_URL")def test_fallback_models_are_agentic_pro_only(self, upstage_profile):# Only the agentic, tool-calling Solar Pro models belong in the offline@@ -56,13 +42,7 @@ class TestUpstageProfile:denied in m for m in upstage_profile.fallback_models), f"non-agentic family {denied!r} must not be a fallback default"- def test_default_model_is_solar_pro3(self, upstage_profile):- # Entry [0] is the setup default (get_default_model_for_provider).- assert upstage_profile.fallback_models[0] == "solar-pro3"- def test_aux_model_left_empty(self, upstage_profile):- # Unset → auxiliary side tasks fall back to the user's main model.- assert upstage_profile.default_aux_model == ""class TestUpstageReasoning:@@ -130,8 +110,3 @@ class TestUpstageReasoning:_, top_level = upstage_profile.build_api_kwargs_extras(model=None)assert top_level == {"reasoning_effort": "medium"}--def upstage_profile_singleton():- import providers-- return providers.get_provider_profile("upstage")diff --git a/tests/plugins/platforms/buzz/test_buzz_ws_dial_happy_eyeballs.py b/tests/plugins/platforms/buzz/test_buzz_ws_dial_happy_eyeballs.pydeleted file mode 100644index 7c14f2e6ddb..00000000000--- a/tests/plugins/platforms/buzz/test_buzz_ws_dial_happy_eyeballs.py+++ /dev/null@@ -1,36 +0,0 @@-"""Buzz WebSocket dial races IPv6/IPv4 (#114265): ``happy_eyeballs_delay`` reaches-``loop.create_connection`` through ``websockets.connect`` — see tests/gateway/test_ws_dial_happy_eyeballs.py."""--from __future__ import annotations--import asyncio-from unittest.mock import AsyncMock, MagicMock--import pytest--pytest.importorskip("websockets")--EXPECTED_DELAY = 0.25---async def test_buzz_websocket_loop_dial_races_ipv6_ipv4(monkeypatch):- import websockets-- from plugins.platforms.buzz.adapter import BuzzAdapter-- adapter = BuzzAdapter.__new__(BuzzAdapter)- adapter.relay_url = "https://relay.example.com/"- adapter._ws_ready = None- adapter._mark_connected = MagicMock()- recorded: dict = {}-- def fake_connect(*_args, **kwargs):- recorded.update(kwargs)- raise asyncio.CancelledError # first dial ends the loop: only the kwargs matter here-- monkeypatch.setattr(websockets, "connect", fake_connect)- monkeypatch.setattr(asyncio, "sleep", AsyncMock())- with pytest.raises(asyncio.CancelledError):- await adapter._websocket_loop()- assert recorded["happy_eyeballs_delay"] == EXPECTED_DELAYdiff --git a/tests/plugins/platforms/photon/test_auth.py b/tests/plugins/platforms/photon/test_auth.pyindex 9a650e58300..56cc570690e 100644--- a/tests/plugins/platforms/photon/test_auth.py+++ b/tests/plugins/platforms/photon/test_auth.py@@ -3,13 +3,10 @@ from __future__ import annotationsimport jsonimport os-import statimport threading-import timefrom base64 import b64encodefrom pathlib import Pathfrom typing import Any, Dict-from unittest import mockimport pytest@@ -345,12 +342,8 @@ def test_credential_summary_no_secret_leak(blob = "\n".join(lines)assert "token-aaaa" not in blobassert "secret-bbbb" not in blob- assert "device token : ✓" in blob- assert "project secret : ✓" in blob- # Unified id: dashboard id == Spectrum id, surfaced as one project id.- assert "project id : sp-uuid" in blob- assert "my number : ✗ missing" in blob- assert "assigned number : ✗ missing" in blob+ # Non-secret identifiers are still surfaced.+ assert "sp-uuid" in blob# ---------------------------------------------------------------------------diff --git a/tests/plugins/platforms/photon/test_check_requirements_risks.py b/tests/plugins/platforms/photon/test_check_requirements_risks.pyindex e4455fe7d08..f634f3dcef3 100644--- a/tests/plugins/platforms/photon/test_check_requirements_risks.py+++ b/tests/plugins/platforms/photon/test_check_requirements_risks.py@@ -14,13 +14,11 @@ from __future__ import annotationsimport loggingimport shutil-import typesfrom pathlib import Pathimport pytestfrom plugins.platforms.photon import adapter as adapter_mod-from plugins.platforms.photon import cli as cli_modfrom plugins.platforms.photon import sidecar_paths@@ -104,11 +102,6 @@ def test_risk2_fix_empty_node_modules_no_longer_passes_guard(# ----------------------------------------------------------------------------def test_cli_status_shares_adapter_sidecar_deps_check(tmp_path: Path) -> None:- """`hermes photon status` must use the exact same spectrum-ts check as- check_requirements() / _start_sidecar() — not a separate node_modules-only- existence check that would disagree on a partial/empty install."""- assert cli_mod.sidecar_deps_installed is adapter_mod.sidecar_deps_installeddef test_sidecar_deps_installed_false_on_empty_node_modules(diff --git a/tests/plugins/platforms/photon/test_fatal_notify_self_cancel.py b/tests/plugins/platforms/photon/test_fatal_notify_self_cancel.pyindex 68c034a99d6..bb4a4ab995a 100644--- a/tests/plugins/platforms/photon/test_fatal_notify_self_cancel.py+++ b/tests/plugins/platforms/photon/test_fatal_notify_self_cancel.py@@ -21,7 +21,7 @@ layer down, which that PR's scope could not reach.from __future__ import annotationsimport asyncio-from typing import Any, Dict, List+from typing import Any, Dictimport pytest@@ -124,26 +124,9 @@ class TestFatalNotifyIsDetached:with caplog.at_level("WARNING"):await adapter._notify_fatal_error_logged()- assert "fatal-error notification failed" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)-class TestBothCallSitesDetached:- """Neither fatal path may await the notification inline."""-- def test_no_inline_notify_awaits_remain(self) -> None:- """Guard against a future edit reintroducing the inline await."""- import inspect-- from plugins.platforms.photon import adapter as photon_adapter-- for name in ("_monitor_sidecar_health", "_supervise_sidecar"):- src = inspect.getsource(getattr(photon_adapter.PhotonAdapter, name))- assert "await self._notify_fatal_error()" not in src, (- f"{name} awaits _notify_fatal_error inline; use "- f"_dispatch_fatal_notification() so disconnect() cannot cancel "- f"its own caller"- )- assert "_dispatch_fatal_notification()" in srcasync def _noop() -> None:diff --git a/tests/plugins/platforms/photon/test_mention_gating.py b/tests/plugins/platforms/photon/test_mention_gating.pyindex 5e120ce50f1..12c10031b43 100644--- a/tests/plugins/platforms/photon/test_mention_gating.py+++ b/tests/plugins/platforms/photon/test_mention_gating.py@@ -58,11 +58,6 @@ def _capture(adapter: PhotonAdapter, monkeypatch: pytest.MonkeyPatch) -> List[Mereturn captured-def test_require_mention_defaults_off(monkeypatch: pytest.MonkeyPatch) -> None:- adapter = _make_adapter(monkeypatch)- assert adapter.require_mention is False- # Defaults compile to the two Hermes wake-word patterns.- assert len(adapter._mention_patterns) == 2@pytest.mark.asynciodiff --git a/tests/plugins/platforms/photon/test_presence_watchdog.py b/tests/plugins/platforms/photon/test_presence_watchdog.pyindex 65256e990ac..a3d50d14892 100644--- a/tests/plugins/platforms/photon/test_presence_watchdog.py+++ b/tests/plugins/platforms/photon/test_presence_watchdog.py@@ -28,14 +28,6 @@ def _make_adapter(monkeypatch: pytest.MonkeyPatch, **extra: Any) -> PhotonAdaptereturn PhotonAdapter(cfg)-def test_probe_config_defaults(monkeypatch: pytest.MonkeyPatch) -> None:- a = _make_adapter(monkeypatch)- # Conservative by default: probe only after 10+ minutes of stream silence- # so quiet shared lines never trigger restart storms.- assert a._probe_interval == 600.0- assert a._probe_timeout == 10.0- assert a._probe_max_failures == 3- assert a._probe_enabled is Truedef test_note_activity_resets_failures(monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/plugins/platforms/photon/test_setup_access.py b/tests/plugins/platforms/photon/test_setup_access.pyindex ca7d5c691cf..5ac25b259bf 100644--- a/tests/plugins/platforms/photon/test_setup_access.py+++ b/tests/plugins/platforms/photon/test_setup_access.py@@ -11,7 +11,7 @@ import argparseimport pytest-from hermes_cli.config import get_env_value, save_env_value+from hermes_cli.config import get_env_valuefrom plugins.platforms.photon.adapter import _env_enablementfrom plugins.platforms.photon import cli@@ -41,51 +41,6 @@ def test_env_enablement_seeds_home_channel(monkeypatch: pytest.MonkeyPatch) -> N}-def test_setup_hint_uses_gateway_service_command(monkeypatch: pytest.MonkeyPatch, capsys) -> None:- monkeypatch.setattr(cli.photon_auth, "load_photon_token", lambda: "token")- # Token validation (added for #72763) would otherwise hit the network.- monkeypatch.setattr(cli.photon_auth, "check_photon_token_valid", lambda token: True)- # The dashboard id *is* the Spectrum project id (ids unified), so setup no- # longer enables Spectrum or fetches a separate spectrumProjectId — it- # reuses this id directly.- monkeypatch.setattr(cli.photon_auth, "load_dashboard_project_id", lambda: "dashboard")- # No existing credentials — first-time setup path.- monkeypatch.setattr(- cli.photon_auth, "load_project_credentials", lambda: (None, None),- )- monkeypatch.setattr(- cli.photon_auth,- "regenerate_project_secret",- lambda token, dashboard_id: "secret_123",- )- monkeypatch.setattr(cli.photon_auth, "store_project_credentials", lambda **kwargs: None)- monkeypatch.setattr(- cli.photon_auth,- "register_user_if_absent",- lambda *args, **kwargs: ({"id": "user_123", "phoneNumber": "+155****4567"}, True),- )- monkeypatch.setattr(cli.photon_auth, "user_assigned_line", lambda user: "+155****4321")- monkeypatch.setattr(cli.photon_auth, "store_user_numbers", lambda **kwargs: None)- monkeypatch.setattr(cli, "_install_sidecar", lambda: 0)-- rc = cli._cmd_setup(- argparse.Namespace(- project_name=None,- phone="+155****4567",- first_name=None,- last_name=None,- email=None,- no_browser=True,- skip_sidecar_install=False,- )- )-- assert rc == 0- out = capsys.readouterr().out- assert "Start the gateway: hermes gateway start" in out- assert "--platform photon" not in out- assert "new secret saved" in out- assert "restart it so the sidecar" in outdef test_setup_reuses_valid_existing_secret(diff --git a/tests/plugins/platforms/photon/test_streaming.py b/tests/plugins/platforms/photon/test_streaming.pydeleted file mode 100644index e27069c12e9..00000000000--- a/tests/plugins/platforms/photon/test_streaming.py+++ /dev/null@@ -1,12 +0,0 @@-"""Regression tests for Photon adapter streaming behavior."""-from plugins.platforms.photon.adapter import PhotonAdapter---def test_photon_adapter_does_not_support_message_editing() -> None:- """PhotonAdapter.SUPPORTS_MESSAGE_EDITING must be False.-- Photon (iMessage) has no real edit API for already-sent messages.- This attribute signals the gateway to suppress the streaming cursor- instead of leaving a stale tofu square (▉) behind when edit attempts fail.- """- assert PhotonAdapter.SUPPORTS_MESSAGE_EDITING is Falsediff --git a/tests/plugins/platforms/photon/test_zombie_stream_watchdog.py b/tests/plugins/platforms/photon/test_zombie_stream_watchdog.pyindex e2f0d7e1bf2..8c30f36c2f6 100644--- a/tests/plugins/platforms/photon/test_zombie_stream_watchdog.py+++ b/tests/plugins/platforms/photon/test_zombie_stream_watchdog.py@@ -23,7 +23,6 @@ gRPC traffic occurs."""from __future__ import annotations-import asyncioimport jsonimport reimport subprocess@@ -248,16 +247,3 @@ async def test_inconclusive_probes_never_accumulate_toward_respawn(assert adapter._probe_failures == 0-def test_probe_upstream_reads_a_guid_shaped_id() -> None:- """The wire probe in ``probeUpstream`` must use the GUID helper: a non-GUID synthetic id is- rejected locally by the SDK ("Expected message resource GUID") before any round-trip, so- the classifier can never observe the not-found rejection that proves liveness (#117390).-- This is a source-reading gate on purpose: ``index.mjs`` is the sidecar entry point — it- binds an HTTP server at import time and needs the Spectrum SDK on the module path — so it- cannot be imported from a test. The GUID helper itself is executed by the Node harness- above; this test only pins that ``probeUpstream`` is wired to it."""- source = (_MODULE.parent / "index.mjs").read_text(encoding="utf-8")- probe_fn = source.split("async function probeUpstream()", 1)[1].split("\nasync function", 1)[0]- assert "createProbeMessageId()" in probe_fn- assert "hermes-liveness-probe-" not in sourcediff --git a/tests/plugins/test_a2a_phase23.py b/tests/plugins/test_a2a_phase23.pyindex 068b72f9abd..8dde5bee56c 100644--- a/tests/plugins/test_a2a_phase23.py+++ b/tests/plugins/test_a2a_phase23.py@@ -242,13 +242,6 @@ class TestStreamingEndToEnd:asyncio.run(run())- def test_agent_card_advertises_streaming(self):- card = protocol.build_agent_card(- name="test", url="http://localhost:9900/",- description="test", streaming=True, push_notifications=True,- )- assert card["capabilities"]["streaming"] is True- assert card["capabilities"]["pushNotifications"] is True# ═════════════════════════════════════════════════════════════════════════════@@ -302,9 +295,6 @@ class TestAntiLoopProtection:turns.reset("c1")assert turns.track("c1") == 1- def test_max_pingpong_turns_default(self, monkeypatch):- monkeypatch.delenv("A2A_MAX_PINGPONG_TURNS", raising=False)- assert protocol.max_pingpong_turns() == 5def test_max_pingpong_turns_env_override(self, monkeypatch):monkeypatch.setenv("A2A_MAX_PINGPONG_TURNS", "10")@@ -343,11 +333,6 @@ class TestAntiLoopProtection:class TestRateLimiting:- def test_allows_under_limit(self, monkeypatch):- monkeypatch.setenv("A2A_RATE_LIMIT", "10")- rl = protocol.RateLimiter()- for _ in range(10):- assert rl.allow("peer-1") is Truedef test_blocks_over_limit(self, monkeypatch):monkeypatch.setenv("A2A_RATE_LIMIT", "3")@@ -402,13 +387,6 @@ class TestRateLimiting:class TestMetrics:- def test_metrics_snapshot_has_fields(self):- m = protocol.metrics.snapshot()- for field in ("uptime_seconds", "inbound_total", "outbound_total",- "streams_started", "push_sent", "push_failed",- "tasks_completed", "tasks_failed", "anti_loop_triggers",- "rate_limit_triggers", "avg_latency_ms"):- assert field in mdef test_record_latency_updates_average(self):m = protocol.Metrics()@@ -446,22 +424,7 @@ class TestMetrics:class TestTaskStore:- def test_create_and_get(self):- store = protocol.TaskStore()- store.create("t1", "c1", "peer-1")- rec = store.get("t1")- assert rec["state"] == protocol.STATE_SUBMITTED- assert rec["context_id"] == "c1"- assert rec["peer"] == "peer-1"- def test_complete_keeps_task_queryable(self):- store = protocol.TaskStore()- store.create("t1", "c1", "p")- store.complete("t1", protocol.STATE_COMPLETED, "the reply")- rec = store.get("t1")- assert rec is not None- assert rec["state"] == protocol.STATE_COMPLETED- assert rec["reply"] == "the reply"def test_complete_is_idempotent(self):store = protocol.TaskStore()@@ -696,10 +659,6 @@ class TestA2AOrchestrate:assert "capability" in tools.a2a_orchestrate({"message": "do something"})assert "message" in tools.a2a_orchestrate({"capability": "research"})- def test_no_matching_peers(self, monkeypatch):- monkeypatch.setattr(tools, "_load_config", lambda: {})- result = tools.a2a_orchestrate({"capability": "research", "message": "search X"})- assert "no configured peers" in resultdef test_match_peers_by_capability(self, monkeypatch):monkeypatch.setattr(tools, "_load_config", lambda: _TWO_PEERS)diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.pyindex 3856b71dabc..d30f4a588af 100644--- a/tests/plugins/test_a2a_plugin.py+++ b/tests/plugins/test_a2a_plugin.py@@ -19,7 +19,6 @@ import socketimport threadingimport urllib.errorimport urllib.request-from concurrent.futures import Futurefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom types import SimpleNamespace@@ -264,26 +263,8 @@ class TestAgentCardV1:assert "web_search" in web["tags"]assert "web_extract" in web["tags"]- def test_skills_default_when_empty(self):- assert protocol.skills_from_toolsets([])[0]["id"] == "general"- assert protocol.skills_from_toolsets({})[0]["id"] == "general"---class TestV1Enums:- def test_task_states_are_screaming_snake(self):- assert protocol.STATE_SUBMITTED == "TASK_STATE_SUBMITTED"- assert protocol.STATE_WORKING == "TASK_STATE_WORKING"- assert protocol.STATE_COMPLETED == "TASK_STATE_COMPLETED"- assert protocol.STATE_FAILED == "TASK_STATE_FAILED"- assert protocol.STATE_CANCELED == "TASK_STATE_CANCELED"- assert protocol.STATE_REJECTED == "TASK_STATE_REJECTED"- assert protocol.STATE_INPUT_REQUIRED == "TASK_STATE_INPUT_REQUIRED"-- def test_roles_are_v1(self):- assert protocol.ROLE_USER == "ROLE_USER"- assert protocol.ROLE_AGENT == "ROLE_AGENT"- msg = protocol.text_message(protocol.ROLE_USER, "hi")- assert msg["role"] == "ROLE_USER"++class TestV1Parts:@@ -419,12 +400,7 @@ class TestPersistence:assert "what is 2+2" in outassert "[agent] 4" in out- def test_a2a_history_requires_context_id(self):- assert "required" in tools.a2a_history({})- def test_a2a_history_unknown_context(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- assert "No persisted conversation" in tools.a2a_history({"context_id": "ghost"})# --------------------------------------------------------------------------@@ -432,17 +408,8 @@ class TestPersistence:# --------------------------------------------------------------------------class TestClientTools:- def test_call_requires_args(self):- assert "required" in tools.a2a_call({"agent": "", "message": "hi"})- assert "required" in tools.a2a_call({"agent": "x", "message": ""})- def test_discover_requires_url(self):- assert "required" in tools.a2a_discover({"url": ""})- def test_unknown_peer(self, monkeypatch):- monkeypatch.setattr(tools, "_load_config", lambda: {"a2a_agents": {}})- out = tools.a2a_call({"agent": "ghost", "message": "hi"})- assert "unknown agent" in outdef test_discover_summarizes_v1_card(self, monkeypatch):card = protocol.build_agent_card(@@ -454,7 +421,6 @@ class TestClientTools:out = tools.a2a_discover({"url": "http://localhost:9999"})assert "researcher" in outassert "search" in out- assert "JSONRPC v1.0" in outdef test_call_sends_v1_message(self, monkeypatch):"""Outbound params: contextId inside the message, v1.0 role, no kind."""@@ -515,11 +481,6 @@ class TestClientTools:assert tools._rpc_url("http://base:3", {"url": "http://legacy:1/"}) == "http://legacy:1/"assert tools._rpc_url("http://base:3/", None) == "http://base:3"- def test_list_no_peers(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.setattr(tools, "_load_config", lambda: {})- out = tools.a2a_list({})- assert "No peers configured" in outclass TestRegistryDispatchConvention:@@ -694,14 +655,6 @@ class TestTaskRpcHandlers:resp = adapter._rpc_tasks_get(1, {"taskId": "ghost"})assert resp["error"]["code"] == protocol.ERR_TASK_NOT_FOUND- def test_tasks_get_returns_completed_task(self):- adapter = _bare_adapter()- adapter.tasks.create("task-done", "ctx-d", "peer")- adapter.tasks.complete("task-done", protocol.STATE_COMPLETED, "answer")- resp = adapter._rpc_tasks_get(1, {"taskId": "task-done"})- task = resp["result"]- assert task["status"]["state"] == "TASK_STATE_COMPLETED"- assert protocol.extract_text(task["artifacts"][0]) == "answer"def test_tasks_cancel_resets_turns_for_context(self):"""Cancel must reset anti-loop turns for the task's CONTEXT (the old@@ -753,17 +706,6 @@ class TestTaskRpcHandlers:ids = {t["id"] for t in result["tasks"]} | {t["id"] for t in resp2["result"]["tasks"]}assert len(ids) == 4 # no overlap between pages- def test_push_config_create_returns_config_id(self):- adapter = _bare_adapter()- adapter.tasks.create("task-p", "ctx-p", "peer")- resp = adapter._rpc_push_config_create(1, {- "taskId": "task-p",- "pushNotificationConfig": {"url": "https://example.com/hook"},- })- cfg = resp["result"]- assert cfg["configId"].startswith("cfg-")- assert cfg["createdAt"]- assert cfg["pushNotificationConfig"]["url"] == "https://example.com/hook"def test_push_config_create_unknown_task(self):adapter = _bare_adapter()@@ -776,18 +718,6 @@ class TestTaskRpcHandlers:resp = adapter._rpc_push_config_create(1, {"taskId": "t"})assert resp["error"]["code"] == protocol.ERR_INVALID_PARAMS- def test_push_config_get_returns_stored_config(self):- """GetTaskPushNotificationConfig retrieves a config after create."""- adapter = _bare_adapter()- adapter.tasks.create("task-g", "ctx-g", "peer")- adapter._rpc_push_config_create(1, {- "taskId": "task-g",- "pushNotificationConfig": {"url": "https://example.com/hook"},- })- resp = adapter._rpc_push_config_get(1, {"taskId": "task-g"})- cfg = resp["result"]- assert cfg["pushNotificationConfig"]["url"] == "https://example.com/hook"- assert cfg["configId"].startswith("cfg-")def test_push_config_get_by_config_id(self):"""Get with a specific configId returns the matching config."""@@ -824,18 +754,6 @@ class TestTaskRpcHandlers:resp = adapter._rpc_push_config_get(1, {})assert resp["error"]["code"] == protocol.ERR_INVALID_PARAMS- def test_push_config_list_returns_configs(self):- """ListTaskPushNotificationConfigs returns all configs for a task."""- adapter = _bare_adapter()- adapter.tasks.create("task-l", "ctx-l", "peer")- adapter._rpc_push_config_create(1, {- "taskId": "task-l",- "pushNotificationConfig": {"url": "https://example.com/hook"},- })- resp = adapter._rpc_push_config_list(1, {"taskId": "task-l"})- configs = resp["result"]["configs"]- assert len(configs) == 1- assert configs[0]["pushNotificationConfig"]["url"] == "https://example.com/hook"def test_push_config_list_empty_for_task_without_config(self):"""List returns empty array for a task with no push config."""@@ -844,20 +762,6 @@ class TestTaskRpcHandlers:resp = adapter._rpc_push_config_list(1, {"taskId": "task-l2"})assert resp["result"]["configs"] == []- def test_push_config_delete_removes_config(self):- """DeleteTaskPushNotificationConfig removes the push config."""- adapter = _bare_adapter()- adapter.tasks.create("task-d", "ctx-d", "peer")- adapter._rpc_push_config_create(1, {- "taskId": "task-d",- "pushNotificationConfig": {"url": "https://example.com/hook"},- })- # Delete- resp = adapter._rpc_push_config_delete(1, {"taskId": "task-d"})- assert resp["result"]["deleted"] is True- # Get now fails- resp2 = adapter._rpc_push_config_get(1, {"taskId": "task-d"})- assert resp2["error"]["code"] == protocol.ERR_TASK_NOT_FOUNDdef test_push_config_delete_unknown_task(self):"""Delete for non-existent task returns not-found."""@@ -1341,14 +1245,6 @@ class TestPushNotificationEndToEnd:hook_server.server_close()-def test_agent_card_can_advertise_tenant():- card = protocol.build_agent_card(- name="tenant-agent",- url="http://localhost:9900/research/",- description="test",- tenant="research",- )- assert card["supportedInterfaces"][0]["tenant"] == "research"class TestMultiAgentRouting:@@ -1740,9 +1636,7 @@ class TestMultiplexConstructionScope:adapter = A2AAdapter(PlatformConfig(enabled=True, extra={}))assert adapter.port == _DEFAULT_PORTassert adapter.agent_name != "default-profile-agent"- assert adapter._agents[""]["description"] == (- "Hermes Agent — a general-purpose agent reachable over A2A."- )+ assert adapter._agents[""]["description"] != "Default profile's own agent."# _public_url was captured at construction time via a bare os.getenv, missed by the# scoped retrofit the sibling fields above already got.assert adapter._public_url != "https://default-profile.example.com/"diff --git a/tests/plugins/test_a2a_schema_registration.py b/tests/plugins/test_a2a_schema_registration.pydeleted file mode 100644index 76f9a3819df..00000000000--- a/tests/plugins/test_a2a_schema_registration.py+++ /dev/null@@ -1,55 +0,0 @@-"""Regression tests for A2A client-tool schema registration."""--from __future__ import annotations--import json--from plugins.platforms.a2a import tools as a2a_tools-from tools import tool_search-from tools.registry import ToolRegistry---def test_a2a_call_schema_round_trips_through_tool_describe(monkeypatch):- registry = ToolRegistry()-- # The client tools are config-gated now (test_a2a_tools_gate.py):- # open the gate the way a real install would — configure a peer.- monkeypatch.setattr(- a2a_tools,- "_load_config",- lambda: {"a2a_agents": {"peer": {"url": "http://localhost:9999"}}},- )-- class _Context:- def register_tool(self, name, toolset, schema, handler, **kwargs):- registry.register(- name=name,- toolset=toolset,- schema=schema,- handler=handler,- **kwargs,- )-- a2a_tools.register_tools(_Context())- definitions = registry.get_definitions({"a2a_call"})- monkeypatch.setattr(- tool_search,- "is_deferrable_tool_name",- # #97979 added the defer_tools positional (curated-set override).- lambda name, defer_tools=None: name == "a2a_call",- )-- described = json.loads(- tool_search.dispatch_tool_describe(- {"names": ["a2a_call"]},- current_tool_defs=definitions,- )- )["tools"]["a2a_call"]-- assert described["description"]- assert described["parameters"]["required"] == ["agent", "message"]- assert set(described["parameters"]["properties"]) == {- "agent",- "message",- "context_id",- }diff --git a/tests/plugins/test_a2a_tools_gate.py b/tests/plugins/test_a2a_tools_gate.pyindex fd1ad13d93d..d5e220417c6 100644--- a/tests/plugins/test_a2a_tools_gate.py+++ b/tests/plugins/test_a2a_tools_gate.py@@ -56,7 +56,7 @@ class TestA2AToolsGate(unittest.TestCase):seen[name] = kw.get("check_fn")a2at.register_tools(Ctx())- self.assertEqual(len(seen), 5, sorted(seen))+ self.assertTrue(seen)for name, fn in seen.items():self.assertIs(fn, a2at._a2a_tools_available, name)diff --git a/tests/plugins/test_chronos_verify.py b/tests/plugins/test_chronos_verify.pyindex 6380ec5f9a4..97007101a24 100644--- a/tests/plugins/test_chronos_verify.py+++ b/tests/plugins/test_chronos_verify.py@@ -181,13 +181,7 @@ def test_jwks_client_sends_explicit_http_headers(monkeypatch):verify_mod._get_jwk_client(url)assert captured["url"] == url- assert captured["kwargs"].get("headers") == {- "Accept": "application/json",- "User-Agent": "HermesAgent/1.0",- }-+ headers = captured["kwargs"].get("headers") or {}+ assert headers.get("Accept") and headers.get("User-Agent")-def test_get_fire_verifier_returns_nas_verifier():- from plugins.cron_providers.chronos.verify import get_fire_verifier, verify_nas_fire_token- assert get_fire_verifier() is verify_nas_fire_tokendiff --git a/tests/plugins/test_disk_cleanup_plugin.py b/tests/plugins/test_disk_cleanup_plugin.pyindex e3c8a723e7f..d8cc4f68c1f 100644--- a/tests/plugins/test_disk_cleanup_plugin.py+++ b/tests/plugins/test_disk_cleanup_plugin.py@@ -479,28 +479,12 @@ class TestOnSessionEndHook:pi._on_session_end(session_id="s1", completed=True, interrupted=False)assert not p.exists(), "test file should be auto-deleted"- def test_noop_when_no_test_tracked(self, _isolate_env):- pi = _load_plugin_init()- # Nothing tracked → on_session_end should not raise.- pi._on_session_end(session_id="empty", completed=True, interrupted=False)# ---------------------------------------------------------------------------# Slash command# ----------------------------------------------------------------------------class TestSlashCommand:- def test_help(self, _isolate_env):- pi = _load_plugin_init()- out = pi._handle_slash("help")- assert "disk-cleanup" in out- assert "status" in out--- def test_unknown_subcommand(self, _isolate_env):- pi = _load_plugin_init()- out = pi._handle_slash("foobar")- assert "Unknown subcommand" in out# ---------------------------------------------------------------------------diff --git a/tests/plugins/test_google_meet_plugin.py b/tests/plugins/test_google_meet_plugin.pyindex cdcd90db1b5..bccad6765e5 100644--- a/tests/plugins/test_google_meet_plugin.py+++ b/tests/plugins/test_google_meet_plugin.py@@ -107,9 +107,9 @@ def test_start_refuses_unsafe_url():def test_status_reports_no_active_meeting():from plugins.google_meet import process_manager as pm- assert pm.status() == {"ok": False, "reason": "no active meeting"}- assert pm.transcript() == {"ok": False, "reason": "no active meeting"}- assert pm.stop() == {"ok": False, "reason": "no active meeting"}+ assert pm.status()["ok"] is False+ assert pm.transcript()["ok"] is False+ assert pm.stop()["ok"] is Falsedef test_transcript_reads_last_n_lines(tmp_path):@@ -177,7 +177,7 @@ def test_meet_join_handler_missing_url_returns_error():out = json.loads(handle_meet_join({}))assert out["success"] is False- assert "url is required" in out["error"]+ assert out["error"]# ---------------------------------------------------------------------------@@ -196,20 +196,6 @@ def test_on_session_end_noop_when_nothing_active():# Plugin register() — platform gating + tool registration# ----------------------------------------------------------------------------def test_register_refuses_on_windows():- import plugins.google_meet as plugin-- calls = {"tools": [], "cli": [], "hooks": []}-- class _Ctx:- def register_tool(self, **kw): calls["tools"].append(kw["name"])- def register_cli_command(self, **kw): calls["cli"].append(kw["name"])- def register_hook(self, name, fn): calls["hooks"].append(name)-- with patch.object(plugin.platform, "system", return_value="Windows"):- plugin.register(_Ctx())-- assert calls == {"tools": [], "cli": [], "hooks": []}# ---------------------------------------------------------------------------@@ -407,14 +393,5 @@ def test_realtime_session_cancel_response_when_disconnected():# ----------------------------------------------------------------------------def test_cmd_install_refuses_windows(capsys):- from plugins.google_meet.cli import _cmd_install-- with patch("plugins.google_meet.cli.platform" if False else "platform.system",- return_value="Windows"):- rc = _cmd_install(realtime=False, assume_yes=True)- assert rc == 1- out = capsys.readouterr().out- assert "Windows" in outdiff --git a/tests/plugins/test_honcho_client_config.py b/tests/plugins/test_honcho_client_config.pyindex 695da505dee..9d4b35e0463 100644--- a/tests/plugins/test_honcho_client_config.py+++ b/tests/plugins/test_honcho_client_config.py@@ -3,7 +3,6 @@import jsonimport osimport stat-from pathlib import Pathimport pytest@@ -60,14 +59,6 @@ class TestHonchoClientConfigAutoEnable:os.environ["HONCHO_API_KEY"] = env_key- def test_from_env_always_enabled(self, monkeypatch):- """from_env() should always set enabled=True."""- monkeypatch.setenv("HONCHO_API_KEY", "env-test-key")-- cfg = HonchoClientConfig.from_env()-- assert cfg.api_key == "env-test-key"- assert cfg.enabled is Truediff --git a/tests/plugins/test_kanban_dashboard_plugin.py b/tests/plugins/test_kanban_dashboard_plugin.pyindex c0e955e4311..0fb37f46ae0 100644--- a/tests/plugins/test_kanban_dashboard_plugin.py+++ b/tests/plugins/test_kanban_dashboard_plugin.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport importlib.utilimport jsonimport os-import reimport subprocessimport shutilimport sys@@ -180,17 +179,6 @@ def test_tenant_filter(client):assert total == 1-def test_dashboard_markdown_html_is_sanitized_before_render():- """Markdown rendering must sanitize HTML before dangerouslySetInnerHTML."""-- repo_root = Path(__file__).resolve().parents[2]- bundle = repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js"- js = bundle.read_text(encoding="utf-8")-- assert "function sanitizeMarkdownHtml(html)" in js- assert "MARKDOWN_ALLOWED_TAGS" in js- assert "sanitizeMarkdownHtml(renderMarkdown(props.source || \"\"))" in js- assert "dangerouslySetInnerHTML: { __html: renderMarkdown(props.source || \"\") }" not in js# ---------------------------------------------------------------------------@@ -743,79 +731,8 @@ def test_bulk_status_running_rejected(client):assert statuses.get(t["id"]) != "running"-def test_dashboard_done_actions_prompt_for_completion_summary():- """Behavioral coverage for the migrated ``requestDialog`` flow.-- Replaces the prior bundle-string-only assertion (which only proved the- rename landed). The dialog state machine at- ``plugins/kanban/dashboard/dist/index.js`` resolves with- ``{confirmed: true|false, summary?}``. Each migrated call site must- gate the dispatch on the resolved ``confirmed`` flag. This test- asserts that contract at two layers:-- 1. **Bundle cancel guards**: every migrated site gates on ``r.confirmed``- (or its subscripted alias ``r1.confirmed``/``r2.confirmed``) before- dispatching. We verify by counting the cancel-guard patterns +- cross-referencing against the 8 migrated sites listed in the PR- description.- 2. **Visual affordance**: every destructive ``requestDialog`` call marks- ``destructive: true`` so the host renders the destructive variant.-- The dispatch path itself (PATCH/DELETE actually firing on confirm, not- on cancel) is covered by the backend behavioral tests- ``test_dashboard_confirm_dispatches_expected_*`` and- ``test_dashboard_cancel_keeps_task_in_old_status`` below — together- they pin the contract end-to-end.- """- repo_root = Path(__file__).resolve().parents[2]- js = (repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js").read_text()- import re-- # Match ``if (!r.confirmed)``, ``if (!r1.confirmed)``, ``if (r.confirmed)``- # (positive-form gate). The bundle uses both polarities:- # - negative ``if (!r.confirmed) return null;`` in dialog flow bodies- # - positive ``if (r.confirmed) props.onDeleteBoard(...);`` in JSX handlers- cancel_guard_pattern = re.compile(- r"if\s*\(\s*!?\s*r\d?\.confirmed\s*\)",- re.IGNORECASE,- )- guards = cancel_guard_pattern.findall(js)- # 8 migrated sites per the PR description:- # moveTask (1), moveSelected (1), applyBulk (1), deleteTask (1),- # deleteSelected (1), archiveBoard (1), removeAttachment (1), doPatch (1).- # Plus performMoveTask callers (moveTask/moveSelected each have- # ``r1.confirmed`` + ``r2.confirmed`` for the two-stage flow) → up to- # 10 guards. Loose lower bound to avoid brittleness.- assert len(guards) >= 8, (- f"expected >= 8 `if (r?.confirmed)` cancel guards in bundle (one "- f"per migrated site, plus extras for two-stage flows); found {len(guards)}"- )-- # Visual affordance: every destructive requestDialog call must mark- # ``destructive: true`` so the host renders the destructive variant.- # deleteTask, deleteSelected, archiveBoard → at least 3.- destructive_call_count = js.count("destructive: true")- assert destructive_call_count >= 3, (- f"expected >= 3 `destructive: true` requestDialog calls (single "- f"delete, bulk delete, archive-board); found {destructive_call_count}"- )---def test_dashboard_cancel_keeps_task_in_old_status(client):- """Behavioral: the cancel branch of the dispatch path (no PATCH/DELETE- issued) must leave the task in its previous status. The cancel guard- lives in the bundle; this test pins the backend contract that the guard- relies on.- """- t = client.post("/api/plugins/kanban/tasks",- json={"title": "x"}).json()["task"]- # Tasks land in ``ready`` by default. No PATCH issued — simulating the- # cancel branch in the bundle.- assert t["status"] == "ready"- r = client.get(f"/api/plugins/kanban/tasks/{t['id']}")- assert r.json()["task"]["status"] == "ready"def test_dashboard_confirm_dispatches_expected_patch_body(client):@@ -841,88 +758,12 @@ def test_dashboard_confirm_dispatches_expected_patch_body(client):assert body.get("result") == "shipped"-def test_dashboard_confirm_dispatches_expected_delete(client):- """Behavioral: the DELETE call the bundle issues on confirm- (``fetchJSON(`${API}/tasks/${id}`, { method: 'DELETE' })``) must- succeed and remove the task.- """- t = client.post("/api/plugins/kanban/tasks",- json={"title": "x"}).json()["task"]- r = client.delete(f"/api/plugins/kanban/tasks/{t['id']}")- assert r.status_code == 200, r.text- # 404 on the now-deleted task confirms removal.- r2 = client.get(f"/api/plugins/kanban/tasks/{t['id']}")- assert r2.status_code == 404-def test_dashboard_surfaces_ready_blocked_error_inline():- """Regression for #26744: failed status transitions must be surfaced- inline, not swallowed. The drag/drop banner and the drawer's action- row each render the parsed API ``detail`` so operators see *why*- their click did nothing.- """- repo_root = Path(__file__).resolve().parents[2]- bundle = (- repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js"- ).read_text()-- # Helper that strips ``"409: {\"detail\":\"…\"}"`` down to the- # human-readable message before it lands in any banner.- assert "function parseApiErrorMessage(err)" in bundle- assert "parsed.detail" in bundle-- # Drag/drop banner now uses the parsed message instead of raw- # ``err.message`` so it no longer leaks HTTP plumbing.- assert "setError(tx(t, \"moveFailed\", \"Move failed: \") + parseApiErrorMessage(err))" in bundle-- # Drawer action row has its own visible error surface and clears it- # on success/refresh so stale failures don't follow the operator- # around.- assert "const [patchErr, setPatchErr] = useState(null);" in bundle- assert "setPatchErr(parseApiErrorMessage(e))" in bundle- assert "setPatchErr(null)" in bundle---def test_dashboard_dependency_selects_use_value_change_handler():- """Regression for the dependency selects in the task drawer: the- add-parent / add-child dropdowns must wire through the shared- selectChangeHandler helper so their value actually lands on the- underlying React state. Salvaged from #20019 @LeonSGP43.- """- repo_root = Path(__file__).resolve().parents[2]- bundle = (- repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js"- ).read_text()-- parent_select = (- 'value: newParent,\n'- ' className: "h-7 text-xs flex-1",\n'- ' }, selectChangeHandler(setNewParent))'- )- child_select = (- 'value: newChild,\n'- ' className: "h-7 text-xs flex-1",\n'- ' }, selectChangeHandler(setNewChild))'- )- assert parent_select in bundle- assert child_select in bundle-def test_dashboard_board_project_binding_is_exposed_in_ui():- """The board switcher's unbind action clears the binding through the- same REST contract the API tests pin (PATCH ``project_id: ""``); the- create/settings payload shapes themselves are covered behaviourally in- ``test_kanban_board_project_api.py``. The bundle has no build step, so- only the UI-side seam is pinned here.- """- repo_root = Path(__file__).resolve().parents[2]- bundle = (- repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js"- ).read_text(encoding="utf-8")- assert "hermes-kanban-board-project-unbind" in bundle- assert 'updateBoard(board, { project_id: "" })' in bundledef test_bulk_archive(client):@@ -1312,30 +1153,3 @@ def test_touch_card_tap_opens_instead_of_dragging():# ----------------------------------------------------------------------------def test_diag_severity_tokens_route_through_host_theme_tokens():- """The three ``--hermes-diag-*`` rungs must resolve through the host's- ``--color-warning`` / ``--color-destructive`` tokens (#115118). They were- literals declared on the consuming elements, which no theme override can- reach (the theme engine writes custom properties on ``<html>`` and an- element-level declaration always wins), so light themes rendered the- amber badge at 1.8:1 contrast with no way to fix it. Headless-Chrome- receipt: with the tokens set on ``<html>`` the computed colours follow;- with none set the shipped literals render unchanged.- """- css = (Path(__file__).resolve().parents[2] / "plugins" / "kanban" / "dashboard" / "dist" / "style.css").read_text(encoding="utf-8")- block = css[css.index("--hermes-diag-warning"):]- block = block[: block.index("}")]- # Parse the declarations rather than matching whitespace-exact substrings, so a- # reformat that keeps the computed value passes and a wrong token/fallback fails.- declared = {- name: (token, fallback)- for name, token, fallback in re.findall(- r"--hermes-diag-(warning|error|critical)\s*:\s*var\(\s*(--color-[\w-]+)\s*,\s*(#[0-9a-fA-F]{6})\s*\)\s*;",- block,- )- }- assert declared == {- "warning": ("--color-warning", "#ff9e3b"),- "error": ("--color-destructive", "#ff6b3d"),- "critical": ("--color-destructive", "#ff4d4d"),- }diff --git a/tests/plugins/test_kanban_dashboard_task_updated_hook.py b/tests/plugins/test_kanban_dashboard_task_updated_hook.pyindex 6f974e35679..d8a2b70a5e6 100644--- a/tests/plugins/test_kanban_dashboard_task_updated_hook.py+++ b/tests/plugins/test_kanban_dashboard_task_updated_hook.py@@ -87,23 +87,6 @@ def test_patch_priority_fires_task_updated(client, captured_updates):assert kw["board"]-def test_patch_priority_uses_shared_edit_task_primitive(client, monkeypatch):- """The dashboard reprioritizes through ``kanban_db.edit_task`` (one event- kind, one observer) instead of a duplicate raw UPDATE/INSERT (#117434)."""- from plugins.kanban.dashboard import plugin_api-- calls = []- real = plugin_api.kanban_db.edit_task-- def spy(conn, task_id, **kw):- calls.append((task_id, kw))- return real(conn, task_id, **kw)-- monkeypatch.setattr(plugin_api.kanban_db, "edit_task", spy)- tid = _make_task()- r = client.patch(f"/api/plugins/kanban/tasks/{tid}", json={"priority": 5})- assert r.status_code == 200- assert [(t, k["priority"]) for t, k in calls] == [(tid, 5)]def test_bulk_priority_fires_task_updated_per_task(client, captured_updates):tid1 = _make_task("a")diff --git a/tests/plugins/test_kanban_model_override.py b/tests/plugins/test_kanban_model_override.pyindex 25904790e69..61768c6606f 100644--- a/tests/plugins/test_kanban_model_override.py+++ b/tests/plugins/test_kanban_model_override.py@@ -108,10 +108,6 @@ def test_create_task_with_model_and_provider(conn):assert ev.payload["provider_override"] == "openrouter"-def test_migration_adds_provider_override_column(conn):- cols = {row["name"] for row in conn.execute("PRAGMA table_info(tasks)")}- assert "model_override" in cols- assert "provider_override" in cols# ---------------------------------------------------------------------------@@ -245,12 +241,6 @@ def test_reasoning_effort_survives_clearing_the_model(conn):assert t.reasoning_effort == "ultra"-def test_reasoning_effort_without_a_model_override(conn):- """A task may run the profile's OWN model at a different depth."""- tid = kb.create_task(conn, title="t", assignee="worker", reasoning_effort="low")- t = kb.get_task(conn, tid)- assert t.model_override is None- assert t.reasoning_effort == "low"def test_spawn_passes_reasoning_without_a_model(monkeypatch, tmp_path, conn):