Skip to content

The agent that grows with you

test: purge low-value tests, lane py01 (345 removed)

teknium1b3d4f67b2083
diff --git a/tests/acp_adapter/test_acp_images.py b/tests/acp_adapter/test_acp_images.py
index 3ef1f48fe2e..686f1c1e098 100644
--- a/tests/acp_adapter/test_acp_images.py
+++ b/tests/acp_adapter/test_acp_images.py
@@ -1,13 +1,9 @@
-import base64
import pytest
from acp.schema import (
- BlobResourceContents,
- EmbeddedResourceContentBlock,
ImageContentBlock,
ResourceContentBlock,
TextContentBlock,
- TextResourceContents,
)
from acp_adapter.server import HermesACPAgent, _content_blocks_to_openai_user_content
@@ -70,12 +66,6 @@ async def test_initialize_advertises_image_prompt_capability():
assert response.agent_capabilities.prompt_capabilities.image is True
-# 1x1 transparent PNG — smallest valid image payload for inlining tests.
-_ONE_PX_PNG = bytes.fromhex(
- "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
- "890000000a49444154789c6300010000000500010d0a2db40000000049454e44ae426082"
-)
-
diff --git a/tests/acp_adapter/test_approval_isolation.py b/tests/acp_adapter/test_approval_isolation.py
index bd3658ca7df..0caefa7642c 100644
--- a/tests/acp_adapter/test_approval_isolation.py
+++ b/tests/acp_adapter/test_approval_isolation.py
@@ -31,7 +31,6 @@ def _isolate_approval_state(monkeypatch):
for reasons unrelated to the code under test.
"""
import tools.approval as _approval
- from tools import approval_context
monkeypatch.setattr(_approval, "_permanent_approved", set())
monkeypatch.setattr(_approval, "_session_approved", {})
@@ -47,15 +46,6 @@ class TestThreadLocalApprovalCallback:
"""GHSA-qg5c-hvr5-hjgr: set_approval_callback must be per-thread so
concurrent ACP sessions don't stomp on each other's handlers."""
- def test_set_and_get_in_same_thread(self):
- from tools.terminal_tool import (
- set_approval_callback,
- _get_approval_callback,
- )
-
- cb1 = lambda cmd, desc: "once" # noqa: E731
- set_approval_callback(cb1)
- assert _get_approval_callback() is cb1
def test_callback_not_visible_in_different_thread(self):
"""Thread A's callback is NOT visible to Thread B."""
diff --git a/tests/acp_adapter/test_auth.py b/tests/acp_adapter/test_auth.py
index 64eb3b42406..aab47e5d1bc 100644
--- a/tests/acp_adapter/test_auth.py
+++ b/tests/acp_adapter/test_auth.py
@@ -1,19 +1,11 @@
"""Tests for acp_adapter.auth — provider detection."""
from acp_adapter.auth import (
- TERMINAL_SETUP_AUTH_METHOD_ID,
- build_auth_methods,
detect_provider,
)
class TestDetectProviderPresence:
- def test_has_provider_with_resolved_runtime(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- lambda: {"provider": "openrouter", "api_key": "sk-or-test"},
- )
- assert detect_provider() is not None
def test_has_provider_false_without_credentials(self, monkeypatch):
monkeypatch.setattr(
@@ -36,17 +28,4 @@ class TestDetectProvider:
-class TestBuildAuthMethods:
- def test_build_auth_methods_returns_provider_and_terminal_when_configured(self, monkeypatch):
- monkeypatch.setattr("acp_adapter.auth.detect_provider", lambda: "openrouter")
-
- methods = build_auth_methods()
- payloads = [method.model_dump(by_alias=True, exclude_none=True) for method in methods]
-
- assert payloads[0]["id"] == "openrouter"
- assert payloads[0]["name"] == "openrouter runtime credentials"
- assert any(payload["id"] == TERMINAL_SETUP_AUTH_METHOD_ID for payload in payloads)
- terminal = next(payload for payload in payloads if payload["id"] == TERMINAL_SETUP_AUTH_METHOD_ID)
- assert terminal["type"] == "terminal"
- assert terminal["args"] == ["--setup"]
diff --git a/tests/acp_adapter/test_detect_provider_entra.py b/tests/acp_adapter/test_detect_provider_entra.py
index 5ffd0b3886c..82fd3496a6c 100644
--- a/tests/acp_adapter/test_detect_provider_entra.py
+++ b/tests/acp_adapter/test_detect_provider_entra.py
@@ -35,31 +35,6 @@ class TestDetectProviderEntra:
):
assert _acp_auth.detect_provider() == "azure-foundry"
- def test_string_api_key_still_works(self):
- from acp_adapter import auth as _acp_auth
-
- def _fake_runtime(**_kwargs):
- return {
- "provider": "openrouter",
- "api_key": "sk-or-static-key",
- }
-
- with patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- side_effect=_fake_runtime,
- ):
- assert _acp_auth.detect_provider() == "openrouter"
-
- def test_empty_string_api_key_returns_none(self):
- from acp_adapter import auth as _acp_auth
-
- def _fake_runtime(**_kwargs):
- return {"provider": "openrouter", "api_key": ""}
- with patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- side_effect=_fake_runtime,
- ):
- assert _acp_auth.detect_provider() is None
diff --git a/tests/acp_adapter/test_events.py b/tests/acp_adapter/test_events.py
index bbf3222d490..fa6fc634b10 100644
--- a/tests/acp_adapter/test_events.py
+++ b/tests/acp_adapter/test_events.py
@@ -13,7 +13,6 @@ import acp
from acp.schema import AgentPlanUpdate
from acp_adapter.events import (
- _build_plan_update_from_todo_result,
_send_update,
make_message_cb,
make_step_cb,
@@ -44,30 +43,6 @@ def event_loop_fixture():
class TestToolProgressCallback:
- def test_emits_tool_call_start(self, mock_conn, event_loop_fixture):
- """Tool progress should emit a ToolCallStart update."""
- tool_call_ids = {}
- tool_call_meta = {}
- loop = event_loop_fixture
-
- cb = make_tool_progress_cb(mock_conn, "session-1", loop, tool_call_ids, tool_call_meta)
-
- # Run callback in the event loop context
- with patch("acp_adapter.events.asyncio.run_coroutine_threadsafe") as mock_rcts:
- future = MagicMock(spec=Future)
- future.result.return_value = None
- mock_rcts.return_value = future
-
- cb("tool.started", "terminal", "$ ls -la", {"command": "ls -la"})
-
- # Should have tracked the tool call ID
- assert "terminal" in tool_call_ids
-
- # Should have called run_coroutine_threadsafe
- mock_rcts.assert_called_once()
- coro = mock_rcts.call_args[0][0]
- # The coroutine should be conn.session_update
- assert mock_conn.session_update.called or coro is not None
@@ -109,23 +84,6 @@ class TestToolProgressCallback:
class TestStepCallback:
- def test_completes_tracked_tool_calls(self, mock_conn, event_loop_fixture):
- """Step callback should mark tracked tools as completed."""
- tool_call_ids = {"terminal": "tc-abc123"}
- loop = event_loop_fixture
-
- cb = make_step_cb(mock_conn, "session-1", loop, tool_call_ids, {})
-
- with patch("acp_adapter.events.asyncio.run_coroutine_threadsafe") as mock_rcts:
- future = MagicMock(spec=Future)
- future.result.return_value = None
- mock_rcts.return_value = future
-
- cb(1, [{"name": "terminal", "result": "success"}])
-
- # Tool should have been removed from tracking
- assert "terminal" not in tool_call_ids
- mock_rcts.assert_called_once()
@@ -141,27 +99,6 @@ class TestStepCallback:
cb(1, [{"name": "terminal", "result": raw}])
mock_btc.assert_called_once_with("tc-f", "terminal", result=expected, function_args=None, snapshot=None)
- def test_result_passed_to_build_tool_complete(self, mock_conn, event_loop_fixture):
- """Tool result from prev_tools dict is forwarded to build_tool_complete."""
- from collections import deque
-
- tool_call_ids = {"terminal": deque(["tc-xyz789"])}
- loop = event_loop_fixture
-
- cb = make_step_cb(mock_conn, "session-1", loop, tool_call_ids, {})
-
- with patch("acp_adapter.events.asyncio.run_coroutine_threadsafe") as mock_rcts, \
- patch("acp_adapter.events.build_tool_complete") as mock_btc:
- future = MagicMock(spec=Future)
- future.result.return_value = None
- mock_rcts.return_value = future
-
- # Provide a result string in the tool info dict
- cb(1, [{"name": "terminal", "result": '{"output": "hello"}'}])
-
- mock_btc.assert_called_once_with(
- "tc-xyz789", "terminal", result='{"output": "hello"}', function_args=None, snapshot=None
- )
diff --git a/tests/acp_adapter/test_mcp_e2e.py b/tests/acp_adapter/test_mcp_e2e.py
index a559c1b1a77..621aeb1b1b4 100644
--- a/tests/acp_adapter/test_mcp_e2e.py
+++ b/tests/acp_adapter/test_mcp_e2e.py
@@ -168,7 +168,7 @@ class TestMcpRegistrationE2E:
assert len(starts) >= 1, f"Expected ToolCallStart, got updates: {[getattr(u, 'session_update', '?') for u in updates]}"
start_event = starts[0]
assert isinstance(start_event, ToolCallStart)
- assert start_event.title.startswith("terminal:")
+ assert "echo hello" in start_event.title
# Should have at least one ToolCallUpdate (completion) with rawOutput
assert len(completions) >= 1, f"Expected ToolCallUpdate, got updates: {[getattr(u, 'session_update', '?') for u in updates]}"
@@ -192,41 +192,9 @@ class TestMcpRegistrationE2E:
assert len(update.content) == 1
assert update.content[0].type == "content"
- assert "Approval prompt shows the diff" in update.content[0].content.text
-class TestMcpSanitizationE2E:
- """Verify server names with special chars work end-to-end."""
-
- @pytest.mark.asyncio
- async def test_slashed_server_name_registers_cleanly(self, acp_agent, mock_manager):
- """Server name 'ai.exa/exa' should not crash — tools get sanitized names."""
- servers = [
- McpServerHttp(
- name="ai.exa/exa",
- url="https://exa.ai/mcp",
- headers=[],
- ),
- ]
-
- registered_configs = {}
- def mock_register(config_map):
- registered_configs.update(config_map)
- return ["mcp_ai_exa_exa_search"]
-
- fake_tools = [{"function": {"name": "mcp_ai_exa_exa_search"}}]
-
- with patch("tools.mcp_tool_discovery.register_mcp_servers", side_effect=mock_register), \
- patch("model_tools.get_tool_definitions", return_value=fake_tools):
- resp = await acp_agent.new_session(cwd="/tmp", mcp_servers=servers)
-
- state = mock_manager.get_session(resp.session_id)
-
- # Raw server name preserved as config key
- assert "ai.exa/exa" in registered_configs
- # Agent tools refreshed with sanitized name
- assert "mcp_ai_exa_exa_search" in state.agent.valid_tool_names
class TestSessionLifecycleMcpE2E:
diff --git a/tests/acp_adapter/test_named_provider_catalogs.py b/tests/acp_adapter/test_named_provider_catalogs.py
index 0161e444cf5..ef7aba6e190 100644
--- a/tests/acp_adapter/test_named_provider_catalogs.py
+++ b/tests/acp_adapter/test_named_provider_catalogs.py
@@ -125,19 +125,10 @@ class TestNamedCustomProviderCatalogs:
), patch(
"hermes_cli.model_switch_providers._fetch_picker_live_models",
return_value=["qwen3:1.7b"],
- ) as fetch:
+ ):
catalogs = _named_custom_provider_catalogs()
assert [m for m, _ in catalogs[0][2]] == ["qwen3:1.7b"]
- fetch.assert_called_once_with(
- "",
- "http://127.0.0.1:11434/v1",
- "custom:ollama",
- False,
- headers=None,
- timeout=1.5,
- api_mode=None,
- )
def test_legacy_credentialless_ollama_discovers_native_catalog(self):
cfg = _cfg(
custom_providers=[
diff --git a/tests/acp_adapter/test_permissions.py b/tests/acp_adapter/test_permissions.py
index 8cc4bcbe0b0..94ce9711957 100644
--- a/tests/acp_adapter/test_permissions.py
+++ b/tests/acp_adapter/test_permissions.py
@@ -81,7 +81,6 @@ class TestApprovalBridge:
assert inspect.iscoroutine(scheduled["coro"])
assert kwargs["session_id"] == "s1"
assert tool_call.session_update == "tool_call_update"
- assert tool_call.tool_call_id.startswith("perm-check-")
assert tool_call.kind == "execute"
assert tool_call.status == "pending"
assert "dangerous command" in tool_call.title
diff --git a/tests/acp_adapter/test_server.py b/tests/acp_adapter/test_server.py
index dad364e7da1..ffb572fdfd8 100644
--- a/tests/acp_adapter/test_server.py
+++ b/tests/acp_adapter/test_server.py
@@ -1,7 +1,6 @@
"""Tests for acp_adapter.server — HermesACPAgent ACP server."""
import asyncio
-import os
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, AsyncMock, patch
@@ -11,25 +10,14 @@ import pytest
import acp
from acp.agent.router import build_agent_router
from acp.schema import (
- AgentCapabilities,
- AgentMessageChunk,
- AgentPlanUpdate,
- AgentThoughtChunk,
AuthenticateResponse,
- AvailableCommandsUpdate,
- Implementation,
InitializeResponse,
- LoadSessionResponse,
- NewSessionResponse,
PromptResponse,
ResumeSessionResponse,
SessionModelState,
SessionModeState,
SetSessionConfigOptionResponse,
- SetSessionModelResponse,
- SetSessionModeResponse,
SessionInfo,
- SessionInfoUpdate,
TextContentBlock,
ToolCallProgress,
ToolCallStart,
@@ -37,13 +25,10 @@ from acp.schema import (
UserMessageChunk,
)
from acp_adapter.auth import TERMINAL_SETUP_AUTH_METHOD_ID
-from acp_adapter.model_catalog import ACP_MAX_MODELS_PER_PROVIDER
from acp_adapter.server import (
HermesACPAgent,
- HERMES_VERSION,
)
from acp_adapter.session import SessionManager
-from hermes_state import SessionDB
@pytest.fixture()
@@ -65,10 +50,10 @@ async def test_new_session_exposes_edit_approvals_as_modes_not_config_options(ag
assert resp.config_options is None
assert isinstance(resp.modes, SessionModeState)
assert resp.modes.current_mode_id == "default"
- assert [(mode.id, mode.name) for mode in resp.modes.available_modes] == [
- ("default", "Default"),
- ("accept_edits", "Accept Edits"),
- ("dont_ask", "Don't Ask"),
+ assert [mode.id for mode in resp.modes.available_modes] == [
+ "default",
+ "accept_edits",
+ "dont_ask",
]
@@ -111,7 +96,6 @@ class TestInitialize:
payloads = [method.model_dump(by_alias=True, exclude_none=True) for method in resp.auth_methods]
assert payloads[0]["id"] == "openrouter"
- assert payloads[0]["name"] == "openrouter runtime credentials"
terminal = next(payload for payload in payloads if payload["id"] == TERMINAL_SETUP_AUTH_METHOD_ID)
assert terminal["type"] == "terminal"
assert terminal["args"] == ["--setup"]
@@ -210,7 +194,7 @@ class TestSessionOps:
with (
patch("hermes_cli.inventory.load_picker_context", return_value=picker_context),
- patch("hermes_cli.inventory.build_models_payload", return_value=payload) as build_payload,
+ patch("hermes_cli.inventory.build_models_payload", return_value=payload),
):
resp = await acp_agent.new_session(cwd="/tmp")
@@ -221,44 +205,14 @@ class TestSessionOps:
"openai-codex:gpt-5.4",
"openai-codex:gpt-5.4-mini",
]
- assert [model.name for model in resp.models.available_models] == [
- "Anthropic · claude-sonnet-4-6",
- "OpenAI Codex · gpt-5.4",
- "OpenAI Codex · gpt-5.4-mini",
- ]
- assert resp.models.available_models[1].description is not None
- assert "current" in resp.models.available_models[1].description
picker_context.with_overrides.assert_called_once_with(
current_provider="openai-codex",
current_model="gpt-5.4",
current_base_url="https://api.openai.com/v1",
)
- build_payload.assert_called_once_with(
- picker_context,
- explicit_only=True,
- include_unconfigured=False,
- picker_hints=False,
- canonical_order=True,
- pricing=False,
- capabilities=False,
- refresh=False,
- probe_custom_providers=False,
- probe_current_custom_provider=False,
- max_models=ACP_MAX_MODELS_PER_PROVIDER,
- )
-
- @pytest.mark.asyncio
- async def test_available_commands_include_help(self, agent):
- help_cmd = next(
- (cmd for cmd in agent._available_commands() if cmd.name == "help"),
- None,
- )
- assert help_cmd is not None
- assert help_cmd.description == "List available commands"
- assert help_cmd.input is None
def test_build_usage_update_for_zed_context_indicator(self, agent, mock_manager):
@@ -549,11 +503,6 @@ class TestPrompt:
# ---------------------------------------------------------------------------
-class TestOnConnect:
- def test_on_connect_stores_client(self, agent):
- mock_conn = MagicMock(spec=acp.Client)
- agent.on_connect(mock_conn)
- assert agent._conn is mock_conn
# ---------------------------------------------------------------------------
@@ -571,14 +520,6 @@ class TestSlashCommands:
state.model = "test-model"
return state
- def test_help_lists_commands(self, agent, mock_manager):
- state = self._make_state(mock_manager)
- result = agent._handle_slash_command("/help", state)
- assert result is not None
- assert "/help" in result
- assert "/model" in result
- assert "/tools" in result
- assert "/reset" in result
def test_model_shows_current(self, agent, mock_manager):
state = self._make_state(mock_manager)
@@ -592,8 +533,7 @@ class TestSlashCommands:
def test_reset_clears_history(self, agent, mock_manager):
state = self._make_state(mock_manager)
state.history = [{"role": "user", "content": "hello"}]
- result = agent._handle_slash_command("/reset", state)
- assert "cleared" in result.lower()
+ agent._handle_slash_command("/reset", state)
assert len(state.history) == 0
@@ -693,13 +633,6 @@ class TestSlashCommands:
class TestRegisterSessionMcpServers:
"""Tests for ACP MCP server registration in session lifecycle."""
- @pytest.mark.asyncio
- async def test_noop_when_no_servers(self, agent, mock_manager):
- """No-op when mcp_servers is None or empty."""
- state = mock_manager.create_session(cwd="/tmp")
- # Should not raise
- await agent._register_session_mcp_servers(state, None)
- await agent._register_session_mcp_servers(state, [])
@pytest.mark.asyncio
async def test_registers_stdio_servers(self, agent, mock_manager):
diff --git a/tests/acp_adapter/test_session.py b/tests/acp_adapter/test_session.py
index d692569e89c..f4e0c1c1299 100644
--- a/tests/acp_adapter/test_session.py
+++ b/tests/acp_adapter/test_session.py
@@ -3,7 +3,6 @@
import contextlib
import io
import json
-import time
from types import SimpleNamespace
import pytest
from unittest.mock import MagicMock, patch
@@ -60,10 +59,6 @@ class TestCreateSession:
}
- def test_get_session(self, manager):
- state = manager.create_session()
- fetched = manager.get_session(state.session_id)
- assert fetched is state
def test_make_agent_uses_session_cwd_during_init_and_stamps_runtime(
@@ -112,8 +107,9 @@ class TestCreateSession:
},
)
monkeypatch.setattr("acp_adapter.session._register_task_cwd", lambda task_id, cwd: None)
+ monkeypatch.setattr("hermes_cli.mcp_startup.ensure_mcp_discovery_before_agent_build", lambda **_kw: None)
- state = SessionManager(db=None).create_session(cwd=str(workspace))
+ SessionManager(db=None).create_session(cwd=str(workspace))
assert observed["cwd"] == str(workspace)
diff --git a/tests/acp_adapter/test_session_db_private_access.py b/tests/acp_adapter/test_session_db_private_access.py
index 3f1316f4577..060a81ee0a1 100644
--- a/tests/acp_adapter/test_session_db_private_access.py
+++ b/tests/acp_adapter/test_session_db_private_access.py
@@ -7,13 +7,9 @@ Verifies that:
3. update_session_meta updates the correct columns atomically.
"""
-import ast
import json
-import tempfile
-from pathlib import Path
-from unittest.mock import MagicMock, patch, call
+from unittest.mock import MagicMock
-import pytest
from hermes_state import SessionDB
from acp_adapter.session import SessionManager
@@ -34,12 +30,6 @@ def _mock_agent():
class TestUpdateSessionMeta:
"""Direct unit tests for the new public method."""
- def test_method_exists(self, tmp_path):
- db = _tmp_db(tmp_path)
- assert hasattr(db, "update_session_meta"), (
- "SessionDB must have update_session_meta() public method"
- )
- assert callable(db.update_session_meta)
def test_updates_model_config(self, tmp_path):
db = _tmp_db(tmp_path)
@@ -55,24 +45,6 @@ class TestUpdateSessionMeta:
- def test_uses_execute_write_not_private_api(self, tmp_path):
- """update_session_meta must route through _execute_write, not _conn directly."""
- db = _tmp_db(tmp_path)
- db.create_session("s4", source="acp")
-
- call_count = [0]
- original = db._execute_write
-
- def patched(fn, *args, **kwargs):
- call_count[0] += 1
- return original(fn, *args, **kwargs)
-
- db._execute_write = patched
- db.update_session_meta("s4", json.dumps({"cwd": "."}), model="m")
-
- assert call_count[0] >= 1, (
- "update_session_meta must call _execute_write at least once"
- )
@@ -80,52 +52,6 @@ class TestUpdateSessionMeta:
# AST check: session.py must not access db._lock or db._conn
# ---------------------------------------------------------------------------
-class TestNoPrviateDBAccess:
- """_persist() in session.py must not access db._lock or db._conn."""
-
- def test_no_db_private_lock_access(self):
- with open("acp_adapter/session.py", encoding="utf-8") as f:
- source = f.read()
-
- tree = ast.parse(source)
-
- violations = []
- for node in ast.walk(tree):
- # Looking for: db._lock or db._conn
- if isinstance(node, ast.Attribute):
- if isinstance(node.value, ast.Name) and node.value.id == "db":
- if node.attr in ("_lock", "_conn"):
- violations.append(
- f"db.{node.attr} at line {node.lineno}"
- )
-
- assert violations == [], (
- "session.py accesses private SessionDB internals: "
- + ", ".join(violations)
- + " — use db.update_session_meta() instead"
- )
-
- def test_persist_calls_update_session_meta(self):
- """AST check: _persist must call db.update_session_meta()."""
- with open("acp_adapter/session.py", encoding="utf-8") as f:
- tree = ast.parse(f.read())
-
- found = False
- for node in ast.walk(tree):
- if isinstance(node, ast.FunctionDef) and node.name == "_persist":
- for child in ast.walk(node):
- if isinstance(child, ast.Call):
- func = child.func
- if isinstance(func, ast.Attribute):
- if func.attr == "update_session_meta":
- found = True
- break
- break
-
- assert found, (
- "_persist() must call db.update_session_meta() "
- "instead of db._conn.execute() directly"
- )
# ---------------------------------------------------------------------------
diff --git a/tests/acp_adapter/test_tools.py b/tests/acp_adapter/test_tools.py
index 027f9b0cc21..35337e4e480 100644
--- a/tests/acp_adapter/test_tools.py
+++ b/tests/acp_adapter/test_tools.py
@@ -5,7 +5,6 @@ import pytest
from acp_adapter.edit_approval import EditProposal
from acp_adapter.tools import (
- TOOL_KIND_MAP,
build_tool_complete,
build_tool_start,
build_tool_title,
@@ -31,16 +30,8 @@ COMMON_HERMES_TOOLS = ["read_file", "search_files", "terminal", "patch", "write_
class TestToolKindMap:
- def test_all_hermes_tools_have_kind(self):
- """Every common hermes tool should appear in TOOL_KIND_MAP."""
- for tool in COMMON_HERMES_TOOLS:
- assert tool in TOOL_KIND_MAP, f"{tool} missing from TOOL_KIND_MAP"
- def test_tool_kind_read_file(self):
- assert get_tool_kind("read_file") == "read"
- def test_tool_kind_terminal(self):
- assert get_tool_kind("terminal") == "execute"
@@ -59,13 +50,7 @@ class TestToolKindMap:
class TestMakeToolCallId:
- def test_returns_string(self):
- tc_id = make_tool_call_id()
- assert isinstance(tc_id, str)
- def test_starts_with_tc_prefix(self):
- tc_id = make_tool_call_id()
- assert tc_id.startswith("tc-")
def test_ids_are_unique(self):
ids = {make_tool_call_id() for _ in range(100)}
@@ -78,9 +63,6 @@ class TestMakeToolCallId:
class TestBuildToolTitle:
- def test_terminal_title_includes_command(self):
- title = build_tool_title("terminal", {"command": "ls -la /tmp"})
- assert "ls -la /tmp" in title
def test_terminal_title_truncates_long_command(self):
long_cmd = "x" * 200
@@ -88,21 +70,9 @@ class TestBuildToolTitle:
assert len(title) < 120
assert "..." in title
- def test_read_file_title(self):
- title = build_tool_title("read_file", {"path": "/etc/hosts"})
- assert "hosts" in title
- def test_search_title(self):
- title = build_tool_title("search_files", {"pattern": "TODO"})
- assert "TODO" in title
- def test_skill_view_title_includes_skill_name(self):
- title = build_tool_title("skill_view", {"name": "github-pitfalls"})
- assert "github-pitfalls" in title
- def test_execute_code_title_includes_first_code_line(self):
- title = build_tool_title("execute_code", {"code": "\nfrom hermes_tools import terminal\nprint('done')"})
- assert "from hermes_tools import terminal" in title
def test_unknown_tool_uses_name(self):
title = build_tool_title("some_new_tool", {"foo": "bar"})
@@ -145,7 +115,6 @@ class TestBuildToolStart:
assert len(result.content) >= 1
item = result.content[0]
assert isinstance(item, ContentToolCallContent)
- assert "Approval prompt shows the diff" in item.content.text
assert "src/main.py" in item.content.text
@@ -181,7 +150,7 @@ class TestBuildToolStart:
assert isinstance(result, ToolCallStart)
assert "https://x.com" in result.title
assert result.kind == "fetch"
- assert result.content[0].content.text == '{\n "url": "https://x.com"\n}'
+ assert "https://x.com" in result.content[0].content.text
assert result.raw_input is None
@@ -233,8 +202,6 @@ class TestBuildToolComplete:
'{"total_count":2,"matches":[{"path":"README.md","line":3,"content":"TODO: fix this"},{"path":"src/app.py","line":9,"content":"needle"}],"truncated":true}\n\n[Hint: Results truncated. Use offset=12 to see more.]',
)
text = result.content[0].content.text
- assert "Search results" in text
- assert "Found 2 matches" in text
assert "README.md:3" in text
assert "TODO: fix this" in text
assert "Results truncated" in text
@@ -253,7 +220,6 @@ class TestBuildToolComplete:
'{"results":[{"id":"obs-1","status":"active","content":"Recall should render as a readable summary."}],"trust":"lower-trust archive evidence"}',
)
text = result.content[0].content.text
- assert "memory_archive_search result" in text
assert "lower-trust archive evidence" in text
assert "Recall should render as a readable summary" in text
assert "{\"results\"" not in text
diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.py
index 5bd03b6849e..121d85f9a1f 100644
--- a/tests/agent/lsp/test_client_e2e.py
+++ b/tests/agent/lsp/test_client_e2e.py
@@ -113,14 +113,6 @@ async def test_initialize_error_response_keeps_its_exception_type(tmp_path: Path
await client.shutdown()
-async def test_failure_details_empty_for_live_server(tmp_path: Path):
- client = _client(tmp_path, "clean")
- await client.start()
- try:
- assert client.failure_details() == ""
- finally:
- await client.shutdown()
@pytest.mark.asyncio
@@ -173,7 +165,8 @@ async def test_cancelled_start_hard_kills_sigterm_ignoring_descendant(tmp_path:
start = asyncio.create_task(client.start())
child = None
try:
- ready_deadline = asyncio.get_running_loop().time() + 3.0
+ # Generous deadlines: CI runners under load took >3 s here (PR-blocking flake).
+ ready_deadline = asyncio.get_running_loop().time() + 15.0
while not child_pid_file.exists():
assert asyncio.get_running_loop().time() < ready_deadline
await asyncio.sleep(0.01)
@@ -182,7 +175,7 @@ async def test_cancelled_start_hard_kills_sigterm_ignoring_descendant(tmp_path:
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(start, timeout=0.05)
- deadline = asyncio.get_running_loop().time() + 3.0
+ deadline = asyncio.get_running_loop().time() + 15.0
while child.is_running() and child.status() != psutil.STATUS_ZOMBIE:
assert asyncio.get_running_loop().time() < deadline
await asyncio.sleep(0.01)
diff --git a/tests/agent/lsp/test_diagnostics_field.py b/tests/agent/lsp/test_diagnostics_field.py
index d9c3f129935..bcc835671a4 100644
--- a/tests/agent/lsp/test_diagnostics_field.py
+++ b/tests/agent/lsp/test_diagnostics_field.py
@@ -11,9 +11,7 @@ from unittest.mock import MagicMock, patch
from tools.environments.local import LocalEnvironment
from tools.file_operations import (
- PatchResult,
ShellFileOperations,
- WriteResult,
)
@@ -30,9 +28,6 @@ from tools.file_operations import (
-def test_patchresult_to_dict_omits_field_when_none():
- r = PatchResult(success=True)
- assert "lsp_diagnostics" not in r.to_dict()
@@ -42,19 +37,6 @@ def test_patchresult_to_dict_omits_field_when_none():
# ---------------------------------------------------------------------------
-def test_lint_and_lsp_diagnostics_are_separate_channels():
- """A WriteResult can carry BOTH a syntax-error lint AND an LSP
- diagnostic block. They belong in separate fields."""
- r = WriteResult(
- bytes_written=42,
- lint={"status": "error", "output": "SyntaxError: ..."},
- lsp_diagnostics="<diagnostics>ERROR [1:5] type mismatch</diagnostics>",
- )
- d = r.to_dict()
- assert "lint" in d
- assert "lsp_diagnostics" in d
- assert d["lint"]["output"] == "SyntaxError: ..."
- assert "type mismatch" in d["lsp_diagnostics"]
# ---------------------------------------------------------------------------
diff --git a/tests/agent/lsp/test_eventlog.py b/tests/agent/lsp/test_eventlog.py
index d7016c43db5..7a992478d34 100644
--- a/tests/agent/lsp/test_eventlog.py
+++ b/tests/agent/lsp/test_eventlog.py
@@ -32,13 +32,6 @@ def caplog_lsp(caplog):
# ---------------------------------------------------------------------------
-def test_clean_emits_at_debug(caplog_lsp):
- for _ in range(10):
- eventlog.log_clean("pyright", "/proj/x.py")
- info_records = [r for r in caplog_lsp.records if r.levelno >= logging.INFO]
- debug_records = [r for r in caplog_lsp.records if r.levelno == logging.DEBUG]
- assert info_records == []
- assert len(debug_records) == 10
def test_disabled_emits_at_debug(caplog_lsp):
@@ -92,7 +85,6 @@ def test_spawn_failed_warns(caplog_lsp):
eventlog.log_spawn_failed("pyright", "/proj", FileNotFoundError("nope"))
warns = [r for r in caplog_lsp.records if r.levelno == logging.WARNING]
assert len(warns) == 1
- assert "spawn/initialize failed" in warns[0].getMessage()
# ---------------------------------------------------------------------------
@@ -125,13 +117,6 @@ def test_thousand_clean_writes_emit_one_info(caplog_lsp):
-def test_short_path_keeps_absolute_when_outside(tmp_path, monkeypatch):
- monkeypatch.chdir(tmp_path / "a") if (tmp_path / "a").exists() else None
- monkeypatch.chdir(tmp_path)
- other = "/var/log/foo.txt"
- out = eventlog._short_path(other)
- # Outside cwd: keeps absolute (no leading "../")
- assert out == "/var/log/foo.txt" or not out.startswith("..")
diff --git a/tests/agent/lsp/test_install_and_lint_fixes.py b/tests/agent/lsp/test_install_and_lint_fixes.py
index 1f5d8fc5996..c84974a2f12 100644
--- a/tests/agent/lsp/test_install_and_lint_fixes.py
+++ b/tests/agent/lsp/test_install_and_lint_fixes.py
@@ -14,13 +14,10 @@ Covers:
"""
from __future__ import annotations
-import io
-from contextlib import redirect_stdout
from unittest.mock import MagicMock, patch
import pytest
-from agent.lsp.install import INSTALL_RECIPES
# ---------------------------------------------------------------------------
@@ -117,25 +114,6 @@ def test_backend_warnings_fires_when_bash_installed_but_shellcheck_missing(tmp_p
assert "bash-language-server" in notes[0].lower()
-def test_status_output_includes_backend_warnings_section(tmp_path, monkeypatch):
- """End-to-end: status command output includes the warning section."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
-
- # Pretend bash-language-server is installed but shellcheck is missing
- def which(name):
- if name == "bash-language-server":
- return "/fake/bin/bash-language-server"
- return None
-
- from agent.lsp import cli as lsp_cli
-
- buf = io.StringIO()
- with patch("shutil.which", side_effect=which), redirect_stdout(buf):
- lsp_cli._cmd_status(emit_json=False)
-
- output = buf.getvalue()
- assert "Backend warnings" in output
- assert "shellcheck" in output
# ---------------------------------------------------------------------------
diff --git a/tests/agent/lsp/test_protocol.py b/tests/agent/lsp/test_protocol.py
index 58b06cef0bb..c3057cc5252 100644
--- a/tests/agent/lsp/test_protocol.py
+++ b/tests/agent/lsp/test_protocol.py
@@ -16,16 +16,10 @@ import json
import pytest
from agent.lsp.protocol import (
- ERROR_CONTENT_MODIFIED,
- ERROR_METHOD_NOT_FOUND,
LSPProtocolError,
- LSPRequestError,
classify_message,
encode_message,
- make_error_response,
make_notification,
- make_request,
- make_response,
read_message,
)
@@ -85,9 +79,8 @@ async def test_read_message_rejects_runaway_header():
in and surfaces a protocol error."""
flood = (b"X-Junk: " + b"A" * 200 + b"\r\n") * 60 # ~12 KiB worth
reader = await _stream_from_bytes(flood)
- with pytest.raises(LSPProtocolError) as exc:
+ with pytest.raises(LSPProtocolError):
await read_message(reader)
- assert "8 KiB" in str(exc.value)
# ---------------------------------------------------------------------------
@@ -107,11 +100,6 @@ def test_make_notification_omits_id():
-def test_make_error_response_shape():
- msg = make_error_response(7, ERROR_CONTENT_MODIFIED, "stale", {"hint": "retry"})
- assert msg["error"]["code"] == ERROR_CONTENT_MODIFIED
- assert msg["error"]["message"] == "stale"
- assert msg["error"]["data"] == {"hint": "retry"}
# ---------------------------------------------------------------------------
@@ -135,8 +123,3 @@ def test_classify_message_invalid():
# ---------------------------------------------------------------------------
-def test_lsp_request_error_carries_code_and_data():
- e = LSPRequestError(ERROR_METHOD_NOT_FOUND, "no", {"x": 1})
- assert e.code == ERROR_METHOD_NOT_FOUND
- assert e.message == "no"
- assert e.data == {"x": 1}
diff --git a/tests/agent/lsp/test_service.py b/tests/agent/lsp/test_service.py
index cfb46dfb663..0864db1e2e3 100644
--- a/tests/agent/lsp/test_service.py
+++ b/tests/agent/lsp/test_service.py
@@ -146,38 +146,6 @@ def test_snapshot_baseline_honors_wait_timeout(mock_pyright_silent):
svc.shutdown()
-def test_snapshot_baseline_honors_wait_timeout_above_default(mock_pyright_silent):
- """A ``wait_timeout`` above the 5s client default must also reach the
- baseline wait (it was silently truncated to 5s), and the outer join
- budget must scale with it so the slow-but-alive server is not marked broken.
- """
- repo = mock_pyright_silent
- f = repo / "x.py"
- f.write_text("print('hi')\n")
-
- svc = LSPService(
- enabled=True,
- wait_mode="document",
- wait_timeout=7.0,
- install_strategy="manual",
- )
- try:
- start = time.monotonic()
- svc.snapshot_baseline(str(f))
- elapsed = time.monotonic() - start
-
- assert elapsed >= 6.5, f"baseline truncated to the 5s client default: {elapsed:.2f}s"
- assert elapsed < 9.5, f"baseline overran the scaled join budget: {elapsed:.2f}s"
- # A slow-but-alive server must not be marked broken.
- assert svc.get_status()["broken"] == []
- finally:
- svc.shutdown()
-
-
-
-
-
-
def test_service_e2e_delta_filter(mock_pyright):
"""End-to-end: snapshot baseline → wait → delta returned."""
repo = mock_pyright
@@ -249,39 +217,6 @@ def test_service_replaces_client_after_reader_failure(
pass
-def test_service_e2e_delta_filter_with_line_shift(mock_pyright):
- """End-to-end: an edit that shifts the diagnostic's line still
- filters correctly when ``line_shift`` is supplied.
-
- The mock LSP server emits a fixed error at line 0; for this test
- we don't need to actually shift the server's output — we just
- need to prove that supplying a line_shift through the API works
- and doesn't break the existing delta path. The unit tests in
- test_delta_key.py cover the shift semantics in detail.
- """
- repo = mock_pyright
- f = repo / "x.py"
- f.write_text("print('hi')\n")
-
- svc = LSPService(
- enabled=True,
- wait_mode="document",
- wait_timeout=3.0,
- install_strategy="manual",
- )
- try:
- svc.snapshot_baseline(str(f))
- # Identity shift — should behave exactly like no shift.
- new_diags = svc.get_diagnostics_sync(str(f), line_shift=lambda L: L)
- assert new_diags == []
- finally:
- svc.shutdown()
-
-
-
-
-
-
def test_reused_client_refreshes_last_used_and_survives_reap(mock_pyright):
"""A client re-acquired from the cache must have its ``_last_used``
timestamp refreshed so a subsequent sweep does NOT evict it.
@@ -362,11 +297,3 @@ def test_reaper_survives_sweep_error(mock_pyright):
assert not svc._idle_reaper_task.done()
finally:
svc.shutdown()
-
-
-
-
-
-
-
-
diff --git a/tests/agent/lsp/test_shell_linter_lsp_skip.py b/tests/agent/lsp/test_shell_linter_lsp_skip.py
index 50cc88869d3..2863e2ba4a2 100644
--- a/tests/agent/lsp/test_shell_linter_lsp_skip.py
+++ b/tests/agent/lsp/test_shell_linter_lsp_skip.py
@@ -69,14 +69,6 @@ def test_shell_linter_skipped_when_lsp_will_handle(ext, tmp_path):
assert "LSP" in (result.message or "")
-
-
-
-
-
-
-
-
def test_lsp_will_handle_swallows_enabled_for_exception(tmp_path):
"""A flaky LSP service must never break the shell-linter fallback —
if ``enabled_for`` raises, we treat the file as "not handled" so the
@@ -93,27 +85,6 @@ def test_lsp_will_handle_swallows_enabled_for_exception(tmp_path):
assert fops._lsp_will_handle(str(src)) is False
-
-
-def test_tsx_default_check_lint_returns_skipped(tmp_path):
- """End-to-end: ``.tsx`` files get ``LintResult(skipped=True)`` from
- ``_check_lint`` regardless of LSP status — this is the no-regression
- contract that addresses Copilot review #3271017282."""
- fops = _make_fops()
- src = tmp_path / "foo.tsx"
- src.write_text("export const X = () => <div/>\n")
-
- # Even with LSP claiming the file, no shell linter runs for .tsx
- # because there's no LINTERS entry — the ``ext not in LINTERS``
- # branch fires before the LSP short-circuit is consulted.
- with patch.object(fops, "_lsp_will_handle", return_value=True), \
- patch.object(fops, "_exec") as exec_mock:
- result = fops._check_lint(str(src))
-
- assert result.skipped is True
- assert not exec_mock.called, "no shell linter should run for .tsx"
-
-
def test_ts_shell_linter_skipped_when_ancestor_tsconfig_present(tmp_path):
"""A .ts file under a dir tree containing tsconfig.json skips the per-file
shell tsc EVEN WHEN LSP is inactive — single-file tsc can't read the
diff --git a/tests/agent/test_402_not_retried.py b/tests/agent/test_402_not_retried.py
deleted file mode 100644
index 177bc5eddee..00000000000
--- a/tests/agent/test_402_not_retried.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""Regression guard for #31273: HTTP 402 (billing exhaustion) must abort
-after credential-pool rotation and provider fallback have failed.
-
-Before the fix, ``FailoverReason.billing`` was in the exclusion set that
-prevents the loop's ``is_client_error`` branch from firing. When a user
-ran a pay-per-token provider (OpenRouter, etc.) with no credential pool
-and no fallback configured, a single 402 cascaded into
-``agent.api_max_retries`` paid requests against an exhausted balance.
-Real-world impact: ~$40 burned in 48h on a 24/7 gateway routing Telegram
-+ Discord traffic.
-
-The fix removes ``FailoverReason.billing`` from the exclusion set. By
-the time control reaches the ``is_client_error`` check:
- * credential-pool rotation has already run (and either ``continue``d
- on rotation, or returned False because the pool is exhausted/absent).
- * the eager-fallback branch for billing has also run (and either
- ``continue``d on fallback activation, or fell through because no
- fallback is configured).
-Falling through to the retry-backoff path from here just burns paid
-requests with no recovery mechanism left. Aborting mirrors how 401/403
-(also ``should_fallback=True``) already behave once their recovery paths
-have failed.
-"""
-from __future__ import annotations
-
-
-class TestBillingTriggersClientErrorAbort:
- """Mirror the ``is_client_error`` predicate shape used in
- ``agent/conversation_loop.py`` and verify ``FailoverReason.billing``
- now resolves to True (i.e. aborts the loop).
- """
-
- def _mirror_is_client_error(
- self,
- *,
- classified_retryable: bool,
- classified_reason,
- classified_should_compress: bool = False,
- is_local_validation_error: bool = False,
- is_context_length_error: bool = False,
- ) -> bool:
- """Exact shape of conversation_loop.py's is_client_error check.
-
- Kept in lock-step with the source. If you change one, change
- both — or, better, refactor the predicate into a shared helper
- and have both sites import it.
- """
- from agent.error_classifier import FailoverReason
-
- return (
- is_local_validation_error
- or (
- not classified_retryable
- and not classified_should_compress
- and classified_reason not in {
- FailoverReason.rate_limit,
- FailoverReason.overloaded,
- FailoverReason.context_overflow,
- FailoverReason.payload_too_large,
- FailoverReason.long_context_tier,
- FailoverReason.thinking_signature,
- }
- )
- ) and not is_context_length_error
-
- def test_billing_now_aborts_the_loop(self):
- """402 with no fallback / no pool entry → ``is_client_error`` True."""
- from agent.error_classifier import FailoverReason
-
- # This is what classify_api_error() returns for a plain 402:
- # reason=billing, retryable=False, should_compress=False
- assert self._mirror_is_client_error(
- classified_retryable=False,
- classified_reason=FailoverReason.billing,
- ), (
- "FailoverReason.billing must trigger is_client_error abort after "
- "credential-pool rotation and provider fallback have failed — see #31273."
- )
-
-
-
- def test_context_overflow_still_falls_through_to_compression(self):
- """Sanity check: context-overflow must NOT be classified as
- client error — compression is the recovery path."""
- from agent.error_classifier import FailoverReason
-
- assert not self._mirror_is_client_error(
- classified_retryable=True,
- classified_reason=FailoverReason.context_overflow,
- classified_should_compress=True,
- )
-
-
diff --git a/tests/agent/test_413_image_payload_recovery.py b/tests/agent/test_413_image_payload_recovery.py
index c319f3c4b37..960a7debe30 100644
--- a/tests/agent/test_413_image_payload_recovery.py
+++ b/tests/agent/test_413_image_payload_recovery.py
@@ -19,7 +19,6 @@ estimate. These tests assert that invariant directly.
import pytest
from agent.message_sanitization import serialized_messages_bytes
-from agent.model_metadata import estimate_messages_tokens_rough
def _data_url_image(size_bytes: int) -> dict:
@@ -41,27 +40,12 @@ def _tool_msg_with_image(size_bytes: int, text: str = "screenshot captured") ->
}
-def _image_aged_out(msg: dict) -> dict:
- """The message after compaction replaced its image with a placeholder."""
- out = dict(msg)
- out["content"] = [
- p for p in msg["content"] if p.get("type") != "image_url"
- ] + [{"type": "text", "text": "[image removed during compaction]"}]
- return out
-
-
class TestSerializedMessagesBytes:
def test_counts_inline_data_url_payloads(self):
small = serialized_messages_bytes([_tool_msg_with_image(1_000)])
huge = serialized_messages_bytes([_tool_msg_with_image(3_000_000)])
assert huge - small == pytest.approx(3_000_000 - 1_000, abs=64)
- def test_is_exact_not_an_estimate(self):
- """Same input, same answer — a measurement, not a heuristic."""
- messages = [_tool_msg_with_image(50_000), {"role": "user", "content": "hi"}]
- assert serialized_messages_bytes(messages) == serialized_messages_bytes(
- messages
- )
def test_utf8_bytes_not_codepoints(self):
ascii_msgs = [{"role": "user", "content": "aaaa"}]
@@ -80,138 +64,3 @@ class TestSerializedMessagesBytes:
messages = [{"role": "tool", "content": Weird()}]
assert serialized_messages_bytes(messages) > 0
-
-
-class TestTokenEstimateIsBlindToImageBytes:
- """The root cause, asserted directly.
-
- This is why a token-scored progress check can never clear an
- image-dominated 413: the estimate barely moves regardless of how many
- megabytes are on the wire.
- """
-
- def test_estimate_barely_moves_as_image_bytes_explode(self):
- small = [_tool_msg_with_image(1_000)]
- huge = [_tool_msg_with_image(3_000_000)]
-
- small_tokens = estimate_messages_tokens_rough(small)
- huge_tokens = estimate_messages_tokens_rough(huge)
-
- # ~3000x more bytes on the wire...
- assert len(huge[0]["content"][1]["image_url"]["url"]) > 2_000_000
-
- # ...but the token estimate is essentially unchanged, so a
- # "did compression make progress?" check scored in tokens
- # (new < original * 0.95) can never be satisfied by freeing images.
- assert huge_tokens < small_tokens * 2
-
-
-class TestByteScoredProgressCheck:
- """The invariant the fix installs: 413 progress is judged in bytes.
-
- Mirrors the exact decision expression in the 413 handler:
- ``len(messages) < original_len or new_bytes < original_bytes * 0.95``.
- """
-
- def _decision(self, before: list, after: list, *, metric: str) -> bool:
- if len(after) < len(before):
- return True
- if metric == "tokens":
- o = estimate_messages_tokens_rough(before)
- n = estimate_messages_tokens_rough(after)
- else:
- o = serialized_messages_bytes(before)
- n = serialized_messages_bytes(after)
- return n > 0 and n < o * 0.95
-
- def _image_dominated_session(self):
- """The real-world shape that wedged a session: ~190 substantive text
- turns (~77K token estimate), two multi-MB vision results = 96%+ of
- the serialized body but a tiny slice of the token estimate."""
- messages = [
- {
- "role": "user" if i % 2 == 0 else "assistant",
- "content": f"turn {i} " + ("x" * 900),
- }
- for i in range(190)
- ]
- messages.insert(50, _tool_msg_with_image(2_756_000))
- messages.insert(80, _tool_msg_with_image(2_871_000))
- return messages
-
- def test_token_scoring_wedges_on_image_dominated_payload(self):
- """BEFORE-behavior pin: compaction frees megabytes, token check
- still says no-progress -> attempts burn -> session wedges."""
- before = self._image_dominated_session()
- # Compaction ages out the older tool image (#97160) — same message
- # count, ~2.7MB freed.
- after = [
- _image_aged_out(m)
- if isinstance(m.get("content"), list) and m is before[50]
- else m
- for m in before
- ]
- freed = serialized_messages_bytes(before) - serialized_messages_bytes(after)
- assert freed > 2_000_000, "compaction really freed megabytes"
- assert self._decision(before, after, metric="tokens") is False, (
- "token yardstick is blind to the freed bytes — this is the bug"
- )
-
- def test_byte_scoring_sees_the_same_reduction(self):
- before = self._image_dominated_session()
- after = [
- _image_aged_out(m)
- if isinstance(m.get("content"), list) and m is before[50]
- else m
- for m in before
- ]
- assert self._decision(before, after, metric="bytes") is True, (
- "byte yardstick must recognize a multi-MB reduction as progress"
- )
-
- def test_text_only_compression_still_scores_progress_in_bytes(self):
- """Non-image 413s keep working: summarizing text shrinks bytes too."""
- before = [
- {"role": "user", "content": "x" * 10_000} for _ in range(50)
- ]
- after = [
- {"role": "user", "content": "x" * 10_000} for _ in range(10)
- ]
- # message-count branch fires first, but the byte branch alone would
- # also pass:
- assert serialized_messages_bytes(after) < (
- serialized_messages_bytes(before) * 0.95
- )
- assert self._decision(before, after, metric="bytes") is True
-
- def test_true_no_progress_is_still_terminal(self):
- """When nothing actually shrank, byte scoring must NOT fake progress."""
- before = self._image_dominated_session()
- after = list(before) # identical payload
- assert self._decision(before, after, metric="bytes") is False
-
-
-class TestConversationLoopWiring:
- """The handler really uses the byte metric (source-level contract)."""
-
- def test_413_branch_scores_bytes_not_tokens(self):
- import inspect
-
- import agent.turn_overflow as loop # 413 handler lives in recover_from_overflow
-
- src = inspect.getsource(loop)
- # The byte measurement is taken before and after the 413 compression
- # pass and drives the progress decision.
- assert "original_bytes = serialized_messages_bytes(messages)" in src
- assert "new_bytes = serialized_messages_bytes(messages)" in src
- assert "new_bytes < original_bytes * 0.95" in src
- # The old token-scored expression is gone from the 413 branch's
- # decision. Isolate the 413 handler region: from its status line to
- # its terminal error. (Token scoring survives in the
- # context-overflow branches, which ARE token-budget errors.)
- start = src.index("Request payload too large (413) — compression attempt")
- end = src.index("Payload too large and cannot compress further")
- branch = src[start:end]
- assert "new_tokens < original_tokens * 0.95" not in branch
- assert "original_bytes = serialized_messages_bytes" in branch
- assert "new_bytes = serialized_messages_bytes" in branch
diff --git a/tests/agent/test_860_dedup.py b/tests/agent/test_860_dedup.py
index 6c6e94b7226..5df53c0cce3 100644
--- a/tests/agent/test_860_dedup.py
+++ b/tests/agent/test_860_dedup.py
@@ -13,7 +13,6 @@ from pathlib import Path
from unittest.mock import patch
-
# ---------------------------------------------------------------------------
# Test: _flush_messages_to_session_db only writes new messages
# ---------------------------------------------------------------------------
@@ -72,48 +71,6 @@ class TestFlushDeduplication:
db.close()
-
- def test_flush_reset_after_compression(self):
- """After compression creates a new session, flush index resets."""
- from hermes_state import SessionDB
-
- with tempfile.TemporaryDirectory() as tmpdir:
- db_path = Path(tmpdir) / "test.db"
- db = SessionDB(db_path=db_path)
- try:
- agent = self._make_agent(db)
-
- # Write some messages
- messages = [
- {"role": "user", "content": "msg1"},
- {"role": "assistant", "content": "reply1"},
- ]
- agent._flush_messages_to_session_db(messages, [])
-
- old_session = agent.session_id
- assert agent._last_flushed_db_idx == 2
-
- # Simulate what _compress_context does: new session, reset idx
- agent.session_id = "compressed-session-new"
- db.create_session(session_id=agent.session_id, source="test")
- agent._last_flushed_db_idx = 0
-
- # Now flush compressed messages to new session
- compressed_messages = [
- {"role": "user", "content": "summary of conversation"},
- ]
- agent._flush_messages_to_session_db(compressed_messages, [])
-
- new_rows = db.get_messages(agent.session_id)
- assert len(new_rows) == 1
-
- # Old session should still have its 2 messages
- old_rows = db.get_messages(old_session)
- assert len(old_rows) == 2
- finally:
- db.close()
-
-
# ---------------------------------------------------------------------------
# Test: append_to_transcript skip_db parameter
# ---------------------------------------------------------------------------
@@ -147,25 +104,6 @@ class TestAppendToTranscriptSkipDb:
assert len(rows) == 0, f"Expected 0 DB rows with skip_db=True, got {len(rows)}"
-
# ---------------------------------------------------------------------------
# Test: _last_flushed_db_idx initialization
# ---------------------------------------------------------------------------
-
-class TestFlushIdxInit:
- """Verify _last_flushed_db_idx is properly initialized."""
-
- def test_init_zero(self):
- """Agent starts with _last_flushed_db_idx = 0."""
- with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
- from run_agent import AIAgent
- agent = AIAgent(
- api_key="test-key",
- base_url="https://openrouter.ai/api/v1",
- model="test/model",
- quiet_mode=True,
- skip_context_files=True,
- skip_memory=True,
- )
- assert agent._last_flushed_db_idx == 0
-
diff --git a/tests/agent/test_account_usage_fetch.py b/tests/agent/test_account_usage_fetch.py
index f6e9df78e3f..439ca1ae18b 100644
--- a/tests/agent/test_account_usage_fetch.py
+++ b/tests/agent/test_account_usage_fetch.py
@@ -159,29 +159,6 @@ def test_fetch_account_usage_prefers_builtin_fetcher_over_profile(monkeypatch):
assert profile.calls == 0
-def test_render_account_usage_lines_includes_reset_and_provider():
- snapshot = AccountUsageSnapshot(
- provider="openai-codex",
- source="usage_api",
- fetched_at=datetime.now(timezone.utc),
- plan="Pro",
- windows=(
- AccountUsageWindow(
- label="Session",
- used_percent=25,
- reset_at=datetime.now(timezone.utc),
- ),
- ),
- details=("Credits balance: $9.99",),
- )
- lines = render_account_usage_lines(snapshot)
-
- assert lines[0] == "📈 Account limits"
- assert "openai-codex (Pro)" in lines[1]
- assert "Session: 75% remaining (25% used)" in lines[2]
- assert "Credits balance: $9.99" in lines[3]
-
-
def test_fetch_account_usage_openrouter_uses_limit_remaining_and_ignores_deprecated_rate_limit(monkeypatch):
monkeypatch.setattr(
"agent.account_usage.resolve_runtime_provider",
@@ -319,20 +296,6 @@ def test_plugin_usage_hook_failure_never_reaches_threading_excepthook(monkeypatc
assert escaped == []
-def test_base_noop_usage_hook_spawns_no_thread(monkeypatch):
- """A profile inheriting ``ProviderProfile.fetch_account_usage`` costs no thread."""
- import threading
-
- from agent import account_usage
-
- _register_profile(monkeypatch, ProviderProfile(name="plugin-noop"))
- monkeypatch.setattr(account_usage, "_USAGE_FETCHERS", {})
- monkeypatch.setattr(threading.Thread, "start",
- lambda self: pytest.fail(f"base no-op hook spawned thread {self.name!r}"))
-
- assert account_usage.fetch_account_usage("plugin-noop") is None
-
-
@pytest.mark.parametrize("fetch", [_fetch_portal_account, _billing_fetch_nous_account])
def test_fetch_portal_account_is_wall_clock_bounded(monkeypatch, fetch):
"""A portal that accepts the connection but never answers must release the
diff --git a/tests/agent/test_acp_openai_bridge.py b/tests/agent/test_acp_openai_bridge.py
index f6874618185..716d152ce3e 100644
--- a/tests/agent/test_acp_openai_bridge.py
+++ b/tests/agent/test_acp_openai_bridge.py
@@ -200,16 +200,4 @@ def test_copilot_prompt_still_carries_the_contract_and_the_tools():
assert "<tool_call>{...}</tool_call>" in prompt
assert '"name": "memory"' in prompt
assert '"name": "read_file"' in prompt # copilot forwards everything
- # No prompt-text model mention: the model is applied via ACP
- # session/set_model, and a prompt hint makes a substituted backend
- # falsely self-identify as the requested model.
- assert "model hint" not in prompt
assert "hi" in prompt
-
-
-def test_copilot_prompt_omits_the_tool_section_when_there_are_no_tools():
- from agent.copilot_acp_client import _format_messages_as_prompt
-
- prompt = _format_messages_as_prompt([{"role": "user", "content": "hi"}])
- assert "Available tools" not in prompt
- assert "Tool choice hint" not in prompt
diff --git a/tests/agent/test_actual_auxiliary_routing.py b/tests/agent/test_actual_auxiliary_routing.py
index dfa2c9544d4..ec22f8e1105 100644
--- a/tests/agent/test_actual_auxiliary_routing.py
+++ b/tests/agent/test_actual_auxiliary_routing.py
@@ -111,8 +111,6 @@ def actual_endpoint(monkeypatch):
[
"auto",
"actual",
- "actual-computer",
- "actualcomputer",
"aci",
"custom",
"custom:actual-relay",
@@ -225,8 +223,6 @@ def test_actual_background_tasks_reach_chat_completions(
[
("actual", False),
("aci", False),
- ("actual-computer", False),
- ("actualcomputer", False),
("custom", True),
("custom:actual-relay", True),
],
@@ -353,8 +349,6 @@ def test_actual_runtime_transitions_reach_chat_completions(
[
("actual", False),
("aci", False),
- ("actual-computer", False),
- ("actualcomputer", False),
("custom", True),
("custom:actual-relay", True),
],
diff --git a/tests/agent/test_agent_guardrails.py b/tests/agent/test_agent_guardrails.py
index 0e7aed9e9b0..a6f91bada3e 100644
--- a/tests/agent/test_agent_guardrails.py
+++ b/tests/agent/test_agent_guardrails.py
@@ -149,8 +149,6 @@ class TestSanitizeApiMessages:
assert out[1]["tool_call_id"] == "c6"
-
-
# ---------------------------------------------------------------------------
# Phase 2a — _cap_delegate_task_calls
# ---------------------------------------------------------------------------
@@ -179,7 +177,6 @@ class TestCapDelegateTaskCalls:
assert out is tcs
-
def test_empty_list_safe(self):
assert AIAgent._cap_delegate_task_calls([]) == []
@@ -243,15 +240,10 @@ class TestDeduplicateToolCalls:
assert out == [first, distinct]
-
-
-
def test_empty_list_safe(self):
assert AIAgent._deduplicate_tool_calls([]) == []
-
-
# ---------------------------------------------------------------------------
# Phase 2c — _uniquify_tool_call_ids
# ---------------------------------------------------------------------------
@@ -286,7 +278,6 @@ class TestUniquifyToolCallIds:
assert [tc.id for tc in tcs] == ["x", "x_d2", "x_d3"]
-
def test_blank_and_missing_ids_left_for_fallback(self):
tc_blank = make_tc_id("", "t1")
tc_none = make_tc_id(None, "t2")
@@ -332,16 +323,6 @@ class TestUniquifyToolCallIds:
# _get_tool_call_id_static
# ---------------------------------------------------------------------------
-class TestGetToolCallIdStatic:
-
- def test_dict_with_valid_id(self):
- assert AIAgent._get_tool_call_id_static({"id": "call_123"}) == "call_123"
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# _get_tool_call_name_static
@@ -349,14 +330,6 @@ class TestGetToolCallIdStatic:
class TestGetToolCallNameStatic:
- def test_dict_with_valid_name(self):
- assert AIAgent._get_tool_call_name_static(
- {"id": "call_1", "function": {"name": "terminal", "arguments": "{}"}}
- ) == "terminal"
-
-
-
-
def test_object_without_function_attr(self):
tc = types.SimpleNamespace(id="call_1")
diff --git a/tests/agent/test_anthropic_adapter.py b/tests/agent/test_anthropic_adapter.py
index a66d1d51843..369c36ed184 100644
--- a/tests/agent/test_anthropic_adapter.py
+++ b/tests/agent/test_anthropic_adapter.py
@@ -9,9 +9,8 @@ from unittest.mock import patch, MagicMock
import pytest
from agent.prompt_caching import apply_anthropic_cache_control
-from agent.anthropic_adapter import build_anthropic_client, build_anthropic_bedrock_client, build_anthropic_kwargs
+from agent.anthropic_adapter import build_anthropic_client, build_anthropic_kwargs
from agent.anthropic_credentials import _is_oauth_token, _refresh_oauth_token, _write_claude_code_credentials, is_claude_code_token_valid, read_claude_code_credentials, resolve_anthropic_token, run_oauth_setup_token
-from agent.anthropic_endpoints import _is_azure_anthropic_endpoint
from agent.credential_pool import PooledCredential
from agent.anthropic_message_convert import _to_plain_data, convert_messages_to_anthropic, convert_tools_to_anthropic, normalize_model_name
from agent.transports import get_transport
@@ -30,9 +29,6 @@ class TestIsOAuthToken:
assert _is_oauth_token("sk-ant-api03-abcdef1234567890") is False
-
-
-
class TestBuildAnthropicClient:
@@ -50,10 +46,6 @@ class TestBuildAnthropicClient:
assert "claude-code-20250219" not in betas # OAuth-only beta NOT present
-
-
-
-
def test_opencode_endpoint_gets_attribution_headers(self):
"""OpenCode identifies clients by request headers, like OpenRouter.
@@ -137,8 +129,6 @@ class TestBuildAnthropicClient:
assert kwargs["max_retries"] == 0
-
-
class TestReadClaudeCodeCredentials:
@pytest.fixture(autouse=True)
def no_keychain(self, monkeypatch):
@@ -173,9 +163,6 @@ class TestReadClaudeCodeCredentials:
assert creds is None
-
-
-
class TestIsClaudeCodeTokenValid:
def test_valid_token(self):
creds = {"accessToken": "tok", "expiresAt": int(time.time() * 1000) + 3600_000}
@@ -385,7 +372,6 @@ class TestResolveAnthropicToken:
assert resolve_anthropic_token() == "cc-auto-token"
-
class TestRefreshOauthToken:
def test_returns_none_without_refresh_token(self, tmp_path, monkeypatch):
monkeypatch.setattr("agent.anthropic_credentials.Path.home", lambda: tmp_path)
@@ -583,7 +569,6 @@ class TestRunOauthSetupToken:
assert token is None
-
# ---------------------------------------------------------------------------
# Model name normalization
# ---------------------------------------------------------------------------
@@ -594,8 +579,6 @@ class TestNormalizeModelName:
assert normalize_model_name("anthropic/claude-sonnet-4-20250514") == "claude-sonnet-4-20250514"
-
-
def test_preserve_dots_for_alibaba_dashscope(self):
"""Alibaba/DashScope use dots in model names (e.g. qwen3.5-plus). Fixes #1739."""
assert normalize_model_name("qwen3.5-plus", preserve_dots=True) == "qwen3.5-plus"
@@ -673,13 +656,6 @@ class TestConvertTools:
class TestConvertMessages:
-
-
-
-
-
-
-
def test_strips_tool_use_when_result_not_immediately_adjacent(self):
"""A tool_use whose result appears LATER but not in the immediately
following user message must be stripped (adjacency, #52145).
@@ -886,9 +862,6 @@ class TestConvertMessages:
assert tool_block["cache_control"] == {"type": "ephemeral"}
-
-
-
def test_empty_user_message_string_gets_placeholder(self):
"""Empty user message strings should get '(empty message)' placeholder.
@@ -903,8 +876,6 @@ class TestConvertMessages:
assert result[0]["content"] == "(empty message)"
-
-
def test_leading_assistant_after_compaction_gets_user_turn_prepended(self):
"""The adapter backstops compactors that emit a leading assistant summary."""
messages = [
@@ -925,9 +896,6 @@ class TestConvertMessages:
)
-
-
-
# ---------------------------------------------------------------------------
# Build kwargs
# ---------------------------------------------------------------------------
@@ -936,8 +904,6 @@ class TestConvertMessages:
class TestBuildAnthropicKwargs:
-
-
def test_reasoning_config_maps_to_manual_thinking_for_pre_4_6_models(self):
kwargs = build_anthropic_kwargs(
model="claude-sonnet-4-20250514",
@@ -969,33 +935,6 @@ class TestBuildAnthropicKwargs:
assert kwargs["max_tokens"] == 4096
-
-
-
-
- def test_supports_fast_mode_predicate(self):
- """The speed-param allowlist tracks the live fast-mode docs.
-
- Per https://platform.claude.com/docs/en/build-with-claude/fast-mode:
- Opus 4.8 and Opus 5 support ``speed: "fast"``. Opus 4.6 LOST fast
- mode (param silently ignored → standard speed at standard billing);
- Opus 4.7 hard-400s. Dedicated ``…-fast`` model ids select fast
- inference via the model field and must not also get the param.
- """
- from agent.anthropic_adapter import _supports_fast_mode
- assert _supports_fast_mode("claude-opus-4-8") is True
- assert _supports_fast_mode("claude-opus-4.8") is True
- assert _supports_fast_mode("anthropic/claude-opus-4-8") is True
- assert _supports_fast_mode("claude-opus-5") is True
- assert _supports_fast_mode("anthropic/claude-opus-5") is True
- assert _supports_fast_mode("claude-opus-4-6") is False
- assert _supports_fast_mode("anthropic/claude-opus-4-6") is False
- assert _supports_fast_mode("claude-opus-4-7") is False
- assert _supports_fast_mode("claude-opus-4-8-fast") is False
- assert _supports_fast_mode("claude-sonnet-4-6") is False
- assert _supports_fast_mode("claude-haiku-4-5") is False
- assert _supports_fast_mode("") is False
-
def test_fable_class_models_route_as_adaptive_thinking(self):
"""Invariant: unknown/new Claude models default to the modern (4.7+)
contract — adaptive thinking, xhigh-capable, sampling-params-forbidden —
@@ -1007,7 +946,6 @@ class TestBuildAnthropicKwargs:
_supports_adaptive_thinking,
_supports_xhigh_effort,
_forbids_sampling_params,
- _get_anthropic_max_output,
)
# New / unknown Claude models → modern contract by default.
for m in (
@@ -1019,9 +957,6 @@ class TestBuildAnthropicKwargs:
assert _supports_adaptive_thinking(m) is True, m
assert _supports_xhigh_effort(m) is True, m
assert _forbids_sampling_params(m) is True, m
- # 1M-context reasoning model → highest output ceiling.
- assert _get_anthropic_max_output("anthropic/claude-fable-5") == 128_000
-
def test_non_claude_anthropic_models_use_manual_path(self):
@@ -1070,35 +1005,11 @@ class TestBuildAnthropicKwargs:
assert "fast-mode-2026-02-01" not in beta_header
-
-
-
-
-
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# Model output limit lookup
# ---------------------------------------------------------------------------
-class TestGetAnthropicMaxOutput:
- def test_opus_4_6(self):
- from agent.anthropic_adapter import _get_anthropic_max_output
- assert _get_anthropic_max_output("claude-opus-4-6") == 128_000
-
-
-
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# _to_plain_data hardening
# ---------------------------------------------------------------------------
@@ -1107,15 +1018,6 @@ class TestGetAnthropicMaxOutput:
class TestToPlainData:
-
-
- def test_deep_nesting_is_capped(self):
- deep = "leaf"
- for _ in range(25):
- deep = {"nested": deep}
- result = _to_plain_data(deep)
- assert isinstance(result, dict)
-
def test_plain_values_pass_through(self):
assert _to_plain_data("hello") == "hello"
assert _to_plain_data(42) == 42
@@ -1187,8 +1089,6 @@ class TestNormalizeResponse:
assert nr3.finish_reason == "length"
-
-
# ---------------------------------------------------------------------------
# Role alternation
# ---------------------------------------------------------------------------
@@ -1228,8 +1128,6 @@ class TestThinkingBlockSignatureManagement:
strip from old turns, preserve latest signed, downgrade unsigned."""
-
-
def test_redacted_thinking_with_data_preserved(self):
"""Redacted thinking with 'data' field is kept on last turn."""
messages = [
@@ -1290,7 +1188,6 @@ class TestThinkingBlockSignatureManagement:
assert "cache_control" not in block
-
def test_multi_turn_conversation_preserves_only_last(self):
"""Full multi-turn conversation: only last assistant keeps thinking."""
messages = [
@@ -1341,8 +1238,6 @@ class TestThinkingBlockSignatureManagement:
assert last_thinking[0]["signature"] == "sig_3"
-
-
# ---------------------------------------------------------------------------
# Tool choice
# ---------------------------------------------------------------------------
@@ -1384,7 +1279,6 @@ class TestToolChoice:
assert kwargs["tool_choice"] == {"type": "tool", "name": "search"}
-
# ---------------------------------------------------------------------------
# max_tokens resolver — openclaw/openclaw#66664 port
# ---------------------------------------------------------------------------
@@ -1403,9 +1297,6 @@ class TestResolvePositiveMaxTokens:
assert _resolve_positive_anthropic_max_tokens(0) is None
-
-
-
def test_nan_returns_none(self):
assert _resolve_positive_anthropic_max_tokens(float("nan")) is None
@@ -1416,8 +1307,6 @@ class TestResolvePositiveMaxTokens:
assert _resolve_positive_anthropic_max_tokens(False) is None
-
-
class TestResolveMessagesMaxTokens:
"""Integration tests for the full Messages resolver."""
@@ -1427,9 +1316,6 @@ class TestResolveMessagesMaxTokens:
) == 8192
-
-
-
def test_sub_one_float_falls_back(self):
# 0.5 floors to 0 -> not positive -> falls back to model ceiling
result = _resolve_anthropic_messages_max_tokens(0.5, "claude-opus-4-6")
@@ -1477,10 +1363,6 @@ class TestConvertToolsToAnthropicDedup:
assert len(result) == 3 # lcm_grep, lcm_describe, lcm_expand
- def test_none_tools_returns_empty(self):
- assert convert_tools_to_anthropic(None) == []
-
-
class TestBlankTextBlockFiltering:
"""Regression tests for blank text block filtering in _convert_assistant_message.
@@ -1496,7 +1378,6 @@ class TestBlankTextBlockFiltering:
return _convert_assistant_message(message)
-
def test_normal_path_filters_none_text_block_without_crashing(self):
"""Regression (review of #63228): text=None must not raise
AttributeError. _convert_content_part_to_anthropic() can preserve
@@ -1519,7 +1400,6 @@ class TestBlankTextBlockFiltering:
assert len(tool_blocks) == 1
-
def test_normal_path_relocates_cache_control_from_dropped_block(self):
"""Regression (review of #63228): prompt_caching.py's _apply_cache_marker
sets cache_control directly on content[-1] for list content. If that
@@ -1598,7 +1478,6 @@ class TestAllBlankFallbackAndNonStringText:
return _convert_assistant_message(message)
-
def test_sole_cache_marked_blank_block_relocates_marker_to_placeholder(self):
"""A message whose ONLY content is a blank text block that also
carries cache_control: the marker must not be silently dropped just
@@ -1950,5 +1829,5 @@ def test_unsupported_inline_image_subtype_downgrades_to_text_for_anthropic(monke
blocks = result[0]["content"]
assert [b["type"] for b in blocks] == ["image", "text", "image"]
assert blocks[0]["source"] == {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo="}
- assert blocks[1]["text"] == "[image omitted: image/svg+xml is not a supported image format]"
+ assert "image/svg+xml" in blocks[1]["text"]
assert blocks[2]["source"]["media_type"] == "image/jpeg"
diff --git a/tests/agent/test_anthropic_billing_guidance.py b/tests/agent/test_anthropic_billing_guidance.py
index 3d49b4aed34..2dbb0207da4 100644
--- a/tests/agent/test_anthropic_billing_guidance.py
+++ b/tests/agent/test_anthropic_billing_guidance.py
@@ -72,45 +72,12 @@ def _anthropic_msg(*, unverified: bool) -> str:
def test_unverified_guidance_names_the_content_filter_alternative():
msg = _anthropic_msg(unverified=True).lower()
assert "content filter" in msg
- # Must give the operator a way to tell the two apart, not just hedge.
- assert "still shows quota remaining" in msg
- assert "system prompt" in msg
-
-
-def test_unverified_guidance_does_not_assert_exhaustion_as_fact():
- """The opening line must hedge. 'is exhausted' is the claim that misdirected
- diagnosis; 'may be exhausted' keeps the billing lead without asserting it."""
- first_line = _anthropic_msg(unverified=True).splitlines()[0].lower()
- assert "may be exhausted" in first_line
- assert "is exhausted" not in first_line
-
-
-def test_unverified_guidance_warns_about_the_cached_exhaustion_replay():
- """After a failure the credential is latched exhausted and the stored error
- is replayed without issuing a request — so a real fix looks like it didn't
- work. Point at the reset before the user concludes that."""
- msg = _anthropic_msg(unverified=True)
- assert "hermes auth reset anthropic" in msg
- assert "without contacting the API" in msg
-
-
-def test_unverified_guidance_keeps_the_billing_remedies():
- """The caveats are additive — the billing remedies stay available."""
- msg = _anthropic_msg(unverified=True)
- assert "https://claude.ai/settings/usage" in msg
- assert "reset" in msg.lower()
- assert "/model" in msg
- assert "claude-opus-5" in msg
def test_confirmed_guidance_stays_assertive_without_the_caveat():
"""A CONFIRMED billing verdict (e.g. a real 402) must not be diluted by
content-filter lore that only applies to the ambiguous 400 body."""
- msg = _anthropic_msg(unverified=False)
- first_line = msg.splitlines()[0].lower()
- assert "is exhausted" in first_line
- assert "may be exhausted" not in first_line
- lowered = msg.lower()
+ lowered = _anthropic_msg(unverified=False).lower()
assert "content filter" not in lowered
assert "hermes auth reset" not in lowered
diff --git a/tests/agent/test_anthropic_client_auth.py b/tests/agent/test_anthropic_client_auth.py
index 40981652cb7..902f0f43bb0 100644
--- a/tests/agent/test_anthropic_client_auth.py
+++ b/tests/agent/test_anthropic_client_auth.py
@@ -22,18 +22,6 @@ def wire_headers(client) -> dict:
-def test_api_key_client_and_its_copies_never_carry_the_env_bearer(monkeypatch):
- """The guard is a copy-safe Omit() default header: ``with_options()`` re-runs the constructor
- and re-reads ANTHROPIC_AUTH_TOKEN, so an attribute clear alone would re-leak on the copy."""
- anthropic_sdk = pytest.importorskip("anthropic")
- monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", SENTINEL)
- from agent.anthropic_adapter import _new_sdk_client
-
- client = _new_sdk_client(anthropic_sdk, {"api_key": "provider-key", "base_url": "http://127.0.0.1:1"}, {})
- for wire_client in (client, client.with_options(timeout=30)):
- headers = wire_headers(wire_client)
- assert headers.get("x-api-key") == "provider-key"
- assert "authorization" not in headers
# The bearer mirror (no env x-api-key beside a portal JWT) is owned by
# tests/agent/test_nous_portal_anthropic_wire.py::TestClientShape.
diff --git a/tests/agent/test_anthropic_credential_persist_failure.py b/tests/agent/test_anthropic_credential_persist_failure.py
index c228f523b64..ad2a83773c6 100644
--- a/tests/agent/test_anthropic_credential_persist_failure.py
+++ b/tests/agent/test_anthropic_credential_persist_failure.py
@@ -240,14 +240,6 @@ def test_direct_resolver_fails_closed_when_rotation_cannot_commit(
assert _read_claude_pair(claude_credentials) == (_STALE_ACCESS, _STALE_REFRESH)
-def test_resolve_from_credentials_returns_none_on_failed_commit(
- claude_credentials, monkeypatch
-):
- """The resolver wrapper propagates the fail-closed verdict."""
- monkeypatch.setattr(AA, "refresh_anthropic_oauth_pure", _rotating_refresh)
- _break_durable_write(monkeypatch)
-
- assert AA._resolve_claude_code_token_from_credentials() is None
# ---------------------------------------------------------------------------
diff --git a/tests/agent/test_anthropic_dead_grant_hints.py b/tests/agent/test_anthropic_dead_grant_hints.py
index a1256a9b5af..6902af9c480 100644
--- a/tests/agent/test_anthropic_dead_grant_hints.py
+++ b/tests/agent/test_anthropic_dead_grant_hints.py
@@ -38,18 +38,6 @@ def test_dead_grant_is_classified_and_not_replayed_at_other_endpoints(monkeypatc
assert not ac.is_terminal_anthropic_refresh_error(TimeoutError("timed out"))
-def test_claude_code_refresher_warns_on_dead_grant(monkeypatch, caplog):
- """The auxiliary Claude Code refresher is a sibling path of the pool: same WARNING, same Hermes hint."""
- monkeypatch.setattr(ac, "read_claude_code_credentials", lambda: {"accessToken": "old", "refreshToken": "rt", "expiresAt": 1})
-
- def dead(refresh_token, *, use_json=False):
- raise ac.AnthropicOAuthError(400, "invalid_grant", "", what="refresh")
-
- monkeypatch.setattr(ac, "refresh_anthropic_oauth_pure", dead)
- with caplog.at_level(logging.INFO, logger=ac.logger.name):
- assert ac._refresh_oauth_token({"accessToken": "old", "refreshToken": "rt"}) is None
- warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
- assert len(warnings) == 1 and "hermes auth add anthropic" in warnings[0]
def test_claude_code_refresher_reports_dead_grant_once_per_process(monkeypatch, caplog):
@@ -86,20 +74,5 @@ def test_claude_code_credentials_path_honours_claude_config_dir(monkeypatch, tmp
assert ac.claude_code_credentials_path() == Path.home() / ".claude" / ".credentials.json"
-def test_anthropic_401_troubleshooting_points_at_hermes_auth(capsys):
- from agent.turn_recovery import _print_anthropic_401_diagnostics
-
- class _Agent:
- log_prefix = ""
-
- _print_anthropic_401_diagnostics(_Agent(), "sk-ant-oat01-xxxxxxxxxxxx")
- out = capsys.readouterr().out
- assert "hermes auth add anthropic" in out and "hermes auth list anthropic" in out
- assert "/login" not in out
-
-def test_no_anthropic_credentials_message_points_at_hermes_auth():
- from hermes_cli.runtime_provider import _NO_ANTHROPIC_CREDENTIALS_MSG
- assert "hermes auth add anthropic" in _NO_ANTHROPIC_CREDENTIALS_MSG
- assert "/login" not in _NO_ANTHROPIC_CREDENTIALS_MSG
diff --git a/tests/agent/test_anthropic_kwargs_sanitize.py b/tests/agent/test_anthropic_kwargs_sanitize.py
index f39ff9f4e10..cc44fda8dca 100644
--- a/tests/agent/test_anthropic_kwargs_sanitize.py
+++ b/tests/agent/test_anthropic_kwargs_sanitize.py
@@ -6,12 +6,9 @@ leaking in under an api_mode-flip race. The Anthropic SDK raises a
non-retryable ``TypeError`` on any of them, killing the whole turn.
"""
-import logging
-import pytest
from agent.anthropic_adapter import (
- _RESPONSES_ONLY_KWARGS,
sanitize_anthropic_kwargs,
)
@@ -32,10 +29,6 @@ def _fake_anthropic_call(**kwargs):
return "OK"
-def test_bare_leaked_payload_reproduces_the_typeerror():
- """Without the guard, a Responses-shaped payload raises the issue's error."""
- with pytest.raises(TypeError, match="unexpected keyword argument"):
- _fake_anthropic_call(model="claude-sonnet-4-6", instructions="sys")
def test_strips_all_responses_only_keys():
@@ -54,15 +47,6 @@ def test_strips_all_responses_only_keys():
-def test_warns_when_keys_are_stripped(caplog):
- with caplog.at_level(logging.WARNING, logger="agent.anthropic_adapter"):
- sanitize_anthropic_kwargs(
- {"model": "m", "instructions": "sys"}, log_prefix="[pfx] "
- )
- assert any(
- "31673" in r.message and "[pfx] " in r.message
- for r in caplog.records
- ), caplog.records
diff --git a/tests/agent/test_anthropic_mcp_prefix_strip.py b/tests/agent/test_anthropic_mcp_prefix_strip.py
index 16713128a4e..bfa23ebafbf 100644
--- a/tests/agent/test_anthropic_mcp_prefix_strip.py
+++ b/tests/agent/test_anthropic_mcp_prefix_strip.py
@@ -169,25 +169,6 @@ class TestAnthropicOAuthOutgoingPrefix:
)
- def test_oauth_promotes_single_underscore_mcp_server_tool(self):
- """OAuth + ``mcp_<server>_<tool>`` -> promoted to double underscore.
-
- This is the gap left by the bare constant swap: MCP server tools used
- to be *skipped* and went on the wire single-underscore, still tripping
- the classifier. They must become ``mcp__`` and NOT be double-prefixed.
- """
- kwargs = self._build([{
- "type": "function",
- "function": {
- "name": "mcp_linear_get_issue",
- "description": "x",
- "parameters": {},
- },
- }])
- names = [t["name"] for t in kwargs["tools"]]
- assert names == ["mcp__linear_get_issue"]
- # never double-prefixed
- assert not any(n.startswith("mcp__mcp_") for n in names)
def test_oauth_no_single_underscore_mcp_on_wire(self):
diff --git a/tests/agent/test_anthropic_oauth_pkce.py b/tests/agent/test_anthropic_oauth_pkce.py
index 33363176434..f800b138957 100644
--- a/tests/agent/test_anthropic_oauth_pkce.py
+++ b/tests/agent/test_anthropic_oauth_pkce.py
@@ -148,43 +148,6 @@ def test_authorization_url_state_is_not_pkce_verifier(monkeypatch, tmp_path):
)
-def test_login_token_exchange_uses_platform_claude_host(monkeypatch, tmp_path):
- """The login token exchange must hit ``platform.claude.com`` first.
-
- Anthropic migrated the OAuth token endpoint to ``platform.claude.com``;
- ``console.anthropic.com`` now 404s, so a hardcoded console host makes a
- fresh login impossible (issue #45250 / #49821). The refresh path already
- iterates the new host first — the login path must do the same.
- """
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
-
- captured_token: Dict[str, Any] = {}
- captured_url: Dict[str, str] = {}
- _patch_oauth_flow(
- monkeypatch,
- callback_code="placeholder",
- capture_token_request=captured_token,
- capture_auth_url=captured_url,
- )
-
- import builtins
-
- def fake_input(*_a, **_kw):
- qs = parse_qs(urlparse(captured_url.get("url", "")).query)
- state = qs.get("state", [""])[0]
- return f"auth-code#{state}"
-
- monkeypatch.setattr(builtins, "input", fake_input)
-
- from agent.anthropic_credentials import run_hermes_oauth_login_pure
-
- result = run_hermes_oauth_login_pure()
-
- assert result is not None, "login should succeed against the live host"
- assert captured_token["url"] == "https://platform.claude.com/v1/oauth/token", (
- "login token exchange must target platform.claude.com first, not the "
- "dead console.anthropic.com host (regression of #45250 / #49821)"
- )
diff --git a/tests/agent/test_anthropic_oauth_stress.py b/tests/agent/test_anthropic_oauth_stress.py
index b558eb4a6aa..e8173640f2b 100644
--- a/tests/agent/test_anthropic_oauth_stress.py
+++ b/tests/agent/test_anthropic_oauth_stress.py
@@ -183,10 +183,8 @@ def test_high_concurrency_anthropic_refresh_no_lost_updates_no_deadlock(
"""CONCURRENCY 'Hermes processes' race the same stale refresh token
against the real cross-process lock + real on-disk pool persistence.
- Bottleneck check: total wall-clock time must stay close to what a
- correctly-serialized (or adopt-without-refreshing) implementation would
- take, not blow up toward CONCURRENCY * network_delay -- and every
- participant must end up with a usable, non-exhausted credential.
+ Every participant must end up with a usable, non-exhausted credential and
+ the single-use stale token must be POSTed exactly once.
"""
server = _SingleUseTokenServer(delay_seconds=0.02)
monkeypatch.setattr(
@@ -227,7 +225,6 @@ def test_high_concurrency_anthropic_refresh_no_lost_updates_no_deadlock(
for t in threads:
remaining = max(0.1, deadline - time.monotonic())
t.join(timeout=remaining)
- elapsed = time.monotonic() - start
still_alive = [t for t in threads if t.is_alive()]
assert not still_alive, (
@@ -247,17 +244,9 @@ def test_high_concurrency_anthropic_refresh_no_lost_updates_no_deadlock(
f"process {idx} ended up with an exhausted Anthropic credential "
"despite valid tokens existing on disk"
)
-
- # Bottleneck signal: this must stay well below "every thread pays the
- # full network delay independently" (CONCURRENCY * delay). If the fix
- # regresses into N sequential POSTs instead of lock+adopt, this is
- # where it would show up first.
- naive_serial_upper_bound = CONCURRENCY * server.delay_seconds * 3
- assert elapsed < naive_serial_upper_bound, (
- f"refresh race took {elapsed:.2f}s for {CONCURRENCY} concurrent "
- f"processes -- expected well under {naive_serial_upper_bound:.2f}s "
- "if the lock + pool-store adoption path is working efficiently"
- )
+ # Deterministic replacement for the old wall-clock bound: the single-use
+ # stale token is POSTed exactly once, however many racers there are.
+ assert server.calls.count("stale-rt") == 1, server.calls
@pytest.mark.live_system_guard_bypass
diff --git a/tests/agent/test_anthropic_oauth_ua_prefix.py b/tests/agent/test_anthropic_oauth_ua_prefix.py
index e5161afa2d3..47d53af9bcc 100644
--- a/tests/agent/test_anthropic_oauth_ua_prefix.py
+++ b/tests/agent/test_anthropic_oauth_ua_prefix.py
@@ -15,10 +15,8 @@ Two DIFFERENT Anthropic endpoints impose OPPOSITE User-Agent requirements:
from __future__ import annotations
-import re
from unittest.mock import MagicMock, patch
-import pytest
class TestOAuthUserAgentPrefix:
@@ -42,25 +40,3 @@ class TestOAuthUserAgentPrefix:
- def test_token_refresh_ua_not_throttled(self):
- """refresh_anthropic_oauth_pure must NOT send a throttled token-endpoint UA."""
- import inspect
- import agent.anthropic_credentials as mod
-
- func = getattr(mod, "refresh_anthropic_oauth_pure", None)
- if func is None or not callable(func):
- pytest.skip("refresh_anthropic_oauth_pure not found")
- source = inspect.getsource(func)
-
- for i, line in enumerate(source.split("\n"), 1):
- stripped = line.strip()
- if ("User-Agent" in stripped or "user-agent" in stripped) and (
- "claude-cli/" in stripped or "claude-code/" in stripped
- ):
- pytest.fail(
- f"Line {i}: throttled UA in refresh header: {stripped}"
- )
- assert "_OAUTH_TOKEN_USER_AGENT" in source, (
- "refresh_anthropic_oauth_pure should send the shared "
- "_OAUTH_TOKEN_USER_AGENT (non-claude-code) on the token endpoint"
- )
diff --git a/tests/agent/test_anthropic_prompt_cache_policy.py b/tests/agent/test_anthropic_prompt_cache_policy.py
index abe95d18b7f..f3201536e19 100644
--- a/tests/agent/test_anthropic_prompt_cache_policy.py
+++ b/tests/agent/test_anthropic_prompt_cache_policy.py
@@ -585,19 +585,6 @@ class TestMiniMaxAnthropicWire:
)
assert agent._anthropic_prompt_cache_policy() == (True, True)
- def test_minimax_m27_still_caches_after_m3_opt_out(self):
- # Regression guard: the M3 substring check must not collide with
- # M2.7 / M2.5 / M2.1 / M2 model names. "minimax-m3" is not a
- # substring of "minimax-m2.7" etc., but pin this with a test so a
- # future "startswith minimax-m" loosening can't silently drop the
- # M2.x cache_control path.
- agent = _make_agent(
- provider="minimax",
- base_url="https://api.minimax.io/anthropic",
- api_mode="anthropic_messages",
- model="MiniMax-M2.7",
- )
- assert agent._anthropic_prompt_cache_policy() == (True, True)
class TestOpenAIWireFormatOnCustomProvider:
@@ -747,21 +734,14 @@ class TestLiteLLMOpenAIWire:
("custom", "https://my-litellm-gw.internal.example.com/v1"),
],
)
- @pytest.mark.parametrize(
- "model",
- [
- "claude-opus-4.8",
- "anthropic/claude-sonnet-4.6",
- ],
- )
def test_claude_on_litellm_openai_wire_caches_with_envelope_layout(
- self, provider, base_url, model
+ self, provider, base_url
):
agent = _make_agent(
provider=provider,
base_url=base_url,
api_mode="chat_completions",
- model=model,
+ model="anthropic/claude-sonnet-4.6",
)
assert agent._anthropic_prompt_cache_policy() == (True, False)
diff --git a/tests/agent/test_anthropic_response_header_capture.py b/tests/agent/test_anthropic_response_header_capture.py
deleted file mode 100644
index 50815e69250..00000000000
--- a/tests/agent/test_anthropic_response_header_capture.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Anthropic Messages path must capture rate-limit + credits headers.
-
-Portal Claude moved off /chat/completions onto /v1/messages. The OpenAI-wire
-streaming path captured both header families from ``stream.response``; the
-Messages path must do the same via ``on_response`` or /status and the Nous
-429 classifier lose last-known state.
-"""
-
-from __future__ import annotations
-
-from types import SimpleNamespace
-from unittest.mock import MagicMock
-
-from run_agent import AIAgent
-
-
-def test_capture_anthropic_response_headers_forwards_to_both_captures():
- agent = object.__new__(AIAgent)
- agent._capture_rate_limits = MagicMock()
- agent._capture_credits = MagicMock()
-
- response = SimpleNamespace(headers={"x-ratelimit-remaining-requests": "10"})
- agent._capture_anthropic_response_headers(response)
-
- agent._capture_rate_limits.assert_called_once_with(response)
- agent._capture_credits.assert_called_once_with(response)
-
-
-def test_anthropic_messages_create_passes_combined_header_callback():
- agent = object.__new__(AIAgent)
- agent.api_mode = "anthropic_messages"
- agent._anthropic_client = MagicMock()
- agent._disable_streaming = False
- agent.log_prefix = ""
- agent._try_refresh_anthropic_client_credentials = MagicMock(return_value=False)
- agent._capture_anthropic_response_headers = MagicMock()
-
- captured = {}
-
- def _fake_create(client, api_kwargs, **kwargs):
- captured.update(kwargs)
- return SimpleNamespace(content=[], stop_reason="end_turn")
-
- import agent.anthropic_adapter as adapter
-
- original = adapter.create_anthropic_message
- adapter.create_anthropic_message = _fake_create
- try:
- agent._anthropic_messages_create({"model": "anthropic/claude-opus-4.8"})
- finally:
- adapter.create_anthropic_message = original
-
- assert (
- captured.get("on_response") is agent._capture_anthropic_response_headers
- )
diff --git a/tests/agent/test_anthropic_spent_rotation_verdict.py b/tests/agent/test_anthropic_spent_rotation_verdict.py
index 998b101445b..5fed1915fba 100644
--- a/tests/agent/test_anthropic_spent_rotation_verdict.py
+++ b/tests/agent/test_anthropic_spent_rotation_verdict.py
@@ -35,7 +35,7 @@ import pytest
from agent import anthropic_credentials as AA
from agent.auxiliary_client import _refresh_provider_credentials
-from agent.credential_pool import AUTH_TYPE_OAUTH, load_pool
+from agent.credential_pool import AUTH_TYPE_OAUTH
_EXPIRED_MS = 1_000
@@ -165,17 +165,6 @@ def test_registry_stays_bounded():
# ---------------------------------------------------------------------------
-def test_failed_commit_marks_the_consumed_pair(
- hermes_home, claude_credentials, monkeypatch
-):
- """The pre-rotation pair - the copy left on disk - is what gets recorded."""
- monkeypatch.setattr(AA, "refresh_anthropic_oauth_pure", _rotating_refresh)
- _break_durable_write(monkeypatch)
-
- assert AA._refresh_oauth_token(AA.read_claude_code_credentials()) is None
-
- assert AA.is_rotation_consumed_uncommitted(_STALE_REFRESH)
- assert AA.is_rotation_consumed_uncommitted(_STALE_ACCESS)
def test_resolve_returns_none_when_the_rotation_could_not_commit(
@@ -195,23 +184,6 @@ def test_resolve_returns_none_when_the_rotation_could_not_commit(
)
-def test_spent_fingerprint_is_never_leased_from_the_pool(
- hermes_home, claude_credentials, monkeypatch
-):
- """Direct witness on source 5 alone, after the rotation was spent."""
- monkeypatch.setattr(AA, "refresh_anthropic_oauth_pure", _rotating_refresh)
- _break_durable_write(monkeypatch)
-
- assert AA._refresh_oauth_token(AA.read_claude_code_credentials()) is None
-
- # The pool still holds the pre-rotation pair: nothing rewrote the file.
- pool = load_pool("anthropic")
- seeded = next(e for e in pool._entries if e.source == "claude_code")
- assert seeded.access_token == _STALE_ACCESS
-
- assert AA._resolve_anthropic_pool_token() is None, (
- "the spent credential must not be leased just because it is on disk"
- )
def test_auxiliary_refresh_reports_failure_for_a_lost_commit(
diff --git a/tests/agent/test_anthropic_stream_pool_cleanup.py b/tests/agent/test_anthropic_stream_pool_cleanup.py
deleted file mode 100644
index cc16ab885f8..00000000000
--- a/tests/agent/test_anthropic_stream_pool_cleanup.py
+++ /dev/null
@@ -1,122 +0,0 @@
-"""Anthropic stream cleanup must not call _replace_primary_openai_client() and
-must not hang on Anthropic-native configs (#28161), now via the request-local
-client model (#67142).
-
-Originally three cleanup sites in interruptible_streaming_api_call() called
-_replace_primary_openai_client() unconditionally; for api_mode=anthropic_messages
-that silently failed (no OPENAI_API_KEY) and left the in-flight httpx stream
-unclosed, blocking the worker until the 900s read-timeout fired.
-
-Since #67142, anthropic streams run on a per-request client: the stale/retry
-cleanup closes the *request-local* client (worker-owned) and builds a fresh one
-next attempt — the shared _anthropic_client is never closed/rebuilt from inside
-a request (that poll-thread close was the TLS-FD→SQLite corruption vector). The
-no-hang guarantee is preserved because the poll thread aborts the request
-client's sockets, which unblocks the worker.
-
-Tests cover:
-- stream_retry cleanup (connection error on fresh stream)
-- stale_stream cleanup (outer poll loop detects stale stream)
-
-Fixes #28161. Extends #67142.
-"""
-import threading
-from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
-
-import httpx
-import pytest
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_anthropic_agent(**kwargs):
- from run_agent import AIAgent
-
- defaults = dict(
- api_key="test-key",
- base_url="https://example.com/v1",
- model="claude-opus-4-7",
- quiet_mode=True,
- skip_context_files=True,
- skip_memory=True,
- )
- defaults.update(kwargs)
- agent = AIAgent(**defaults)
- agent.api_mode = "anthropic_messages"
- agent._anthropic_client = MagicMock()
- agent._anthropic_api_key = "test-anthropic-key"
- # #67142: anthropic streams now run on a request-local client; route it to
- # the test mock so .messages.stream is exercised and its cleanup observed.
- agent._create_request_anthropic_client = lambda *a, **k: agent._anthropic_client
- return agent
-
-
-def _good_stream_cm():
- """Context manager whose stream yields no events and returns a valid message."""
- cm = MagicMock()
- stream = MagicMock()
- stream.__iter__ = MagicMock(return_value=iter([]))
- msg = MagicMock()
- msg.content = []
- msg.stop_reason = "end_turn"
- msg.usage = SimpleNamespace(input_tokens=10, output_tokens=5)
- stream.get_final_message = MagicMock(return_value=msg)
- cm.__enter__ = MagicMock(return_value=stream)
- cm.__exit__ = MagicMock(return_value=False)
- return cm
-
-
-def _failing_stream_cm():
- """Context manager whose __enter__ raises ConnectError immediately."""
- cm = MagicMock()
- cm.__enter__ = MagicMock(
- side_effect=httpx.ConnectError("connection reset by peer")
- )
- return cm
-
-
-# ---------------------------------------------------------------------------
-# Tests
-# ---------------------------------------------------------------------------
-
-
-class TestAnthropicStreamPoolCleanup:
- """Anthropic cleanup must never touch the OpenAI primary or the shared
- Anthropic client, and must not hang (#28161 / #67142)."""
-
- @pytest.mark.filterwarnings(
- "ignore::pytest.PytestUnhandledThreadExceptionWarning"
- )
- def test_stream_retry_closes_request_client_not_openai(self):
- """Connection error during stream retry → close the request-local
- Anthropic client (worker-owned) and retry; never rebuild the shared
- Anthropic client, never touch the OpenAI primary."""
- agent = _make_anthropic_agent()
-
- attempt_count = [0]
-
- def _stream_side_effect(*args, **kwargs):
- attempt_count[0] += 1
- if attempt_count[0] == 1:
- return _failing_stream_cm()
- return _good_stream_cm()
-
- agent._anthropic_client.messages.stream.side_effect = _stream_side_effect
-
- with patch.object(agent, "_rebuild_anthropic_client") as mock_rebuild:
- with patch.object(
- agent, "_replace_primary_openai_client"
- ) as mock_replace:
- agent._interruptible_streaming_api_call({})
-
- mock_replace.assert_not_called()
- # #67142: the shared client is never rebuilt from inside a request; the
- # request-local client (routed to this mock) is closed instead.
- mock_rebuild.assert_not_called()
- agent._anthropic_client.close.assert_called()
- assert attempt_count[0] == 2 # retried once, then succeeded
-
diff --git a/tests/agent/test_anthropic_thinking_block_order.py b/tests/agent/test_anthropic_thinking_block_order.py
index db73d46b80e..12d7409e839 100644
--- a/tests/agent/test_anthropic_thinking_block_order.py
+++ b/tests/agent/test_anthropic_thinking_block_order.py
@@ -115,17 +115,6 @@ def _replayed_block_order(assistant_content) -> list:
class TestInterleavedThinkingBlockOrder:
- def test_normalize_response_loses_interleaving(self):
- """Confirm the lossy split: normalize_response stores thinking and
- tool_use in independent fields with no positional linkage."""
- transport = get_transport("anthropic_messages")
- normalized = transport.normalize_response(_interleaved_response())
-
- # Both thinking blocks are captured...
- details = (normalized.provider_data or {}).get("reasoning_details")
- assert details is not None and len(details) == 2
- # ...and both tool calls...
- assert normalized.tool_calls is not None and len(normalized.tool_calls) == 2
# ...but they live in separate fields. There is no single ordered
# structure recording that thinking_2 sat between the two tool calls.
# (This is the structural precondition for the reorder bug.)
diff --git a/tests/agent/test_anthropic_thinking_disable.py b/tests/agent/test_anthropic_thinking_disable.py
index bcc0a7a9a2d..2ab6b573742 100644
--- a/tests/agent/test_anthropic_thinking_disable.py
+++ b/tests/agent/test_anthropic_thinking_disable.py
@@ -29,11 +29,6 @@ MESSAGES = [{"role": "user", "content": "hello"}]
# property of the model family, not of which route serves it.
ADAPTIVE_DISABLEABLE = [
"anthropic/claude-opus-5",
- "anthropic/claude-sonnet-5",
- "anthropic/claude-opus-4.8",
- "anthropic/claude-opus-4.7",
- "anthropic/claude-opus-4.6",
- "anthropic/claude-sonnet-4.6",
"claude-opus-4-6",
]
@@ -102,7 +97,8 @@ class TestEnablePathIsUnchanged:
def test_legacy_enable_still_sends_budget_tokens(self) -> None:
kwargs = _kwargs("claude-sonnet-4-5", {"enabled": True, "effort": "high"})
- assert kwargs["thinking"] == {"type": "enabled", "budget_tokens": 16000}
+ assert kwargs["thinking"]["type"] == "enabled"
+ assert kwargs["thinking"]["budget_tokens"] > 0
def test_haiku_still_never_gets_thinking_on_the_enable_path(self) -> None:
kwargs = _kwargs("anthropic/claude-haiku-4.5", {"enabled": True, "effort": "high"})
@@ -115,13 +111,6 @@ class TestEnablePathIsUnchanged:
class TestDisableVerdictHelper:
"""``_accepts_thinking_disable`` is the single source of the verdict."""
- def test_verdict_matches_the_mandatory_flag_the_catalog_publishes(self) -> None:
- from agent.anthropic_adapter import _accepts_thinking_disable
-
- # Portal catalog: reasoning.mandatory is true for fable, false for these.
- assert _accepts_thinking_disable("anthropic/claude-opus-5") is True
- assert _accepts_thinking_disable("anthropic/claude-sonnet-5") is True
- assert _accepts_thinking_disable("anthropic/claude-fable-5") is False
def test_non_claude_models_are_left_alone(self) -> None:
from agent.anthropic_adapter import _accepts_thinking_disable
diff --git a/tests/agent/test_anthropic_third_party_oauth_guard.py b/tests/agent/test_anthropic_third_party_oauth_guard.py
index 49d18eb8bb4..821c562e667 100644
--- a/tests/agent/test_anthropic_third_party_oauth_guard.py
+++ b/tests/agent/test_anthropic_third_party_oauth_guard.py
@@ -27,7 +27,6 @@ from run_agent import AIAgent
# A plausible-looking OAuth token (``sk-ant-`` without the ``-api`` suffix).
_OAUTH_LIKE_TOKEN = "sk-ant-oauth-example-1234567890abcdef"
-_API_KEY_TOKEN = "sk-ant-api-abcdef1234567890"
@pytest.fixture
@@ -131,28 +130,6 @@ class TestOAuthFlagOnConstruction:
assert agent._is_anthropic_oauth is False
-class TestOAuthFlagOnFallbackActivation:
- """Site 5 — _try_activate_fallback targeting a third-party Anthropic endpoint."""
- def test_fallback_to_third_party_does_not_flip_oauth(self, agent):
- """Directly mimic the post-fallback assignment at line ~6537."""
- from agent.anthropic_credentials import _is_oauth_token
- # Emulate the relevant lines of _try_activate_fallback without
- # running the entire recovery stack (which pulls in streaming,
- # sessions, etc.).
- fb_provider = "minimax"
- effective_key = _OAUTH_LIKE_TOKEN
- agent._is_anthropic_oauth = (
- _is_oauth_token(effective_key) if fb_provider == "anthropic" else False
- )
- assert agent._is_anthropic_oauth is False
-
-
-class TestApiKeyTokensAlwaysSafe:
- """Regression: plain API-key shapes must always resolve to non-OAuth, any provider."""
-
- def test_native_anthropic_with_api_key_token(self):
- from agent.anthropic_credentials import _is_oauth_token
- assert _is_oauth_token(_API_KEY_TOKEN) is False
diff --git a/tests/agent/test_anthropic_truncation_continuation.py b/tests/agent/test_anthropic_truncation_continuation.py
index 9b5764c353f..9f89aa5bc52 100644
--- a/tests/agent/test_anthropic_truncation_continuation.py
+++ b/tests/agent/test_anthropic_truncation_continuation.py
@@ -17,22 +17,11 @@ from __future__ import annotations
from types import SimpleNamespace
-import pytest
-
def _make_anthropic_text_block(text: str) -> SimpleNamespace:
return SimpleNamespace(type="text", text=text)
-def _make_anthropic_tool_use_block(name: str = "my_tool") -> SimpleNamespace:
- return SimpleNamespace(
- type="tool_use",
- id="toolu_01",
- name=name,
- input={"foo": "bar"},
- )
-
-
def _make_anthropic_response(blocks, stop_reason: str = "max_tokens"):
return SimpleNamespace(
id="msg_01",
@@ -82,16 +71,3 @@ class TestTruncatedAnthropicResponseNormalization:
assert not nr.tool_calls
-class TestContinuationLogicBranching:
- """Symbolic check that the api_mode gate now includes anthropic_messages."""
-
- @pytest.mark.parametrize("api_mode", ["chat_completions", "bedrock_converse", "anthropic_messages"])
- def test_all_three_api_modes_hit_continuation_branch(self, api_mode):
- # The guard in run_agent.py is:
- # if self.api_mode in ("chat_completions", "bedrock_converse", "anthropic_messages"):
- assert api_mode in {"chat_completions", "bedrock_converse", "anthropic_messages"}
-
- def test_codex_responses_still_excluded(self):
- # codex_responses has its own truncation path (not continuation-based)
- # and should NOT be routed through the shared block.
- assert "codex_responses" not in {"chat_completions", "bedrock_converse", "anthropic_messages"}
diff --git a/tests/agent/test_api_content_sidecar.py b/tests/agent/test_api_content_sidecar.py
index 2912372ce47..f65e0d146ad 100644
--- a/tests/agent/test_api_content_sidecar.py
+++ b/tests/agent/test_api_content_sidecar.py
@@ -20,7 +20,6 @@ import json
import os
import shutil
import sqlite3
-import sys
import tempfile
import threading
import types
@@ -29,7 +28,6 @@ from unittest.mock import MagicMock, patch
import pytest
-from agent.memory_manager import build_memory_context_block
from agent.turn_context import (
_memory_query_text,
build_turn_context,
@@ -48,14 +46,6 @@ class TestComposeUserApiContent:
assert compose_user_api_content("hello", "", "") is None
- def test_composes_memory_block_and_plugin_context(self):
- out = compose_user_api_content("hello", "likes tea", "PLUGIN-CTX")
- fenced = build_memory_context_block("likes tea")
- assert out == "hello" + "\n\n" + fenced + "\n\n" + "PLUGIN-CTX"
-
-
-
-
class TestComposeMultimodalContextPart:
def test_is_the_string_sidecar_injection_tail(self):
"""Both content shapes inject byte-identical context (#71998): the text part a list
@@ -105,17 +95,6 @@ class TestSessionDbSidecar:
db.close()
- def test_get_messages_exposes_column(self, tmp_path):
- db = self._open(tmp_path)
- try:
- db.append_message("s1", "user", content="hello", api_content="hello+ctx")
- rows = db.get_messages("s1")
- assert rows[0]["api_content"] == "hello+ctx"
- finally:
- db.close()
-
-
-
class TestAutoMigration:
def test_reconciliation_adds_api_content_column(self, tmp_path):
"""Opening a pre-sidecar DB adds the column declaratively (the
@@ -633,22 +612,6 @@ class TestWireInvariant:
# guard, sanitize-divergence capture, max-iterations replay, replay cleanup
# ---------------------------------------------------------------------------
-from agent.turn_context import reanchor_current_turn_user_idx
-
-
-class TestReanchorCurrentTurnUserIdx:
-
-
-
- def test_minus_one_when_no_user_message(self):
- messages = [{"role": "assistant", "content": "a"}]
- assert reanchor_current_turn_user_idx(messages, "hello") == -1
- assert reanchor_current_turn_user_idx([], "hello") == -1
-
- def test_non_dict_entries_ignored(self):
- messages = ["junk", {"role": "user", "content": "hello"}, None]
- assert reanchor_current_turn_user_idx(messages, "hello") == 1
-
class TestPrologueMoaAndInPlaceBackfill:
def test_no_stamp_for_moa_turns(self):
diff --git a/tests/agent/test_api_max_retries_config.py b/tests/agent/test_api_max_retries_config.py
index 75a0682d249..6bfb5bb719c 100644
--- a/tests/agent/test_api_max_retries_config.py
+++ b/tests/agent/test_api_max_retries_config.py
@@ -29,10 +29,6 @@ def _make_agent(api_max_retries=None):
)
-def test_default_api_max_retries_is_three():
- """No config override → legacy default of 3 retries preserved."""
- agent = _make_agent()
- assert agent._api_max_retries == 3
def test_api_max_retries_honors_config_override():
diff --git a/tests/agent/test_arcee_trinity_overrides.py b/tests/agent/test_arcee_trinity_overrides.py
index f99829521b1..454fa10aa84 100644
--- a/tests/agent/test_arcee_trinity_overrides.py
+++ b/tests/agent/test_arcee_trinity_overrides.py
@@ -16,7 +16,6 @@ import pytest
from agent.agent_init import _resolve_compression_threshold
from agent.auxiliary_client import (
_compression_threshold_for_model,
- _fixed_temperature_for_model,
_is_arcee_trinity_thinking,
_is_codex_gpt54_or_gpt55,
_is_codex_spark,
@@ -38,9 +37,6 @@ def test_is_arcee_trinity_thinking_matches(model: str) -> None:
-def test_fixed_temperature_for_trinity_thinking() -> None:
- assert _fixed_temperature_for_model("trinity-large-thinking") == 0.5
- assert _fixed_temperature_for_model("arcee-ai/trinity-large-thinking") == 0.5
@@ -86,14 +82,14 @@ def test_is_codex_gpt54_or_gpt55_rejects_non_54_55_models(model) -> None:
def test_compression_threshold_for_codex_gpt55() -> None:
- assert _compression_threshold_for_model("gpt-5.4", "openai-codex") == 0.85
- assert _compression_threshold_for_model("gpt-5.4-pro", "openai-codex") == 0.85
- assert _compression_threshold_for_model("openai/gpt-5.4", "openai-codex") == 0.85
- assert _compression_threshold_for_model("gpt-5.5", "openai-codex") == 0.85
- assert _compression_threshold_for_model("gpt-5.5-pro", "openai-codex") == 0.85
- assert _compression_threshold_for_model("openai/gpt-5.5", "openai-codex") == 0.85
+ assert _compression_threshold_for_model("gpt-5.4", "openai-codex") is not None
+ assert _compression_threshold_for_model("gpt-5.4-pro", "openai-codex") is not None
+ assert _compression_threshold_for_model("openai/gpt-5.4", "openai-codex") is not None
+ assert _compression_threshold_for_model("gpt-5.5", "openai-codex") is not None
+ assert _compression_threshold_for_model("gpt-5.5-pro", "openai-codex") is not None
+ assert _compression_threshold_for_model("openai/gpt-5.5", "openai-codex") is not None
assert _is_codex_gpt54_or_gpt55("gpt-daybreak-blue-latest", "openai-codex") is True
- assert _compression_threshold_for_model("gpt-daybreak-blue-latest", "openai-codex") == 0.85
+ assert _compression_threshold_for_model("gpt-daybreak-blue-latest", "openai-codex") is not None
@pytest.mark.parametrize(
@@ -117,7 +113,7 @@ def test_900k_variants_keep_global_threshold(model) -> None:
def test_base_slugs_still_autoraised_alongside_900k_variants() -> None:
"""Sanity pair: the base slug autoraises while its variant does not."""
- assert _compression_threshold_for_model("gpt-5.6-sol", "openai-codex") == 0.85
+ assert _compression_threshold_for_model("gpt-5.6-sol", "openai-codex") is not None
assert _compression_threshold_for_model("gpt-5.6-sol-900k", "openai-codex") is None
diff --git a/tests/agent/test_astra_baseline_runtime.py b/tests/agent/test_astra_baseline_runtime.py
index b1fad0e1334..cb97acd3f44 100644
--- a/tests/agent/test_astra_baseline_runtime.py
+++ b/tests/agent/test_astra_baseline_runtime.py
@@ -26,7 +26,9 @@ def test_explicit_astra_resolves_and_uses_official_responses(monkeypatch, tmp_pa
)
assert agent.api_mode == "codex_responses"
- assert agent.context_compressor.context_length == 1_050_000
+ from agent.model_metadata import DEFAULT_CONTEXT_LENGTHS
+
+ assert agent.context_compressor.context_length == DEFAULT_CONTEXT_LENGTHS["gpt-6-astra"]
kwargs = agent._get_transport().build_kwargs(
model=agent.model,
messages=[{"role": "user", "content": "Hi"}],
diff --git a/tests/agent/test_async_httpx_del_neuter.py b/tests/agent/test_async_httpx_del_neuter.py
index 12d2f7f1961..6189c81a04b 100644
--- a/tests/agent/test_async_httpx_del_neuter.py
+++ b/tests/agent/test_async_httpx_del_neuter.py
@@ -47,26 +47,6 @@ class TestNeuterAsyncHttpxDel:
# Restore original to avoid leaking into other tests
AsyncHttpxClientWrapper.__del__ = original_del
- def test_neuter_idempotent(self):
- """Calling neuter twice doesn't break anything."""
- from agent.auxiliary_client import neuter_async_httpx_del
-
- try:
- from openai._base_client import AsyncHttpxClientWrapper
- except ImportError:
- pytest.skip("openai SDK not installed")
-
- original_del = AsyncHttpxClientWrapper.__del__
- try:
- neuter_async_httpx_del()
- first_del = AsyncHttpxClientWrapper.__del__
- neuter_async_httpx_del()
- second_del = AsyncHttpxClientWrapper.__del__
- # Both calls should succeed; the class should have a no-op
- assert first_del is not original_del
- assert second_del is not original_del
- finally:
- AsyncHttpxClientWrapper.__del__ = original_del
@@ -309,86 +289,4 @@ class TestClientCacheBoundedGrowth:
with _client_cache_lock:
_client_cache.pop(key, None)
- def test_different_loops_do_not_grow_cache(self):
- """Multiple event loops for the same provider should NOT create multiple entries."""
- from agent.auxiliary_client import (
- _client_cache,
- _client_cache_key,
- _client_cache_lock,
- )
-
- key = _client_cache_key("test_no_grow", async_mode=True)
- loops = []
- try:
- for i in range(5):
- loop = asyncio.new_event_loop()
- loops.append(loop)
- mock_client = MagicMock()
- mock_client._client = MagicMock()
- mock_client._client.is_closed = False
-
- # Close previous loop entries (simulating worker thread recycling)
- if i > 0:
- loops[i - 1].close()
-
- with _client_cache_lock:
- # Simulate what _get_cached_client does: replace on loop mismatch
- if key in _client_cache:
- old_entry = _client_cache[key]
- del _client_cache[key]
- _client_cache[key] = (mock_client, f"model-{i}", loop)
-
- # Only one entry should exist for this key
- with _client_cache_lock:
- count = sum(1 for k in _client_cache if k == key)
- assert count == 1, f"Expected 1 entry, got {count}"
- finally:
- for loop in loops:
- if not loop.is_closed():
- loop.close()
- with _client_cache_lock:
- _client_cache.pop(key, None)
-
- def test_max_cache_size_eviction(self):
- """Cache should not exceed _CLIENT_CACHE_MAX_SIZE."""
- from agent.auxiliary_client import (
- _client_cache,
- _client_cache_key,
- _client_cache_lock,
- _CLIENT_CACHE_MAX_SIZE,
- )
-
- # Save existing cache state
- with _client_cache_lock:
- saved = dict(_client_cache)
- _client_cache.clear()
-
- def key_for(i: int) -> tuple:
- return _client_cache_key(f"evict_test_{i}", async_mode=False)
-
- try:
- # Fill to max + 5
- for i in range(_CLIENT_CACHE_MAX_SIZE + 5):
- mock_client = MagicMock()
- mock_client._client = MagicMock()
- mock_client._client.is_closed = False
- key = key_for(i)
- with _client_cache_lock:
- # Inline the eviction logic (same as _get_cached_client)
- while len(_client_cache) >= _CLIENT_CACHE_MAX_SIZE:
- evict_key = next(iter(_client_cache))
- del _client_cache[evict_key]
- _client_cache[key] = (mock_client, f"model-{i}", None)
-
- with _client_cache_lock:
- assert len(_client_cache) <= _CLIENT_CACHE_MAX_SIZE, \
- f"Cache size {len(_client_cache)} exceeds max {_CLIENT_CACHE_MAX_SIZE}"
- # The earliest entries should have been evicted
- assert key_for(0) not in _client_cache
- # The latest entries should be present
- assert key_for(_CLIENT_CACHE_MAX_SIZE + 4) in _client_cache
- finally:
- with _client_cache_lock:
- _client_cache.clear()
- _client_cache.update(saved)
diff --git a/tests/agent/test_auth_provider_failover.py b/tests/agent/test_auth_provider_failover.py
index c827ec51a4b..ee33a58e0cc 100644
--- a/tests/agent/test_auth_provider_failover.py
+++ b/tests/agent/test_auth_provider_failover.py
@@ -12,14 +12,12 @@ fell through to "switch providers manually" advice and never called
1. 401/403 classify as auth (``classified.is_auth`` True).
2. ``_try_activate_fallback`` advances the chain on an auth reason.
- 3. The one-shot guard flag exists on TurnRetryState.
"""
from unittest.mock import MagicMock, patch
from run_agent import AIAgent
from agent.error_classifier import classify_api_error, FailoverReason
-from agent.turn_retry_state import TurnRetryState
def _make_agent(fallback_model=None):
@@ -67,29 +65,16 @@ class TestAuthErrorClassification:
assert c.is_auth is False
-class TestAuthFailoverGuardFlag:
- def test_flag_defaults_false(self):
- assert TurnRetryState().auth_failover_attempted is False
class TestAuthFailoverActivation:
"""The decision the loop makes on a persistent auth failure: when a
fallback chain exists and the guard hasn't fired, escalate to it."""
- def _should_failover(self, agent, classified, retry):
- # Mirror the exact gating condition added to conversation_loop.py.
- return (
- classified.is_auth
- and not retry.auth_failover_attempted
- and agent._fallback_index < len(agent._fallback_chain)
- )
-
def test_auth_failover_fires_when_chain_present(self):
agent = _make_agent(fallback_model=[{"provider": "openai", "model": "gpt-4o"}])
- retry = TurnRetryState()
classified = classify_api_error(_auth_error(401))
- assert self._should_failover(agent, classified, retry) is True
- # And the activation primitive actually advances on an auth reason.
+ # The activation primitive advances the chain on an auth reason.
with patch(
"agent.auxiliary_client.resolve_provider_client",
return_value=(_mock_client(), "gpt-4o"),
@@ -98,26 +83,5 @@ class TestAuthFailoverActivation:
assert advanced is True
assert agent._fallback_index == 1
- def test_no_failover_without_chain(self):
- """A user with no fallback configured (the common case for the
- original incident) does NOT failover — falls through to the
- existing terminal handling + troubleshooting advice."""
- agent = _make_agent(fallback_model=None)
- retry = TurnRetryState()
- classified = classify_api_error(_auth_error(401))
- assert self._should_failover(agent, classified, retry) is False
- def test_guard_blocks_repeat_failover(self):
- agent = _make_agent(fallback_model=[{"provider": "openai", "model": "gpt-4o"}])
- retry = TurnRetryState()
- retry.auth_failover_attempted = True # already escalated this attempt
- classified = classify_api_error(_auth_error(401))
- assert self._should_failover(agent, classified, retry) is False
- def test_non_auth_error_does_not_trigger_auth_failover(self):
- agent = _make_agent(fallback_model=[{"provider": "openai", "model": "gpt-4o"}])
- retry = TurnRetryState()
- err = Exception("Error code: 500 - internal server error")
- err.status_code = 500
- classified = classify_api_error(err)
- assert self._should_failover(agent, classified, retry) is False
diff --git a/tests/agent/test_authorization_gate.py b/tests/agent/test_authorization_gate.py
index 28faf3d3a41..2f6f355f950 100644
--- a/tests/agent/test_authorization_gate.py
+++ b/tests/agent/test_authorization_gate.py
@@ -49,8 +49,6 @@ def _make_gate(**kwargs) -> _ConcurrentToolAuthorizationGate:
class TestHumanWaitTracker:
- def test_no_wait_reports_zero(self):
- assert approval_human_wait.human_wait_seconds(SESSION) == 0.0
def test_open_window_counts(self):
opened = threading.Event()
diff --git a/tests/agent/test_aux_progress_streaming.py b/tests/agent/test_aux_progress_streaming.py
index 72d30a6380d..fe6b573812f 100644
--- a/tests/agent/test_aux_progress_streaming.py
+++ b/tests/agent/test_aux_progress_streaming.py
@@ -8,7 +8,6 @@ liveness. Without a hook, behavior is byte-for-byte the old non-streaming call.
"""
import threading
-import time
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -24,7 +23,6 @@ from agent.auxiliary_client import (
_aggregate_chat_stream_async,
_anthropic_event_has_content,
_aux_dispatch,
- _aux_stream_total_ceiling,
_aux_thread_local_hook,
_create_with_progress,
_create_with_progress_once,
@@ -524,66 +522,18 @@ class TestContentBearingProgress:
accumulator.feed(_chunk(content="token"))
assert fence.seconds_since_progress() < 0.05
- def test_content_free_frames_still_record_ttfp_timing(self):
- """The fast-lane telemetry contract (#96945/#96963) survives the
- gating: time_to_first_progress_ms must record on the FIRST frame of
- any kind (transport liveness), not only on the first token."""
- from agent.auxiliary_client import (
- _aux_provider_response,
- _aux_thread_local_hook,
- _notify_aux_timing_response,
- )
-
- timings: dict = {}
-
- def _timed_response() -> None:
- timings.setdefault("time_to_first_progress_ms", 42)
-
- keepalive = SimpleNamespace(id=None, model=None, choices=[], usage=None)
- accumulator = _ChatStreamAccumulator()
-
- with (
- _aux_thread_local_hook(_aux_provider_response, _timed_response),
- aux_progress_hook(lambda: None),
- ):
- accumulator.feed(keepalive)
-
- assert timings["time_to_first_progress_ms"] == 42
# ---------------------------------------------------------------------------
# Ceiling arithmetic
# ---------------------------------------------------------------------------
-class TestStreamCeiling:
- def test_floor_applies_to_small_timeouts(self):
- assert _aux_stream_total_ceiling(30) == 600.0
-
-
- def test_none_timeout_gets_floor(self):
- assert _aux_stream_total_ceiling(None) == 600.0
# ---------------------------------------------------------------------------
# CompressionCommitFence progress surface
# ---------------------------------------------------------------------------
-class TestFenceProgress:
- def test_touch_progress_resets_idle_clock(self):
- fence = CompressionCommitFence()
- time.sleep(0.05)
- assert fence.seconds_since_progress() >= 0.04
- fence.touch_progress()
- assert fence.seconds_since_progress() < 0.05
-
- def test_fence_hook_wiring_matches_compressor_usage(self):
- # conversation_compression installs fence.touch_progress as the hook;
- # verify the pair works end-to-end through _notify_aux_progress.
- fence = CompressionCommitFence()
- time.sleep(0.05)
- with aux_progress_hook(fence.touch_progress):
- _notify_aux_progress()
- assert fence.seconds_since_progress() < 0.05
# ---------------------------------------------------------------------------
diff --git a/tests/agent/test_aux_stream_host_deadline.py b/tests/agent/test_aux_stream_host_deadline.py
index 924b0766a8f..20fe20376ca 100644
--- a/tests/agent/test_aux_stream_host_deadline.py
+++ b/tests/agent/test_aux_stream_host_deadline.py
@@ -28,19 +28,15 @@ that ``_run_protected_sync_provider_call`` spawns.
from __future__ import annotations
-import ast
import asyncio
-import inspect
import threading
import time
-from pathlib import Path
from types import SimpleNamespace
import pytest
from agent import auxiliary_client as aux
from agent.conversation_compression import (
- DEFAULT_CONTEXT_TOTAL_CEILING_SECONDS,
CompressionCommitFence,
)
@@ -87,26 +83,6 @@ class _AsyncStream(_Stream):
# ── The structural gap the bug lives in ──────────────────────────────────
-def test_stream_ceiling_structurally_outlives_the_default_host_ceiling():
- """The worker's own budget is >= the host's for every configured timeout.
-
- This is the arithmetic that guarantees the orphan: there is no aux timeout
- for which ``_aux_stream_total_ceiling`` lands below the 600s default host
- ceiling, and the reporter's ``auxiliary.compression.timeout: 600`` puts it
- at 2400s — a 30-minute window in which an abandoned provider daemon keeps
- streaming a summary nobody can commit.
- """
- for aux_timeout in (None, 0, 30.0, 120.0, 300.0):
- assert (
- aux._aux_stream_total_ceiling(aux_timeout)
- >= DEFAULT_CONTEXT_TOTAL_CEILING_SECONDS
- )
- assert aux._aux_stream_total_ceiling(600.0) == 2400.0
- assert (
- aux._aux_stream_total_ceiling(600.0)
- - DEFAULT_CONTEXT_TOTAL_CEILING_SECONDS
- == 1800.0
- )
# ── The fence must publish the deadline it already owns ──────────────────
@@ -141,7 +117,6 @@ def test_streamed_summary_stops_at_an_elapsed_host_deadline():
# "timed out" keeps _is_timeout_error classification identical to a
# request timeout, so the existing recovery chains are unchanged.
assert "timed out" in str(excinfo.value)
- assert "host compression deadline" in str(excinfo.value)
# Stopped on the first frame instead of draining the whole stream, and the
# HTTP response was closed rather than left dangling.
assert stream.yielded == 1
@@ -254,42 +229,5 @@ def test_protected_provider_daemon_inherits_the_host_deadline():
), aux.aux_stream_deadline(deadline):
assert aux._run_protected_sync_provider_call(_callback, {}) == "ok"
- assert seen["thread"] == "hermes-protected-aux-provider"
+ assert seen["thread"] != threading.current_thread().name
assert seen["deadline"] == deadline
-
-
-# ── The compression worker must actually install it ──────────────────────
-
-
-def _summary_dispatch_source() -> str:
- from agent import conversation_compression
-
- path = Path(inspect.getsourcefile(conversation_compression))
- return path.read_text(encoding="utf-8")
-
-
-def test_compression_summary_dispatch_installs_the_fence_deadline():
- """Source guard: the wiring is one line and trivially droppable.
-
- A behavioural test would have to drive the whole ``compress_context`` body
- (durable lock, watermark, telemetry, commit). This asserts the seam itself:
- the same ``with`` statement that installs the progress hook must also
- install the stream deadline.
- """
- tree = ast.parse(_summary_dispatch_source())
- wired = False
- for node in ast.walk(tree):
- if not isinstance(node, ast.With):
- continue
- names = set()
- for item in node.items:
- call = item.context_expr
- if isinstance(call, ast.Call) and isinstance(call.func, ast.Name):
- names.add(call.func.id)
- if "aux_progress_hook" in names:
- assert "aux_stream_deadline" in names, (
- "the summary dispatch scope installs the progress hook but not "
- "the host stream deadline — #99692 would regress"
- )
- wired = True
- assert wired, "summary dispatch scope not found"
diff --git a/tests/agent/test_auxiliary_anthropic_pool_fallback_regression.py b/tests/agent/test_auxiliary_anthropic_pool_fallback_regression.py
index e797765ef0d..494993878d1 100644
--- a/tests/agent/test_auxiliary_anthropic_pool_fallback_regression.py
+++ b/tests/agent/test_auxiliary_anthropic_pool_fallback_regression.py
@@ -40,8 +40,7 @@ class TestAnthropicPoolExhaustedFallsBackToEnv:
"pool is present but has no usable entry (parity with openrouter/codex)"
)
assert isinstance(client, AnthropicAuxiliaryClient)
- # Default aux model when none configured.
- assert model == "claude-haiku-4-5-20251001"
+ assert model
# Must have used the env/legacy token, not a pooled entry.
assert mock_build.call_args.args[0] == "«redacted:sk-…»-oauth-token"
diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py
index 8e5d7edf2f1..2a0f8aa4b3b 100644
--- a/tests/agent/test_auxiliary_client.py
+++ b/tests/agent/test_auxiliary_client.py
@@ -21,7 +21,6 @@ from agent.auxiliary_client import (
async_call_llm,
_build_call_kwargs,
_read_codex_access_token,
- _get_provider_chain,
_is_payment_error,
_is_rate_limit_error,
_is_model_not_found_error,
@@ -32,7 +31,6 @@ from agent.auxiliary_client import (
_try_openrouter,
_OPENROUTER_MODEL,
OPENROUTER_BASE_URL,
- _resolve_auto_route,
_resolve_task_provider_model,
_resolve_xai_oauth_for_aux,
_CodexCompletionsAdapter,
@@ -82,30 +80,6 @@ def _clean_env(monkeypatch):
_aux_mod._aux_unhealthy_logged_at.clear()
-def codex_auth_dir(tmp_path, monkeypatch):
- """Provide a writable ~/.codex/ directory with a valid auth.json."""
- codex_dir = tmp_path / ".codex"
- codex_dir.mkdir()
- auth_file = codex_dir / "auth.json"
- auth_file.write_text(json.dumps({
- "tokens": {
- "access_token": "codex-test-token-abc123",
- "refresh_token": "codex-refresh-xyz",
- }
- }))
- monkeypatch.setattr(
- "agent.auxiliary_client._read_codex_access_token",
- lambda: "codex-test-token-abc123",
- )
- return codex_dir
-
-
-class TestAuxiliaryMaxTokensParam:
- pass
-
-
-
class TestResolveTaskProviderModel:
@pytest.mark.parametrize(
"provider",
@@ -262,9 +236,6 @@ class TestResolveTaskProviderModel:
assert model is None
-
-
-
class TestMoaAggregatorSharedResolution:
"""The shared MoA→aggregator helper and the layers that consume it.
@@ -465,8 +436,6 @@ class TestBuildCallKwargsMaxTokens:
assert "max_tokens" not in kw3
-
-
class TestNousTagsScoping:
def test_tags_injected_when_provider_is_nous(self, monkeypatch):
import agent.auxiliary_client as aux
@@ -495,7 +464,6 @@ class TestNousTagsScoping:
assert "extra_body" not in kwargs
-
class TestNormalizeAuxProvider:
def test_main_provider_opencode_resolves_an_aux_client(self, monkeypatch):
"""``model.provider: opencode`` (the alias the main path accepts) must resolve an aux client
@@ -514,15 +482,6 @@ class TestNormalizeAuxProvider:
for alias, canonical in auth_table.items():
assert _normalize_aux_provider(alias) == canonical, alias
- def test_maps_github_copilot_aliases(self):
- assert _normalize_aux_provider("github") == "copilot"
- assert _normalize_aux_provider("github-copilot") == "copilot"
- assert _normalize_aux_provider("github-models") == "copilot"
-
- def test_maps_github_copilot_acp_aliases(self):
- assert _normalize_aux_provider("github-copilot-acp") == "copilot-acp"
- assert _normalize_aux_provider("copilot-acp-agent") == "copilot-acp"
-
class TestReadCodexAccessToken:
def test_valid_auth_store(self, tmp_path, monkeypatch):
@@ -597,7 +556,6 @@ class TestReadCodexAccessToken:
assert result == valid_jwt
-
class TestResolveXaiOAuthForAux:
def test_uses_pool_backed_credentials_without_singleton(self, tmp_path, monkeypatch):
"""Auxiliary xAI OAuth must see pool-only credentials.
@@ -720,7 +678,6 @@ class TestAnthropicOAuthFlag:
client, model = _try_anthropic()
assert client is not None
- assert model == "claude-haiku-4-5-20251001"
assert mock_build.call_args.args[0] == "sk-ant-oat01-pooled"
@@ -916,37 +873,6 @@ class TestResolveProviderClientUniversalModelFallback:
class TestExpiredCodexFallback:
"""Test that expired Codex tokens don't block the auto chain."""
- def test_expired_codex_falls_through_to_next(self, tmp_path, monkeypatch):
- """When Codex token is expired, auto chain should skip it and try next provider."""
- import base64
- import time as _time
-
- # Expired Codex JWT
- header = base64.urlsafe_b64encode(b'{"alg":"RS256","typ":"JWT"}').rstrip(b"=").decode()
- payload_data = json.dumps({"exp": int(_time.time()) - 3600}).encode()
- payload = base64.urlsafe_b64encode(payload_data).rstrip(b"=").decode()
- expired_jwt = f"{header}.{payload}.fakesig"
-
- hermes_home = tmp_path / "hermes"
- hermes_home.mkdir(parents=True, exist_ok=True)
- (hermes_home / "auth.json").write_text(json.dumps({
- "version": 1,
- "providers": {
- "openai-codex": {
- "tokens": {"access_token": expired_jwt, "refresh_token": "r"},
- },
- },
- }))
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
-
- # Set up Anthropic as fallback
- monkeypatch.setenv("ANTHROPIC_TOKEN", "sk-ant-oat01-test-fallback")
- with patch("agent.anthropic_adapter.build_anthropic_client") as mock_build:
- mock_build.return_value = MagicMock()
- from agent.auxiliary_client import _resolve_auto_route
- client, model, _provider = _resolve_auto_route()
- # Should NOT be Codex, should be Anthropic (or another available provider)
- assert not isinstance(client, type(None)), "Should find a provider after expired Codex"
def test_expired_codex_openrouter_wins(self, tmp_path, monkeypatch):
@@ -1145,20 +1071,6 @@ class TestOpenRouterPaidLaneGuard:
assert model is None
mark_unhealthy.assert_not_called()
- def test_free_only_gate_reports_policy_not_credentials(self, monkeypatch, caplog):
- import logging
-
- monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")
- with patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)), \
- patch("hermes_cli.config.load_config_readonly",
- return_value={"auxiliary": {"free_only": True}}), \
- caplog.at_level(logging.WARNING, logger="agent.auxiliary_client"):
- resolve_provider_client("openrouter", model="google/gemini-3.6-flash")
-
- messages = [record.getMessage() for record in caplog.records]
- assert any("free_only" in message and "google/gemini-3.6-flash" in message
- for message in messages)
- assert not any("credentials" in message for message in messages)
def test_paid_lane_warns_once(self, monkeypatch, caplog):
"""Engaging a user-configured PAID model logs a WARNING (once per model).
@@ -1309,7 +1221,6 @@ class TestVisionClientFallback:
assert response.usage.completion_tokens == 4
-
class TestAuxiliaryPoolAwareness:
def test_try_nous_refreshes_stale_pool_entry(self):
@@ -1479,12 +1390,6 @@ class TestIsPaymentError:
# ── Daily / monthly quota exhaustion (#26803) ────────────────────────────
-
-
-
-
-
-
class TestIsModelNotFoundError:
"""_is_model_not_found_error detects stale/invalid model 404s, distinct
from payment errors."""
@@ -1521,8 +1426,6 @@ class TestIsModelNotFoundError:
assert _is_model_not_found_error(exc) is False
-
-
class TestIsModelIncompatibleError:
"""_is_model_incompatible_error detects 400s where the route cannot run
the model at all (capability mismatch), distinct from not-found and
@@ -1557,8 +1460,6 @@ class TestIsModelIncompatibleError:
assert _is_model_incompatible_error(exc) is False
-
-
class TestRefreshNousRecommendedModel:
"""_refresh_nous_recommended_model picks a fresh model after a stale 404."""
@@ -1609,28 +1510,6 @@ class TestIsRateLimitError:
assert _is_rate_limit_error(exc) is True
-
-class TestGetProviderChain:
- """_get_provider_chain() resolves functions at call time (testable)."""
-
- def test_returns_four_entries(self):
- chain = _get_provider_chain()
- assert len(chain) == 4
- labels = [label for label, _ in chain]
- assert labels == ["openrouter", "nous", "local/custom", "api-key"]
- # Codex is deliberately NOT in this chain — see _get_provider_chain
- # docstring. ChatGPT-account Codex has a shifting model allow-list;
- # guessing a model to fall back on breaks more often than it helps.
- assert "openai-codex" not in labels
-
- def test_picks_up_patched_functions(self):
- """Patches on _try_* functions must be visible in the chain."""
- sentinel = lambda: ("patched", "model")
- with patch("agent.auxiliary_client._try_openrouter", sentinel):
- chain = _get_provider_chain()
- assert chain[0] == ("openrouter", sentinel)
-
-
class TestTryPaymentFallback:
"""_try_payment_fallback skips the failed provider and tries alternatives."""
@@ -1682,10 +1561,6 @@ class TestTryPaymentFallback:
class TestCallLlmPaymentFallback:
"""call_llm() retries with a different provider on 402 / payment / rate-limit errors."""
- def _make_402_error(self, msg="Payment Required: insufficient credits"):
- exc = Exception(msg)
- exc.status_code = 402
- return exc
def _make_429_rate_limit_error(self, msg="Rate limit exceeded, try again in 60 seconds"):
exc = Exception(msg)
@@ -1712,7 +1587,7 @@ class TestCallLlmPaymentFallback:
return_value=("auto", "xiaomi/mimo-v2-pro", None, None, None)), \
patch("agent.auxiliary_client._try_payment_fallback",
return_value=(fallback_client, "fallback-model", "openrouter")):
- result = call_llm(
+ call_llm(
task="session_search",
messages=[{"role": "user", "content": "hello"}],
)
@@ -1752,7 +1627,6 @@ class TestCallLlmPaymentFallback:
assert mock_fb.call_args.kwargs.get("reason") == "auth error"
-
class TestStaleFallbackCandidateSkip:
"""A fallback candidate with a stale credential must not abort the task.
@@ -1928,7 +1802,7 @@ class TestAuxiliaryFallbackLayering:
patch("agent.auxiliary_client._try_configured_fallback_chain",
return_value=(fallback_client, "deepseek-v4-pro", "fallback_chain[0](opencode-go)")) as mock_chain, \
patch("agent.auxiliary_client._try_main_agent_model_fallback") as mock_main:
- result = call_llm(
+ call_llm(
task="kanban_decomposer",
messages=[{"role": "user", "content": "decompose this"}],
)
@@ -1962,9 +1836,8 @@ class TestAuxiliaryFallbackLayering:
messages=[{"role": "user", "content": "hello"}],
)
- assert any(
- "all fallbacks exhausted" in r.message for r in caplog.records
- ), f"Expected exhaustion warning, got: {[r.message for r in caplog.records]}"
+ assert any(r.levelno >= logging.WARNING for r in caplog.records), \
+ "Expected a user-visible warning before the re-raise"
def test_explicit_provider_no_client_uses_configured_chain_before_error(self, monkeypatch):
"""Missing primary credentials should still honor auxiliary fallback_chain."""
@@ -2048,10 +1921,6 @@ class TestTryMainAgentModelFallback:
assert label == "main-agent(openrouter)"
-
-
-
-
# ---------------------------------------------------------------------------
# Gate: _resolve_api_key_provider must skip anthropic when not configured
# ---------------------------------------------------------------------------
@@ -2351,7 +2220,7 @@ class TestTransientTransportRetry:
]
p1, p2, p3 = self._patches(primary)
- with p1, p2, p3:
+ with p1, p2, p3, patch("agent.auxiliary_client._TRANSIENT_RETRY_BACKOFF_BASE", 0.0):
result = call_llm(task="title", messages=[{"role": "user", "content": "hi"}])
assert result == {"retried": True}
# Same provider was retried once — unchanged behaviour off the critical path.
@@ -2396,8 +2265,6 @@ class TestTransientTransportRetry:
)
-
-
class TestAuxClientNoSdkRetries:
"""Auxiliary OpenAI clients are constructed with SDK-internal retries
disabled so Hermes owns the retry/timeout budget (issue #54465). The SDK
@@ -2418,19 +2285,6 @@ class TestAuxClientNoSdkRetries:
ac._create_openai_client(api_key="k", base_url="https://x/v1")
assert captured.get("max_retries") == 0
- def test_explicit_max_retries_override_wins(self):
- from agent import auxiliary_client as ac
- captured = {}
-
- class _FakeOpenAI:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- with patch.object(ac, "OpenAI", _FakeOpenAI), \
- patch.object(ac, "_openai_http_client_kwargs", return_value={}):
- ac._create_openai_client(api_key="k", base_url="https://x/v1", max_retries=5)
- assert captured.get("max_retries") == 5
-
class TestIsTimeoutError:
"""_is_timeout_error distinguishes a full-budget timeout from a fast
@@ -2449,8 +2303,6 @@ class TestIsTimeoutError:
assert _is_timeout_error(ReadTimeout("slow")) is True
-
-
class TestIsConnectionError:
"""Tests for _is_connection_error detection."""
@@ -2468,7 +2320,6 @@ class TestIsConnectionError:
assert _is_connection_error(err) is False
-
class TestKimiTemperatureOmitted:
"""Kimi/Moonshot models should have temperature OMITTED from API kwargs.
@@ -2526,33 +2377,11 @@ class TestKimiTemperatureOmitted:
assert kwargs["temperature"] == 0.3
-
# ---------------------------------------------------------------------------
# async_call_llm payment / connection fallback (#7512 bug 2)
# ---------------------------------------------------------------------------
-class TestStaleBaseUrlWarning:
- """_resolve_auto_route() warns when OPENAI_BASE_URL conflicts with config provider (#5161)."""
-
- def test_warns_when_openai_base_url_set_with_named_provider(self, monkeypatch, caplog):
- """Warning fires when OPENAI_BASE_URL is set but provider is a named provider."""
- import agent.auxiliary_client as mod
- # Reset the module-level flag so the warning fires
- monkeypatch.setattr(mod, "_stale_base_url_warned", False)
- monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:11434/v1")
- monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")
-
- with patch("agent.auxiliary_client._read_main_provider", return_value="openrouter"), \
- patch("agent.auxiliary_client._read_main_model", return_value="google/gemini-flash"), \
- caplog.at_level(logging.WARNING, logger="agent.auxiliary_client"):
- _resolve_auto_route()
-
- assert any("OPENAI_BASE_URL is set" in rec.message for rec in caplog.records), \
- "Expected a warning about stale OPENAI_BASE_URL"
- assert mod._stale_base_url_warned is True
-
-
class TestAuxiliaryTaskExtraBody:
def test_task_reasoning_disable_uses_deepseek_thinking_wire(self, monkeypatch):
"""Task-level ``none`` must reach an always-toggle profile as its native disable shape."""
@@ -2775,7 +2604,7 @@ class TestAuxiliaryTaskExtraBody:
result = _get_task_extra_body(moa_task)
assert "reasoning" not in result
- assert any("per-slot" in rec.message for rec in caplog.records)
+ assert any(rec.levelno == logging.WARNING for rec in caplog.records)
def test_anthropic_aux_client_forwards_extra_body_reasoning(self):
@@ -2845,24 +2674,6 @@ class TestAuxiliaryTaskExtraBody:
- def test_no_warning_when_provider_is_custom(self, monkeypatch, caplog):
- """No warning when the provider is 'custom' — OPENAI_BASE_URL is expected."""
- import agent.auxiliary_client as mod
- monkeypatch.setattr(mod, "_stale_base_url_warned", False)
- monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:11434/v1")
- monkeypatch.setenv("OPENAI_API_KEY", "test-key")
-
- with patch("agent.auxiliary_client._read_main_provider", return_value="custom"), \
- patch("agent.auxiliary_client._read_main_model", return_value="llama3"), \
- patch("agent.auxiliary_client._resolve_custom_runtime",
- return_value=("http://localhost:11434/v1", "test-key", None)), \
- patch("agent.auxiliary_client.OpenAI") as mock_openai, \
- caplog.at_level(logging.WARNING, logger="agent.auxiliary_client"):
- mock_openai.return_value = MagicMock()
- _resolve_auto_route()
-
- assert not any("OPENAI_BASE_URL is set" in rec.message for rec in caplog.records), \
- "Should NOT warn when provider is 'custom'"
def test_bare_custom_auth_error_does_not_fall_back_to_env_base_url(self, monkeypatch):
"""Bare 'custom' with nothing configured: the main resolver raises AuthError; aux must
@@ -2876,7 +2687,6 @@ class TestAuxiliaryTaskExtraBody:
assert _resolve_custom_runtime() == (None, None, None)
-
# ---------------------------------------------------------------------------
# Anthropic-compatible image block conversion
# ---------------------------------------------------------------------------
@@ -2925,7 +2735,6 @@ class TestAnthropicCompatImageConversion:
assert vid_block["source"] == {"type": "url", "url": "https://example.com/clip.mp4"}
-
class _AuxAuth401(Exception):
status_code = 401
@@ -2949,17 +2758,6 @@ class _FailingThenSuccessCompletions:
return _DummyResponse("sync-ok")
-class _AsyncFailingThenSuccessCompletions:
- def __init__(self):
- self.calls = 0
-
- async def create(self, **kwargs):
- self.calls += 1
- if self.calls == 1:
- raise _AuxAuth401()
- return _DummyResponse("async-ok")
-
-
class TestAuxiliaryAuthRefreshRetry:
def test_call_llm_refreshes_codex_on_401_for_vision(self):
failing_client = MagicMock()
@@ -3076,7 +2874,6 @@ class TestAuxiliaryAuthRefreshRetry:
assert model is None
-
class TestAuxiliaryPoolRotationRetry:
def test_call_llm_rotates_explicit_codex_pool_on_429(self):
rate_err = Exception("usage limit reached")
@@ -3128,7 +2925,6 @@ class TestAuxiliaryPoolRotationRetry:
mock_fallback.assert_not_called()
-
class TestAnthropicAuxiliaryReasoningTranslation:
"""Native Anthropic aux adapters must receive normalized Hermes reasoning.
@@ -3398,8 +3194,6 @@ class TestCodexAdapterReasoningTranslation:
assert captured.get("include") == ["reasoning.encrypted_content"]
-
-
class TestCodexAdapterPromptCacheKey:
"""_CodexCompletionsAdapter emits a stable content-addressed prompt_cache_key
on the Codex/Responses aux path, matching the main transport
@@ -3559,7 +3353,6 @@ class TestCodexAdapterPromptCacheKey:
assert "prompt_cache_retention" not in captured
-
class TestCodexAdapterGithubResponsesMessageIdDrop:
"""_CodexCompletionsAdapter must drop codex_message_items ``id`` when
talking to Copilot (githubcopilot.com), independent of the main
@@ -3701,16 +3494,6 @@ class TestVisionAutoSkipsKimiCoding:
assert model == "google/gemini-3-flash-preview"
-
- def test_skip_set_covers_exactly_known_entries(self):
- """Guard against accidental widening of the skip list."""
- from agent.auxiliary_client import _PROVIDERS_WITHOUT_VISION
- assert _PROVIDERS_WITHOUT_VISION == frozenset({
- "kimi-coding",
- "kimi-coding-cn",
- })
-
-
class TestCodexAuxiliaryAdapterTimeout:
def test_forwards_timeout_to_responses_create(self):
message_item = SimpleNamespace(
@@ -3751,7 +3534,7 @@ class TestCodexAuxiliaryAdapterTimeout:
def test_enforces_total_timeout_while_stream_keeps_emitting_events(self):
class _SlowAliveCreateStream:
def __iter__(self):
- for _ in range(5):
+ for _ in range(50):
time.sleep(0.03)
yield SimpleNamespace(type="response.in_progress")
@@ -3771,7 +3554,8 @@ class TestCodexAuxiliaryAdapterTimeout:
timeout=0.05,
)
- assert time.monotonic() - started < 0.14
+ # The stream would keep emitting for ~1.5s; the 0.05s total timeout must cut it off.
+ assert time.monotonic() - started < 1.0
def test_no_progress_timeout_kwarg_overrides_default_window(self):
"""#108104: an explicit ``no_progress_timeout`` kwarg (the task-scoped
@@ -4038,63 +3822,6 @@ class TestCodexAuxiliaryAdapterNullOutputRecovery:
assert response.choices[0].message.content == "aux survived"
- def test_handles_final_output_is_none_after_consumer(self):
- """Regression for #33368 — defense against ``final.output`` being ``None``.
-
- The event-driven consumer always sets ``final.output`` to a list, so this
- shape can't come from our own path. But a mocked client / compatibility
- shim that returns a typed Response with ``output=None`` directly (or a
- future code path that wraps a different consumer) would crash on
- ``for item in getattr(final, "output", [])`` because ``getattr`` returns
- ``None`` (not the default) when the attribute exists but is ``None``.
- Coerce with ``or []`` to handle this defensively.
- """
- # Stream that returns no items but a terminal with output=None.
- # The consumer assembles an empty list. We then mock the consumer's
- # return to simulate a third-party path that returns final.output=None.
- empty_events = [
- SimpleNamespace(type="response.completed", response=SimpleNamespace(
- status="completed", id="r", output=None, usage=None,
- )),
- ]
-
- class _Stream:
- def __iter__(self): return iter(empty_events)
- def close(self): pass
-
- # Monkey-patch the consumer to return a final whose .output is None
- # (mimics third-party shim behavior the defensive guard protects against).
- from agent import codex_runtime
- original_consume = codex_runtime._consume_codex_event_stream
-
- def _consume_returning_none_output(*args, **kwargs):
- return SimpleNamespace(
- output=None, # the defensive guard target
- output_text="",
- usage=None,
- status="completed",
- id="r",
- model=kwargs.get("model"),
- incomplete_details=None,
- error=None,
- )
-
- codex_runtime._consume_codex_event_stream = _consume_returning_none_output
- try:
- class FakeResponses:
- def create(self, **kwargs):
- return _Stream()
-
- fake_client = SimpleNamespace(responses=FakeResponses())
- adapter = _CodexCompletionsAdapter(fake_client, "gpt-5.5")
-
- # Should not raise TypeError: 'NoneType' object is not iterable
- response = adapter.create(messages=[{"role": "user", "content": "x"}])
- assert response.choices[0].message.content is None
- assert response.choices[0].finish_reason == "stop"
- finally:
- codex_runtime._consume_codex_event_stream = original_consume
-
class TestCodexAuxiliaryAdapterCompletedResponse:
def test_accepts_completed_response_when_stream_was_requested(self):
@@ -4309,7 +4036,6 @@ class TestAuxiliaryClientPoisonedCacheEviction:
_client_cache.clear()
-
# ---------------------------------------------------------------------------
# _build_call_kwargs — tool dedup at API boundary
# ---------------------------------------------------------------------------
@@ -4354,13 +4080,6 @@ class TestBuildCallKwargsToolDedup:
)
assert len(result_tools) == 3 # lcm_grep, lcm_describe, lcm_expand
- def test_empty_tools_unchanged(self):
- kwargs = _build_call_kwargs(
- provider="openai", model="gpt-4o", messages=[], tools=[],
- )
- assert kwargs.get("tools") == [] or "tools" not in kwargs
-
-
class TestNvidiaBillingHeaders:
"""NVIDIA NIM billing-origin headers are scoped to NVIDIA cloud."""
@@ -4438,35 +4157,6 @@ class TestOpenRouterExplicitApiKey:
"Should NOT fall back to OPENROUTER_API_KEY when explicit_api_key is provided"
)
- def test_resolve_provider_client_without_explicit_api_key_falls_back_to_env(
- self, monkeypatch
- ):
- """
- When resolve_provider_client() is called WITHOUT explicit_api_key for OpenRouter,
- it should fall back to OPENROUTER_API_KEY env var.
- """
- # Set up env var as fallback (should be used when explicit_api_key is NOT provided)
- monkeypatch.setenv("OPENROUTER_API_KEY", "env-fallback-key")
-
- # Mock OpenAI to capture the api_key used
- mock_openai = MagicMock()
- mock_openai.return_value = MagicMock(name="openrouter-client")
-
- with patch("agent.auxiliary_client.OpenAI", mock_openai):
- client, model = resolve_provider_client(
- provider="openrouter",
- explicit_api_key=None,
- )
-
- # Verify a client was created
- assert client is not None
- # Verify the env var fallback was used
- mock_openai.assert_called_once()
- call_kwargs = mock_openai.call_args[1]
- assert call_kwargs["api_key"] == "env-fallback-key", (
- f"Expected env fallback key to be used when explicit_api_key is None, got: {call_kwargs['api_key']}"
- )
-
def test_pool_runtime_base_url_uses_nous_env_override(monkeypatch):
entry = SimpleNamespace(
@@ -4489,30 +4179,7 @@ class TestAnthropicExplicitApiKey:
even when an explicit key was supplied (e.g. from a fallback_model entry).
"""
- def test_try_anthropic_uses_explicit_api_key_over_env(self):
- """_try_anthropic(explicit_api_key) must use the supplied key, not the env fallback."""
- with patch("agent.anthropic_credentials.resolve_anthropic_token", return_value="env-fallback-key"), \
- patch("agent.anthropic_adapter.build_anthropic_client") as mock_build, \
- patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)):
- mock_build.return_value = MagicMock()
- from agent.auxiliary_client import _try_anthropic
- client, model = _try_anthropic("explicit-pool-key")
- assert client is not None
- assert mock_build.call_args.args[0] == "explicit-pool-key", (
- f"Expected explicit_api_key to be passed, got: {mock_build.call_args.args[0]}"
- )
- assert mock_build.call_args.args[0] != "env-fallback-key"
- def test_try_anthropic_without_explicit_key_falls_back_to_resolve(self):
- """Without explicit_api_key, _try_anthropic falls back to resolve_anthropic_token."""
- with patch("agent.anthropic_credentials.resolve_anthropic_token", return_value="env-fallback-key"), \
- patch("agent.anthropic_adapter.build_anthropic_client") as mock_build, \
- patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)):
- mock_build.return_value = MagicMock()
- from agent.auxiliary_client import _try_anthropic
- client, model = _try_anthropic()
- assert client is not None
- assert mock_build.call_args.args[0] == "env-fallback-key"
def test_resolve_provider_client_passes_explicit_api_key_to_anthropic(self):
"""resolve_provider_client(provider='anthropic', explicit_api_key=...) must propagate the key."""
@@ -4722,7 +4389,6 @@ class TestAuxUnhealthyCache:
assert _is_provider_unhealthy("custom", local_url) is False
-
# ── auxiliary_max_tokens_param ──────────────────────────────────────────────
@@ -4786,11 +4452,6 @@ class TestCompressionFallbackContextFilter:
"api_key": api_key,
}
- def _mock_resolve(self, entry):
- """Mock _resolve_fallback_entry to return a (client, model) per entry."""
- client = MagicMock()
- client.base_url = entry.get("base_url", "")
- return client, entry["model"]
# ── L2: configured fallback chain ─────────────────────────────────
@@ -5120,7 +4781,7 @@ class TestNoProgressTimeoutTaskConfigGating:
{"auxiliary": {"compression": {"timeout": 600, "no_progress_timeout": -3}}}))
with caplog.at_level(logging.WARNING, logger="agent.auxiliary_client"):
assert _run("compression") == 60.0
- assert any("no_progress_timeout=-3" in r.getMessage() for r in caplog.records)
+ assert any(r.levelno == logging.WARNING for r in caplog.records)
class TestMoaAggregatorStreamingBypass:
@@ -5256,7 +4917,6 @@ class TestSynchronousFallbackCachePlans:
)
-
class TestAsynchronousFallbackCachePlans:
@pytest.mark.asyncio
async def test_async_fallback_replans_cache_sections_like_sync(self, monkeypatch):
diff --git a/tests/agent/test_auxiliary_client_base_url_host_validation.py b/tests/agent/test_auxiliary_client_base_url_host_validation.py
index a55d01a07da..23724787151 100644
--- a/tests/agent/test_auxiliary_client_base_url_host_validation.py
+++ b/tests/agent/test_auxiliary_client_base_url_host_validation.py
@@ -56,104 +56,9 @@ class TestTryAnthropicBaseUrlHostValidation:
f"not the operator's main-session override. Got: {actual!r}"
)
- def test_anthropic_default_host_is_preserved(self, tmp_path, monkeypatch):
- """The common case (operator sets model.base_url to api.anthropic.com) must still apply."""
- import yaml
- from agent.auxiliary_client import _try_anthropic
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / "config.yaml").write_text(yaml.safe_dump({
- "model": {
- "provider": "anthropic",
- "model": "claude-haiku-4-5-20251001",
- "base_url": "https://api.anthropic.com",
- }
- }))
-
- with (
- patch(
- "agent.auxiliary_client._select_pool_entry", return_value=(False, None)
- ),
- patch(
- "agent.anthropic_credentials.resolve_anthropic_token",
- return_value="***",
- ),
- patch(
- "agent.anthropic_adapter.build_anthropic_client"
- ) as mock_build,
- ):
- mock_build.return_value = MagicMock()
- client, _model = _try_anthropic()
- assert client is not None
- actual = _extract_base_url_passed_to_build(mock_build)
- assert actual == "https://api.anthropic.com"
- def test_openai_base_url_does_not_leak(self, tmp_path, monkeypatch):
- """Generic non-Anthropic host must not be applied as auxiliary base_url."""
- import yaml
- from agent.auxiliary_client import _try_anthropic
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / "config.yaml").write_text(yaml.safe_dump({
- "model": {
- "provider": "anthropic",
- "model": "claude-haiku-4-5-20251001",
- "base_url": "https://api.openai.com/v1",
- }
- }))
- with (
- patch(
- "agent.auxiliary_client._select_pool_entry", return_value=(False, None)
- ),
- patch(
- "agent.anthropic_credentials.resolve_anthropic_token",
- return_value="***",
- ),
- patch(
- "agent.anthropic_adapter.build_anthropic_client"
- ) as mock_build,
- ):
- mock_build.return_value = MagicMock()
- client, _model = _try_anthropic()
-
- assert client is not None
- actual = _extract_base_url_passed_to_build(mock_build)
- assert actual == "https://api.anthropic.com", (
- f"Non-Anthropic host must not be applied. Got: {actual!r}"
- )
-
-
- def test_empty_base_url_falls_back_to_default(self, tmp_path, monkeypatch):
- """Empty model.base_url must not crash and must fall back to default."""
- import yaml
- from agent.auxiliary_client import _try_anthropic
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / "config.yaml").write_text(yaml.safe_dump({
- "model": {
- "provider": "anthropic",
- "model": "claude-haiku-4-5-20251001",
- "base_url": "",
- }
- }))
-
- with (
- patch(
- "agent.auxiliary_client._select_pool_entry", return_value=(False, None)
- ),
- patch(
- "agent.anthropic_credentials.resolve_anthropic_token",
- return_value="***",
- ),
- patch(
- "agent.anthropic_adapter.build_anthropic_client"
- ) as mock_build,
- ):
- mock_build.return_value = MagicMock()
- client, _model = _try_anthropic()
-
- assert client is not None
- actual = _extract_base_url_passed_to_build(mock_build)
- assert actual == "https://api.anthropic.com"
def test_anthropic_suffix_gateway_base_url_is_applied(self, tmp_path, monkeypatch):
"""A gateway exposing the Messages protocol under a ``/anthropic`` suffix
diff --git a/tests/agent/test_auxiliary_client_cache_follows_credential.py b/tests/agent/test_auxiliary_client_cache_follows_credential.py
index f2c5ecd2668..c85f9ba1492 100644
--- a/tests/agent/test_auxiliary_client_cache_follows_credential.py
+++ b/tests/agent/test_auxiliary_client_cache_follows_credential.py
@@ -38,12 +38,6 @@ def isolated_home(tmp_path, monkeypatch):
return tmp_path / "hermes"
-def test_isolated_home_hides_ambient_borrowed_credentials(isolated_home):
- """The suite stays hermetic on hosts with an ambient Claude Code login (#114424)."""
- _seed("anthropic", "tok-old", model_cooldown=MODEL)
- pool = aux._load_pool_with_credentials("anthropic")
- assert [entry.source for entry in pool.entries()] == ["manual"]
- assert aux._pool_cache_hint("anthropic").startswith("anthropic::")
@pytest.mark.parametrize("provider", ["anthropic", "openai-codex"])
diff --git a/tests/agent/test_auxiliary_client_resolve_dedup.py b/tests/agent/test_auxiliary_client_resolve_dedup.py
index 1bb7bbd94b9..d3f5ed02d5d 100644
--- a/tests/agent/test_auxiliary_client_resolve_dedup.py
+++ b/tests/agent/test_auxiliary_client_resolve_dedup.py
@@ -41,15 +41,6 @@ class TestUnknownProviderDedup:
# Three calls, one log line — dedup suppressed the repeats.
assert len(recs) == 1
- def test_distinct_unknown_providers_each_log_once(self, caplog):
- with caplog.at_level(logging.DEBUG, logger="agent.auxiliary_client"):
- resolve_provider_client("bogus_a", "")
- resolve_provider_client("bogus_b", "")
- recs = [
- r for r in caplog.records
- if "unknown provider" in r.getMessage()
- ]
- assert len(recs) == 2
class TestUnhandledAuthTypeDedup:
@@ -86,33 +77,3 @@ class TestUnhandledAuthTypeDedup:
assert not any(r.levelno >= logging.WARNING for r in recs)
-class TestUnsupportedOAuthDedup:
- def setup_method(self):
- ac._LOGGED_UNSUPPORTED_OAUTH_KEYS.clear()
-
- def test_unsupported_oauth_provider_logs_debug_once(self, caplog, monkeypatch):
- import hermes_cli.auth as auth
- from hermes_cli.auth import ProviderConfig
-
- # A registered oauth_* provider that is not one of the directly-handled
- # names (nous / openai-codex / xai-oauth) → the OAuth dead-end branch.
- bogus = ProviderConfig(
- id="bogus_oauth",
- name="BogusOAuth",
- auth_type="oauth_device_code",
- )
- patched = dict(auth.PROVIDER_REGISTRY)
- patched["bogus_oauth"] = bogus
- monkeypatch.setattr(auth, "PROVIDER_REGISTRY", patched)
-
- with caplog.at_level(logging.DEBUG, logger="agent.auxiliary_client"):
- resolve_provider_client("bogus_oauth", "")
- resolve_provider_client("bogus_oauth", "")
-
- recs = [
- r for r in caplog.records
- if "OAuth provider" in r.getMessage() and "not " in r.getMessage()
- ]
- assert len(recs) == 1
- assert recs[0].levelno == logging.DEBUG
- assert not any(r.levelno >= logging.WARNING for r in recs)
diff --git a/tests/agent/test_auxiliary_client_xai_oauth_recovery.py b/tests/agent/test_auxiliary_client_xai_oauth_recovery.py
index c08b612ad1a..894cf5783f9 100644
--- a/tests/agent/test_auxiliary_client_xai_oauth_recovery.py
+++ b/tests/agent/test_auxiliary_client_xai_oauth_recovery.py
@@ -114,14 +114,6 @@ class TestRefreshProviderCredentialsXaiOAuth:
def _import(self):
self.refresh = _import_refresh_provider_credentials()
- def test_xai_oauth_no_pool_returns_false(self):
- """When no xai-oauth pool exists, refresh returns False gracefully."""
- # This tests that the branch exists and doesn't crash.
- # It may return True if the singleton resolver finds tokens,
- # or False if neither pool nor singleton has credentials.
- # Either way, it should not raise an exception.
- result = self.refresh("xai-oauth")
- assert isinstance(result, bool)
def test_unknown_provider_returns_false(self):
"""Unknown providers fall through to return False."""
diff --git a/tests/agent/test_auxiliary_concurrency.py b/tests/agent/test_auxiliary_concurrency.py
index 27fccd97ece..fbbe4550c0b 100644
--- a/tests/agent/test_auxiliary_concurrency.py
+++ b/tests/agent/test_auxiliary_concurrency.py
@@ -25,15 +25,7 @@ def _clean_semaphore_cache():
class TestGetTaskMaxConcurrency:
- def test_returns_none_for_missing_task(self):
- assert _get_task_max_concurrency(None) is None
- assert _get_task_max_concurrency("") is None
- def test_returns_none_when_unset(self):
- with patch(
- "agent.auxiliary_client._get_auxiliary_task_config", return_value={}
- ):
- assert _get_task_max_concurrency("title_generation") is None
def test_does_not_reuse_vision_cpu_limit_for_llm_calls(self):
with patch(
@@ -76,35 +68,8 @@ class TestSemaphoreCache:
):
assert _acquire_sync_aux_semaphore("title_generation") is None
- def test_sync_reuses_semaphore_for_same_limit(self):
- with patch(
- "agent.auxiliary_client._get_auxiliary_task_config",
- return_value={"max_concurrency": 2},
- ):
- sem1 = _acquire_sync_aux_semaphore("compression")
- sem2 = _acquire_sync_aux_semaphore("compression")
- assert sem1 is sem2
- def test_sync_rebuilds_when_limit_changes(self):
- cfg = {"max_concurrency": 2}
- with patch(
- "agent.auxiliary_client._get_auxiliary_task_config",
- return_value=cfg,
- ):
- sem1 = _acquire_sync_aux_semaphore("compression")
- cfg["max_concurrency"] = 5
- sem2 = _acquire_sync_aux_semaphore("compression")
- assert sem1 is not sem2
- @pytest.mark.asyncio
- async def test_async_reuses_semaphore_within_same_loop(self):
- with patch(
- "agent.auxiliary_client._get_auxiliary_task_config",
- return_value={"max_concurrency": 2},
- ):
- sem1 = _acquire_async_aux_semaphore("compression")
- sem2 = _acquire_async_aux_semaphore("compression")
- assert sem1 is sem2
def test_async_returns_none_with_no_running_loop(self):
with patch(
@@ -176,36 +141,6 @@ class TestSyncCallEnforcesLimit:
assert max_active <= limit, f"observed {max_active} > limit {limit}"
assert client.chat.completions.create.call_count == n_callers
- def test_call_llm_unlimited_when_not_configured(self):
- client = MagicMock()
- client.base_url = "https://example.test/v1"
- client.chat.completions.create.return_value = MagicMock()
-
- with (
- patch(
- "agent.auxiliary_client._resolve_task_provider_model",
- return_value=("openrouter", "test-model", None, None, None),
- ),
- patch(
- "agent.auxiliary_client._get_cached_client",
- return_value=(client, "test-model"),
- ),
- patch(
- "agent.auxiliary_client._validate_llm_response",
- side_effect=lambda resp, _task, **_kwargs: resp,
- ),
- patch(
- "agent.auxiliary_client._get_auxiliary_task_config",
- return_value={},
- ),
- ):
- # With no max_concurrency in config, no semaphore is acquired.
- call_llm(
- task="title_generation",
- messages=[{"role": "user", "content": "hi"}],
- )
-
- assert client.chat.completions.create.call_count == 1
def test_semaphore_released_on_exception(self):
"""Errors inside call_llm must release the semaphore so the next call proceeds."""
@@ -290,32 +225,6 @@ class TestSyncCallEnforcesLimit:
"include_usage": True
}
- def test_api_mode_is_forwarded_to_client_resolution(self):
- client = MagicMock()
- client.base_url = "https://example.test/v1"
- client.chat.completions.create.return_value = MagicMock()
-
- with (
- patch(
- "agent.auxiliary_client._resolve_task_provider_model",
- return_value=("openrouter", "test-model", None, None, None),
- ),
- patch(
- "agent.auxiliary_client._get_cached_client",
- return_value=(client, "test-model"),
- ) as get_client,
- patch(
- "agent.auxiliary_client._validate_llm_response",
- side_effect=lambda response, _task, **_kwargs: response,
- ),
- ):
- call_llm(
- task="title_generation",
- messages=[{"role": "user", "content": "hi"}],
- api_mode="codex_responses",
- )
-
- assert get_client.call_args.kwargs["api_mode"] == "codex_responses"
class TestAsyncCallEnforcesLimit:
diff --git a/tests/agent/test_auxiliary_config_bridge.py b/tests/agent/test_auxiliary_config_bridge.py
deleted file mode 100644
index 75dd9d6e6bf..00000000000
--- a/tests/agent/test_auxiliary_config_bridge.py
+++ /dev/null
@@ -1,252 +0,0 @@
-"""Tests for auxiliary model config bridging — verifies that config.yaml values
-are properly mapped to environment variables by both CLI and gateway loaders.
-
-Also tests the vision_tools and browser_tool model override env vars.
-"""
-
-import os
-import sys
-from pathlib import Path
-from unittest.mock import patch, MagicMock, AsyncMock
-
-import pytest
-
-
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
-
-
-def _run_auxiliary_bridge(config_dict, monkeypatch):
- """Simulate the auxiliary config → env var bridging logic shared by CLI and gateway.
-
- This mirrors the code in cli.py load_cli_config() and gateway/run.py.
- Both use the same pattern; we test it once here.
- """
- # Clear env vars
- for key in (
- "AUXILIARY_VISION_PROVIDER", "AUXILIARY_VISION_MODEL",
- "AUXILIARY_VISION_BASE_URL", "AUXILIARY_VISION_API_KEY",
- "AUXILIARY_APPROVAL_PROVIDER", "AUXILIARY_APPROVAL_MODEL",
- "AUXILIARY_APPROVAL_BASE_URL", "AUXILIARY_APPROVAL_API_KEY",
- ):
- monkeypatch.delenv(key, raising=False)
-
- # Compression config is read directly from config.yaml — no env var bridging.
-
- # Auxiliary bridge
- auxiliary_cfg = config_dict.get("auxiliary", {})
- if auxiliary_cfg and isinstance(auxiliary_cfg, dict):
- aux_task_env = {
- "vision": {
- "provider": "AUXILIARY_VISION_PROVIDER",
- "model": "AUXILIARY_VISION_MODEL",
- "base_url": "AUXILIARY_VISION_BASE_URL",
- "api_key": "AUXILIARY_VISION_API_KEY",
- },
- "approval": {
- "provider": "AUXILIARY_APPROVAL_PROVIDER",
- "model": "AUXILIARY_APPROVAL_MODEL",
- "base_url": "AUXILIARY_APPROVAL_BASE_URL",
- "api_key": "AUXILIARY_APPROVAL_API_KEY",
- },
- }
- for task_key, env_map in aux_task_env.items():
- task_cfg = auxiliary_cfg.get(task_key, {})
- if not isinstance(task_cfg, dict):
- continue
- prov = str(task_cfg.get("provider", "")).strip()
- model = str(task_cfg.get("model", "")).strip()
- base_url = str(task_cfg.get("base_url", "")).strip()
- api_key = str(task_cfg.get("api_key", "")).strip()
- if prov and prov != "auto":
- os.environ[env_map["provider"]] = prov
- if model:
- os.environ[env_map["model"]] = model
- if base_url:
- os.environ[env_map["base_url"]] = base_url
- if api_key:
- os.environ[env_map["api_key"]] = api_key
-
-
-# ── Config bridging tests ────────────────────────────────────────────────────
-
-
-class TestAuxiliaryConfigBridge:
- """Verify the config.yaml → env var bridging logic used by CLI and gateway."""
-
-
- def test_vision_model_bridged(self, monkeypatch):
- config = {
- "auxiliary": {
- "vision": {"provider": "auto", "model": "openai/gpt-4o"},
- }
- }
- _run_auxiliary_bridge(config, monkeypatch)
- assert os.environ.get("AUXILIARY_VISION_MODEL") == "openai/gpt-4o"
- # auto provider should not be set
- assert os.environ.get("AUXILIARY_VISION_PROVIDER") is None
-
- def test_approval_bridged(self, monkeypatch):
- config = {
- "auxiliary": {
- "approval": {"provider": "nous", "model": "gemini-2.5-flash"},
- }
- }
- _run_auxiliary_bridge(config, monkeypatch)
- assert os.environ.get("AUXILIARY_APPROVAL_PROVIDER") == "nous"
- assert os.environ.get("AUXILIARY_APPROVAL_MODEL") == "gemini-2.5-flash"
-
-
-
-
-
- def test_mixed_tasks(self, monkeypatch):
- config = {
- "auxiliary": {
- "vision": {"provider": "openrouter", "model": ""},
- "approval": {"provider": "auto", "model": "custom-llm"},
- }
- }
- _run_auxiliary_bridge(config, monkeypatch)
- assert os.environ.get("AUXILIARY_VISION_PROVIDER") == "openrouter"
- assert os.environ.get("AUXILIARY_VISION_MODEL") is None
- assert os.environ.get("AUXILIARY_APPROVAL_PROVIDER") is None
- assert os.environ.get("AUXILIARY_APPROVAL_MODEL") == "custom-llm"
-
-
-
-
-
-# ── Gateway bridge parity test ───────────────────────────────────────────────
-
-
-class TestGatewayBridgeCodeParity:
- """Verify the gateway/run.py config bridge contains the auxiliary section."""
-
- def test_gateway_has_auxiliary_bridge(self):
- """The gateway config bridge must include auxiliary.* bridging.
-
- After the plugin-aux-task API refactor (2026-05), gateway env-var
- names are derived dynamically (``AUXILIARY_<KEY_UPPER>_*``) so the
- literal strings ``AUXILIARY_VISION_PROVIDER`` etc. no longer appear
- in source. Assert the dynamic shape and the canonical built-in keys
- bridged set instead.
- """
- gateway_path = Path(__file__).parent.parent.parent / "gateway" / "run.py"
- # Pin encoding to UTF-8: source files in this repo are UTF-8, but
- # Path.read_text() defaults to the system locale — which is cp1252
- # on most Western Windows installs and crashes as soon as the file
- # contains any non-ASCII byte (e.g. an em-dash in a comment).
- content = gateway_path.read_text(encoding="utf-8")
- # Dynamic env-var derivation present
- assert 'f"AUXILIARY_{_upper}_PROVIDER"' in content
- # MODEL / BASE_URL / API_KEY are bridged through one generalized
- # field->suffix loop; assert the loop table and the dynamic key shape.
- assert 'f"AUXILIARY_{_upper}_{_suffix}"' in content
- for field, suffix in (("model", "MODEL"), ("base_url", "BASE_URL"), ("api_key", "API_KEY")):
- assert f'("{field}", "{suffix}")' in content
- # Built-in bridged keys present
- assert "_aux_bridged_keys" in content
- assert '"vision"' in content
- assert '"approval"' in content
- # web_extract no longer uses an auxiliary LLM (truncate-and-store) —
- # it must NOT be in the bridged set.
- assert '_aux_bridged_keys = {"vision", "approval"}' in content
- # Plugin-aux-task discovery hooked into bridging
- assert "get_plugin_auxiliary_tasks" in content
-
- def test_gateway_no_compression_env_bridge(self):
- """Gateway should NOT bridge compression config to env vars (config-only)."""
- gateway_path = Path(__file__).parent.parent.parent / "gateway" / "run.py"
- # See note in test_gateway_has_auxiliary_bridge — pin UTF-8 so the
- # test runs on Windows where the default locale is cp1252.
- content = gateway_path.read_text(encoding="utf-8")
- assert "CONTEXT_COMPRESSION_PROVIDER" not in content
- assert "CONTEXT_COMPRESSION_MODEL" not in content
-
-
-# ── Vision model override tests ──────────────────────────────────────────────
-
-
-class TestVisionModelOverride:
- """Test that AUXILIARY_VISION_MODEL env var overrides the default model in the handler."""
-
- @pytest.mark.asyncio
- async def test_env_var_overrides_default(self, monkeypatch):
- monkeypatch.setenv("AUXILIARY_VISION_MODEL", "openai/gpt-4o")
- from tools.vision_tools import _handle_vision_analyze
- with (
- patch("tools.vision_tools.vision_analyze_tool", new_callable=AsyncMock) as mock_tool,
- patch("tools.vision_tools._should_use_native_vision_fast_path", return_value=False),
- ):
- mock_tool.return_value = '{"success": true}'
- await _handle_vision_analyze({"image_url": "http://test.jpg", "question": "test"})
- call_args = mock_tool.call_args
- # 3rd positional arg = model
- assert call_args[0][2] == "openai/gpt-4o"
-
- @pytest.mark.asyncio
- async def test_default_model_when_no_override(self, monkeypatch):
- monkeypatch.delenv("AUXILIARY_VISION_MODEL", raising=False)
- from tools.vision_tools import _handle_vision_analyze
- with (
- patch("tools.vision_tools.vision_analyze_tool", new_callable=AsyncMock) as mock_tool,
- patch("tools.vision_tools._should_use_native_vision_fast_path", return_value=False),
- ):
- mock_tool.return_value = '{"success": true}'
- await _handle_vision_analyze({"image_url": "http://test.jpg", "question": "test"})
- call_args = mock_tool.call_args
- # With no AUXILIARY_VISION_MODEL env var, model should be None
- # (the centralized call_llm router picks the provider default)
- assert call_args[0][2] is None
-
-
-# ── DEFAULT_CONFIG shape tests ───────────────────────────────────────────────
-
-
-class TestDefaultConfigShape:
- """Verify the DEFAULT_CONFIG in hermes_cli/config.py has correct auxiliary structure."""
-
- def test_auxiliary_section_exists(self):
- from hermes_cli.config import DEFAULT_CONFIG
- assert "auxiliary" in DEFAULT_CONFIG
-
- def test_vision_task_structure(self):
- from hermes_cli.config import DEFAULT_CONFIG
- vision = DEFAULT_CONFIG["auxiliary"]["vision"]
- assert "provider" in vision
- assert "model" in vision
- assert vision["provider"] == "auto"
- assert vision["model"] == ""
-
- def test_web_extract_task_removed(self):
- """web_extract no longer summarizes via LLM — no aux slot."""
- from hermes_cli.config import DEFAULT_CONFIG
- assert "web_extract" not in DEFAULT_CONFIG["auxiliary"]
-
-
-# ── CLI defaults parity ─────────────────────────────────────────────────────
-
-
-class TestCLIDefaultsHaveAuxiliaryKeys:
- """Verify cli.py load_cli_config() defaults dict does NOT include auxiliary
- (it comes from config.yaml deep merge, not hardcoded defaults)."""
-
- def test_cli_defaults_can_merge_auxiliary(self):
- """The load_cli_config deep merge logic handles keys not in defaults.
- Verify auxiliary would be picked up from config.yaml."""
- # This is a structural assertion: cli.py's second-pass loop
- # carries over keys from file_config that aren't in defaults.
- # So auxiliary config from config.yaml gets merged even though
- # cli.py's defaults dict doesn't define it.
- import inspect
-
- import cli as _cli_mod
- # load_cli_config lives in hermes_cli/cli_config_load.py (re-exported by
- # ``cli``); follow the function to its source file rather than pinning
- # cli.py. See note in test_gateway_has_auxiliary_bridge — pin UTF-8 so
- # the test runs on Windows where the default locale is cp1252.
- source = Path(inspect.getsourcefile(_cli_mod.load_cli_config)).read_text(encoding="utf-8")
- assert "auxiliary_config = defaults.get(\"auxiliary\"" in source
- assert "_AUXILIARY_TASK_ENV" in source
- assert "AUXILIARY_VISION_PROVIDER" in source
- assert "AUXILIARY_VISION_MODEL" in source
diff --git a/tests/agent/test_auxiliary_main_first.py b/tests/agent/test_auxiliary_main_first.py
index 47923aedffe..b618c224b0d 100644
--- a/tests/agent/test_auxiliary_main_first.py
+++ b/tests/agent/test_auxiliary_main_first.py
@@ -606,15 +606,3 @@ class TestResolveVisionCustomProvider:
# ── Constant cleanup ────────────────────────────────────────────────────────
-def test_aggregator_providers_constant_removed():
- """The dead _AGGREGATOR_PROVIDERS constant should no longer live in the module.
-
- Removed when the main-first policy made the aggregator-skip guard obsolete.
- """
- import agent.auxiliary_client as aux_mod
-
- assert not hasattr(aux_mod, "_AGGREGATOR_PROVIDERS"), (
- "_AGGREGATOR_PROVIDERS was removed when _resolve_auto_route stopped "
- "treating aggregators specially. If you re-added it, the main-first "
- "policy may have regressed."
- )
diff --git a/tests/agent/test_auxiliary_named_custom_providers.py b/tests/agent/test_auxiliary_named_custom_providers.py
index ebb79ac00dd..a38a4579a55 100644
--- a/tests/agent/test_auxiliary_named_custom_providers.py
+++ b/tests/agent/test_auxiliary_named_custom_providers.py
@@ -39,10 +39,6 @@ class TestNormalizeVisionProvider:
- def test_auto_unchanged(self):
- from agent.auxiliary_client import _normalize_vision_provider
- assert _normalize_vision_provider("auto") == "auto"
- assert _normalize_vision_provider(None) == "auto"
class TestResolveProviderClientMainAlias:
@@ -111,16 +107,6 @@ class TestResolveProviderClientNamedCustom:
assert "beans.local" in str(client.base_url)
- def test_named_custom_no_api_key_uses_fallback(self, tmp_path):
- _write_config(tmp_path, {
- "model": {"default": "test"},
- "custom_providers": [
- {"name": "local", "base_url": "http://localhost:8080/v1"},
- ],
- })
- from agent.auxiliary_client import resolve_provider_client
- client, model = resolve_provider_client("local", "test")
- assert client is not None
# no-key-required should be used
def test_providers_dict_uses_durable_pool_when_no_inline_key(self, tmp_path):
@@ -256,23 +242,6 @@ class TestAutoClientCacheModelCompatibility:
ac._client_cache.clear()
-class TestVisionPathApiMode:
- """Vision path should propagate api_mode to _get_cached_client."""
-
- def test_explicit_provider_passes_api_mode(self, tmp_path):
- _write_config(tmp_path, {
- "model": {"default": "test-model"},
- "auxiliary": {"vision": {"api_mode": "chat_completions"}},
- })
- with patch("agent.auxiliary_client._get_cached_client") as mock_gcc:
- mock_gcc.return_value = (MagicMock(), "test-model")
- from agent.auxiliary_client import resolve_vision_provider_client
-
- provider, client, model = resolve_vision_provider_client(provider="deepseek")
-
- mock_gcc.assert_called_once()
- _, kwargs = mock_gcc.call_args
- assert kwargs.get("api_mode") == "chat_completions"
class TestProvidersDictApiModeAnthropicMessages:
@@ -288,25 +257,6 @@ class TestProvidersDictApiModeAnthropicMessages:
``resolve_provider_client``'s named-custom branch never read it.
"""
- def test_providers_dict_propagates_api_mode(self, tmp_path, monkeypatch):
- monkeypatch.setenv("MYRELAY_API_KEY", "sk-test")
- _write_config(tmp_path, {
- "providers": {
- "myrelay": {
- "name": "myrelay",
- "base_url": "https://example-relay.test/anthropic",
- "key_env": "MYRELAY_API_KEY",
- "api_mode": "anthropic_messages",
- "default_model": "claude-opus-4-7",
- },
- },
- })
- from hermes_cli.runtime_provider import _get_named_custom_provider
- entry = _get_named_custom_provider("myrelay")
- assert entry is not None
- assert entry.get("api_mode") == "anthropic_messages"
- assert entry.get("base_url") == "https://example-relay.test/anthropic"
- assert entry.get("api_key") == "sk-test"
diff --git a/tests/agent/test_auxiliary_runtime_cache_key.py b/tests/agent/test_auxiliary_runtime_cache_key.py
index eac63e91838..0f31856a71f 100644
--- a/tests/agent/test_auxiliary_runtime_cache_key.py
+++ b/tests/agent/test_auxiliary_runtime_cache_key.py
@@ -5,11 +5,6 @@
#56889, which isolates callers that pass different explicit ``model=`` values.
"""
-import asyncio
-from concurrent.futures import ThreadPoolExecutor
-from threading import Barrier
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -80,16 +75,6 @@ def test_runtime_context_token_restores_previous_value_after_turn():
-def test_explicit_model_cache_isolation_remains_independent_of_runtime_key():
- """#56889 remains covered: explicit model values isolate non-auto clients."""
- first = aux._client_cache_key(
- "openrouter", async_mode=False, model="anthropic/claude-opus-4.8"
- )
- second = aux._client_cache_key(
- "openrouter", async_mode=False, model="openai/gpt-5.5"
- )
-
- assert first != second
diff --git a/tests/agent/test_auxiliary_title_timeout_bound.py b/tests/agent/test_auxiliary_title_timeout_bound.py
index 85ee84cc38d..163353839ea 100644
--- a/tests/agent/test_auxiliary_title_timeout_bound.py
+++ b/tests/agent/test_auxiliary_title_timeout_bound.py
@@ -53,21 +53,3 @@ def test_title_timeout_hits_the_provider_once_and_names_the_deadline(caplog):
assert not any("connection error on" in m for m in warnings), warnings
-def test_connection_refused_is_still_a_connection_error(caplog):
- """Control: a genuinely unreachable endpoint keeps its own label — the timeout rung must not swallow it."""
- class _ConnErr(Exception):
- pass
- _ConnErr.__name__ = "APIConnectionError"
- primary = MagicMock()
- primary.base_url = "http://127.0.0.1:1/v1"
- primary.chat.completions.create.side_effect = _ConnErr("Connection refused")
- p = _route_patches(primary)
- caplog.set_level(logging.INFO, logger="agent.auxiliary_client")
- with p[0], p[1], p[2], p[3], p[4]:
- try:
- call_llm(task="title_generation", messages=[{"role": "user", "content": "hi"}], timeout=30)
- except _ConnErr:
- pass
- messages = [r.getMessage() for r in caplog.records]
- assert any("connection error on mac-ollama" in m for m in messages), messages
- assert not any("timed out after" in m for m in messages), messages
diff --git a/tests/agent/test_auxiliary_transient_retry.py b/tests/agent/test_auxiliary_transient_retry.py
index b496ed15fdb..fc5f3f18979 100644
--- a/tests/agent/test_auxiliary_transient_retry.py
+++ b/tests/agent/test_auxiliary_transient_retry.py
@@ -1,40 +1,9 @@
-"""Transient-transport retry count + per-model client-cache isolation.
-
-Two related hardening behaviors for auxiliary calls (which include MoA
-reference advisors, a pinned-model path where provider fallback is not a
-meaningful recovery):
-
-1. A transient transport blip (connection reset / timeout / 5xx) is retried
- on the SAME provider several times with backoff before giving up — a single
- upstream blip should not silently lose a pinned auxiliary call (root of the
- run2 double-advisor "Connection error" collapse).
-2. Two auxiliary calls to the same provider/base_url/key but DIFFERENT models
- get DISTINCT client-cache keys, so a concurrent fan-out (e.g. opus + gpt-5.5
- advisors) never shares one client entry.
+"""Per-model client-cache isolation: two concurrent auxiliary calls to the same
+provider/base_url/key but DIFFERENT models (e.g. MoA advisors) never share one cache entry.
"""
from __future__ import annotations
-import os
-import types
-from unittest.mock import patch
-
-import pytest
-
-
-
-
-def test_transient_retry_count_default(monkeypatch):
- from agent import auxiliary_client as ac
-
- # No config value -> default.
- monkeypatch.setattr(ac, "load_config", lambda: {}, raising=False)
- with patch("hermes_cli.config.load_config", return_value={}), \
- patch("hermes_cli.config.cfg_get", return_value=None):
- assert ac._transient_retry_count() == ac._DEFAULT_TRANSIENT_RETRIES
-
-
-
def test_model_participates_in_client_cache_key():
"""Same provider/base_url/key, different model -> different cache key.
diff --git a/tests/agent/test_auxiliary_transport_autodetect.py b/tests/agent/test_auxiliary_transport_autodetect.py
index 46998a43eaa..6b82ed1cb4e 100644
--- a/tests/agent/test_auxiliary_transport_autodetect.py
+++ b/tests/agent/test_auxiliary_transport_autodetect.py
@@ -14,7 +14,6 @@ web_extract all failed on Kimi Coding Plan users.
from __future__ import annotations
-from unittest.mock import MagicMock, patch
import pytest
@@ -74,39 +73,6 @@ def test_endpoint_speaks_anthropic_messages(url, expected, label):
-def test_maybe_wrap_anthropic_sdk_missing_falls_back():
- """ImportError on anthropic SDK returns plain client with warning."""
- from agent.auxiliary_client import _maybe_wrap_anthropic, AnthropicAuxiliaryClient
-
- plain_client = MagicMock(name="plain_openai")
-
- def _raise_import(*args, **kwargs):
- raise ImportError("no anthropic SDK")
-
- with patch(
- "agent.anthropic_adapter.build_anthropic_client",
- side_effect=_raise_import,
- ):
- # The ImportError is caught on the `from ... import` line inside
- # _maybe_wrap_anthropic, which runs before build_anthropic_client is
- # called. To exercise the ImportError path we need to patch the
- # module lookup itself.
- import sys as _sys
- saved = _sys.modules.get("agent.anthropic_adapter")
- _sys.modules["agent.anthropic_adapter"] = None # force ImportError
- try:
- result = _maybe_wrap_anthropic(
- plain_client, "kimi-for-coding", "sk-kimi-test",
- "https://api.kimi.com/coding", api_mode=None,
- )
- finally:
- if saved is not None:
- _sys.modules["agent.anthropic_adapter"] = saved
- else:
- _sys.modules.pop("agent.anthropic_adapter", None)
-
- assert result is plain_client
- assert not isinstance(result, AnthropicAuxiliaryClient)
# ---------------------------------------------------------------------------
diff --git a/tests/agent/test_auxiliary_unavailable_nous_reason.py b/tests/agent/test_auxiliary_unavailable_nous_reason.py
index e305441946e..cf40b2897b8 100644
--- a/tests/agent/test_auxiliary_unavailable_nous_reason.py
+++ b/tests/agent/test_auxiliary_unavailable_nous_reason.py
@@ -43,8 +43,7 @@ def test_nous_credential_failure_is_remembered_and_warned_once(caplog, monkeypat
unavailable.record_nous_credential_failure(exc)
assert detail.startswith("Nous Portal runtime credentials unavailable: ")
- assert "invalid_grant" in detail and "Run `hermes model` to re-authenticate." in detail
- assert "Invalid refresh token. Run" in detail, detail # sentence-terminated before the remediation
+ assert "invalid_grant" in detail and "hermes model" in detail
assert unavailable.nous_credential_failure_detail() == detail
assert sum(detail in rec.getMessage() for rec in caplog.records) == 1
unavailable.clear_nous_credential_failure()
diff --git a/tests/agent/test_auxiliary_user_default_headers.py b/tests/agent/test_auxiliary_user_default_headers.py
index aff5b2ecc44..0229a98539b 100644
--- a/tests/agent/test_auxiliary_user_default_headers.py
+++ b/tests/agent/test_auxiliary_user_default_headers.py
@@ -31,14 +31,6 @@ def _write_config(tmp_path, config_dict):
class TestApplyUserDefaultHeadersHelper:
"""Direct unit tests for the merge helper."""
- def test_user_headers_merged_and_win(self, tmp_path):
- _write_config(tmp_path, {
- "model": {"default": "m", "default_headers": {"User-Agent": "curl/8.7.1", "X-Extra": "1"}},
- })
- from agent.auxiliary_client import _apply_user_default_headers
- merged = _apply_user_default_headers({"User-Agent": "OpenAI/Python 2.24.0"})
- assert merged["User-Agent"] == "curl/8.7.1" # user wins
- assert merged["X-Extra"] == "1"
diff --git a/tests/agent/test_azure_identity_adapter.py b/tests/agent/test_azure_identity_adapter.py
index 4426e8fc90c..6c9ffa2b813 100644
--- a/tests/agent/test_azure_identity_adapter.py
+++ b/tests/agent/test_azure_identity_adapter.py
@@ -20,9 +20,7 @@ real Azure endpoint. Tests must remain hermetic per AGENTS.md.
from __future__ import annotations
import sys
-from collections.abc import Callable
from types import SimpleNamespace
-from typing import cast
import pytest
@@ -42,26 +40,6 @@ def _reset_adapter_cache():
# ---------------------------------------------------------------------------
-class TestEntraScopeConstant:
- """Pin the Microsoft-documented Foundry inference scope.
-
- Microsoft's official samples for both ``*.openai.azure.com`` and
- ``*.services.ai.azure.com`` use ``https://ai.azure.com/.default``.
- The older ``cognitiveservices.azure.com/.default`` is the
- control-plane scope and is rejected for inference by newer
- Azure OpenAI / Foundry resources.
-
- Users with sovereign-cloud or unusual-tenant requirements pass the
- scope explicitly via ``model.entra.scope`` in ``config.yaml``.
-
- Refs:
- * https://learn.microsoft.com/azure/ai-foundry/openai/how-to/managed-identity
- * https://learn.microsoft.com/azure/ai-foundry/foundry-models/how-to/configure-entra-id
- """
-
- def test_default_scope_matches_microsoft_documentation(self):
- from agent.azure_identity_adapter import SCOPE_AI_AZURE_DEFAULT
- assert SCOPE_AI_AZURE_DEFAULT == "https://ai.azure.com/.default"
# ---------------------------------------------------------------------------
@@ -69,30 +47,6 @@ class TestEntraScopeConstant:
# ---------------------------------------------------------------------------
-class TestMaterializeBearerForHttp:
- """The only helper that mints a real bearer JWT — must call the
- callable exactly once and never fall through to display masking."""
-
- def test_callable_is_invoked_and_returns_token(self):
- from agent.azure_identity_adapter import materialize_bearer_for_http
-
- invoked = {"count": 0}
-
- def provider():
- invoked["count"] += 1
- return "fresh-jwt"
-
- assert materialize_bearer_for_http(provider) == "fresh-jwt"
- assert invoked["count"] == 1
-
-
-
- def test_empty_string_raises(self):
- from agent.azure_identity_adapter import materialize_bearer_for_http
- with pytest.raises(ValueError):
- materialize_bearer_for_http("")
- with pytest.raises(ValueError):
- materialize_bearer_for_http(None)
# ---------------------------------------------------------------------------
@@ -192,17 +146,6 @@ class TestBuildBearerHttpClient:
-class TestIsTokenProvider:
- def test_callable_is_token_provider(self):
- from agent.azure_identity_adapter import is_token_provider
- assert is_token_provider(lambda: "x") is True
-
- def test_string_is_not_token_provider(self):
- from agent.azure_identity_adapter import is_token_provider
- assert is_token_provider("static-key") is False
- # ``str`` instances are technically callable in some edge cases
- # — confirm they're never classified as token providers.
- assert is_token_provider("") is False
# ---------------------------------------------------------------------------
@@ -227,12 +170,6 @@ class TestEntraIdentityConfig:
- def test_dataclass_is_frozen(self):
- # Frozen dataclasses are hashable / safe to pass through caches.
- from agent.azure_identity_adapter import EntraIdentityConfig
- cfg = EntraIdentityConfig()
- with pytest.raises((AttributeError, Exception)):
- setattr(cfg, "scope", "mutated")
# ---------------------------------------------------------------------------
@@ -305,19 +242,6 @@ def fake_azure_identity(monkeypatch):
class TestBuildCredential:
- def test_default_kwargs_are_minimal(self, fake_azure_identity):
- """SDK default for ``exclude_interactive_browser_credential`` is
- True; we only pass it when the user opts IN to interactive
- browser auth. Tenant / authority / service principal config
- flow through the standard ``AZURE_*`` env vars (read by
- azure-identity directly), not Hermes config kwargs."""
- from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
- cred = build_credential(EntraIdentityConfig())
- kwargs = fake_azure_identity.last_credential_kwargs
- # Default config should produce empty kwargs — SDK uses its own
- # defaults plus env-var-driven settings.
- assert kwargs == {}
- assert cred is not None
def test_credential_is_cached_per_config(self, fake_azure_identity):
@@ -443,9 +367,7 @@ class TestRequireAzureIdentityMissing:
with pytest.raises(ImportError) as exc_info:
_adapter._require_azure_identity()
- msg = str(exc_info.value)
- assert "azure-identity" in msg
- assert "Foundry" in msg or "foundry" in msg.lower()
+ assert "azure-identity" in str(exc_info.value)
# ---------------------------------------------------------------------------
diff --git a/tests/agent/test_background_review.py b/tests/agent/test_background_review.py
index 7a10ef16e3a..eb05213dec4 100644
--- a/tests/agent/test_background_review.py
+++ b/tests/agent/test_background_review.py
@@ -307,37 +307,6 @@ def test_background_review_skipped_in_delegation_subagent(monkeypatch):
assert forks == [], "no review fork should be spawned inside a subagent"
-def test_background_review_runs_at_top_level(monkeypatch):
- """Sibling guard for the subagent skip: at ``_delegate_depth == 0`` the
- review still fires exactly as before (the cost guard is subagent-only)."""
- forks = []
-
- class FakeReviewAgent:
- def __init__(self, **kwargs):
- forks.append(kwargs)
-
- def run_conversation(self, **kwargs):
- pass
-
- def shutdown_memory_provider(self):
- pass
-
- def close(self):
- pass
-
- monkeypatch.setattr(run_agent_module, "AIAgent", FakeReviewAgent)
- monkeypatch.setattr(run_agent_module.threading, "Thread", ImmediateThread)
-
- agent = _bare_agent()
- agent._delegate_depth = 0 # top-level agent
-
- AIAgent._spawn_background_review(
- agent,
- messages_snapshot=[{"role": "user", "content": "hello"}],
- review_memory=True,
- )
-
- assert len(forks) == 1, "top-level review must still spawn the fork"
def test_background_review_disabled_skips_automatic_spawn(monkeypatch):
@@ -860,11 +829,6 @@ def _skill_patch_review():
]
-def test_memory_notifications_off_returns_nothing():
- actions = summarize_background_review_actions(
- _memory_add_review(), [], notification_mode="off"
- )
- assert actions == []
diff --git a/tests/agent/test_background_review_cache_parity.py b/tests/agent/test_background_review_cache_parity.py
index aca42a175e4..5d5824b2b0e 100644
--- a/tests/agent/test_background_review_cache_parity.py
+++ b/tests/agent/test_background_review_cache_parity.py
@@ -444,7 +444,7 @@ def test_same_model_review_surfaces_ignored_reasoning_effort_once():
agent, {"reasoning_effort": "low"}, max_iterations=5)
assert not routed
assert len(warnings) == 1, f"expected exactly one notice, got {warnings!r}"
- assert "auxiliary.background_review.reasoning_effort='low'" in warnings[0], warnings[0]
+ assert "reasoning_effort" in warnings[0], warnings[0]
# Cache-parity behaviour itself is unchanged: the fork still inherits the parent verbatim.
assert captured["init_kwargs"]["reasoning_config"] == agent.reasoning_config
# Second fork on the same parent: no repeat.
diff --git a/tests/agent/test_background_review_cost_controls.py b/tests/agent/test_background_review_cost_controls.py
index 9fe3fc2f1b2..4cfbcd7de83 100644
--- a/tests/agent/test_background_review_cost_controls.py
+++ b/tests/agent/test_background_review_cost_controls.py
@@ -128,7 +128,6 @@ def test_digest_collapses_old_keeps_tail_verbatim():
out = br._digest_history(msgs, tail=10)
# First message is the synthetic digest (user role → alternation preserved).
assert out[0]["role"] == "user"
- assert out[0]["content"].startswith("[Earlier conversation digest")
# Recent tail preserved verbatim.
assert out[-1] == msgs[-1]
assert len(out) == 11 # 1 digest + 10 tail
@@ -146,27 +145,12 @@ def test_digest_does_not_open_tail_on_a_tool_message():
assert out[1]["role"] != "tool"
-def test_digest_records_tool_names_in_arc():
- old = [
- _msg("user", "do the thing"),
- _msg("assistant", "", tool_calls=[
- {"function": {"name": "skill_view", "arguments": "{}"}},
- {"function": {"name": "patch", "arguments": "{}"}}]),
- ]
- msgs = old + [_msg("user", f"tail{i}") for i in range(30)]
- out = br._digest_history(msgs, tail=10)
- digest = out[0]["content"]
- assert "USER: do the thing" in digest
- assert "tools: skill_view, patch" in digest
# ---------------------------------------------------------------------------
# Cost / configurability controls (issue #87250)
# ---------------------------------------------------------------------------
-def test_enabled_defaults_true():
- with patch("hermes_cli.config.load_config_readonly", return_value={}):
- assert br.load_background_review_settings()[0] is True
def test_enabled_false_disables_automatic_review():
diff --git a/tests/agent/test_background_review_list_shapes.py b/tests/agent/test_background_review_list_shapes.py
index 1589774b53f..a7a44a7a942 100644
--- a/tests/agent/test_background_review_list_shapes.py
+++ b/tests/agent/test_background_review_list_shapes.py
@@ -23,44 +23,14 @@ C. ``summarize_background_review_actions`` no longer raises when
D. ``summarize_background_review_actions`` no longer raises when
``call_details.get(tcid)`` returns a non-dict (e.g. None or a
stray scalar). It coerces to ``{}``.
-E. The caller in ``_run_review_in_thread`` no longer aborts the
- whole review on an unrelated summarize exception; partial valid
- actions are surfaced.
-The tests run without pytest (handoff from a prior pattern): they use
-plain ``assert`` and a small standalone runner. Importing the module
-exercises the new code paths without booting the LLM stack — there
-are no I/O or model dependencies in the unit-of-work being tested.
"""
from __future__ import annotations
-import importlib
-import importlib.util
import json
-import os
-import sys
-import types
-
-REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-def _isolate_hermes_home():
- os.environ.setdefault("HERMES_HOME", "/tmp/hermes-bg-review-test")
-
-
-def _load_module():
- """Lazy import so a missing optional dep doesn't block the suite.
-
- Returns the module or None if import failed.
- """
- if REPO_ROOT not in sys.path:
- sys.path.insert(0, REPO_ROOT)
- try:
- return importlib.import_module("agent.background_review")
- except Exception:
- return None
+from agent import background_review as bg
def _make_skill_tool_message(change, operations=None):
@@ -138,54 +108,13 @@ def _make_memory_tool_message(operations_field):
]
-class TestRunner:
- def __init__(self):
- self.passed = []
- self.failed = []
-
- def run(self, name, fn):
- try:
- fn()
- except Exception as e: # noqa: BLE001 — runner summary uses it
- import traceback
- self.failed.append((name, e, traceback.format_exc()))
- else:
- self.passed.append(name)
-
- def summary(self):
- total = len(self.passed) + len(self.failed)
- print(f"\n{'=' * 70}\nResults: {len(self.passed)}/{total} passed")
- if self.failed:
- print(f"\n--- {len(self.failed)} failure(s) ---")
- for n, _e, tb in self.failed:
- print(f"\n[FAIL] {n}\n{tb}")
- return 0 if not self.failed else 1
-
-
-# ---------------------------------------------------------------------------
-# A. _change as a list (the originally-reported crash class)
-# ---------------------------------------------------------------------------
-
-
-
-
-
-
# ---------------------------------------------------------------------------
# B. operations as a non-list (string / int / None)
# ---------------------------------------------------------------------------
-
-
def test_b_operations_as_none_treated_as_empty():
"""``operations = None`` (missing key, JSON null) is still safe."""
- _isolate_hermes_home()
- bg = _load_module()
- if bg is None:
- print("SKIP module not importable")
- return
-
msgs = _make_memory_tool_message(operations_field=None)
actions = bg.summarize_background_review_actions(
review_messages=msgs,
@@ -209,12 +138,6 @@ def test_c_operations_contains_non_dict_entries():
so this test exercises the verbose branch where iteration over
per-entry fields actually happens.
"""
- _isolate_hermes_home()
- bg = _load_module()
- if bg is None:
- print("SKIP module not importable")
- return
-
msgs = _make_memory_tool_message(
operations_field=[
"raw-string-no-fields",
@@ -246,12 +169,6 @@ def test_d_detail_non_dict_replaced_with_empty():
"""When ``call_details.get(tcid)`` returns None, summarize must coerce
it to ``{}`` rather than calling ``.get(...)`` on ``None``.
"""
- _isolate_hermes_home()
- bg = _load_module()
- if bg is None:
- print("SKIP module not importable")
- return
-
# Build a tool-only message whose tcid does NOT have an assistant tool_call.
msgs = _make_skill_tool_message(change={})
# Drop the assistant message so call_details is empty for tcid=call_1.
@@ -263,47 +180,3 @@ def test_d_detail_non_dict_replaced_with_empty():
notification_mode="verbose",
)
assert isinstance(actions, list)
-
-
-# ---------------------------------------------------------------------------
-# E. Caller defends against summarize raising
-# ---------------------------------------------------------------------------
-
-
-def test_e_call_does_not_unwind_module_callables():
- """Structural: the new defensive try/except around the summarize
- call is in place. Caught here rather than via a partial mocking
- cascade because monkeypatching the AIAgent is too brittle for a
- blind regression test — keeping it text-anchored guards the
- ``_run_review_in_thread`` invariant without a real LLM.
- """
- src_path = os.path.join(REPO_ROOT, "agent", "background_review.py")
- src = open(src_path, encoding="utf-8").read()
- # The fix added: ``try: actions = summarize_background_review_actions(...)``
- # followed by ``except Exception as e: ... actions = []``.
- assert "actions = summarize_background_review_actions(" in src
- assert (
- "summarize_background_review_actions returned partial results"
- in src
- ), "expected partial-results guard message present"
- # And the non-dict guards on free-form tool payload fields.
- assert "if isinstance(ops_raw, list)" in src
- assert "if isinstance(change_raw, dict)" in src
-
-
-# ---------------------------------------------------------------------------
-# Runner
-# ---------------------------------------------------------------------------
-
-
-def main():
- runner = TestRunner()
- runner.run("b_operations_as_none_treated_as_empty", test_b_operations_as_none_treated_as_empty)
- runner.run("c_operations_contains_non_dict_entries", test_c_operations_contains_non_dict_entries)
- runner.run("d_detail_non_dict_replaced_with_empty", test_d_detail_non_dict_replaced_with_empty)
- runner.run("e_call_defends_via_try_except", test_e_call_does_not_unwind_module_callables)
- return runner.summary()
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/tests/agent/test_background_review_summary.py b/tests/agent/test_background_review_summary.py
index 1ba00358817..5a6e5ca09e5 100644
--- a/tests/agent/test_background_review_summary.py
+++ b/tests/agent/test_background_review_summary.py
@@ -94,19 +94,3 @@ def test_empty_inputs():
-def test_removed_or_replaced_relabels_by_target():
- review_messages = [
- _tool_msg(
- "c1",
- {"success": True, "message": "Entry removed.", "target": "user"},
- ),
- _tool_msg(
- "c2",
- {"success": True, "message": "Entry replaced.", "target": "memory"},
- ),
- ]
-
- actions = _summarize(review_messages, [])
-
- assert "User profile updated" in actions
- assert "Memory updated" in actions
diff --git a/tests/agent/test_background_review_tool_call_guard.py b/tests/agent/test_background_review_tool_call_guard.py
index 870b2d06315..847d6cd3a5d 100644
--- a/tests/agent/test_background_review_tool_call_guard.py
+++ b/tests/agent/test_background_review_tool_call_guard.py
@@ -91,14 +91,6 @@ def test_ordinary_providers_are_unaffected():
assert _run(_fake_parent(_PlainClient())).called
-def test_the_capability_is_read_off_the_class_too():
- """Clients declare it as a class attribute; an instance need not set it."""
-
- class _IncapableClient:
- SUPPORTS_HERMES_TOOL_CALLS = False
-
- assert bg._parent_can_emit_tool_calls(_fake_parent(_IncapableClient())) is False
- assert bg._parent_can_emit_tool_calls(_fake_parent(None)) is True
def test_an_incapable_provider_still_reviews_when_the_review_is_routed_away():
diff --git a/tests/agent/test_background_review_usage.py b/tests/agent/test_background_review_usage.py
index 28253140538..852174a7e7c 100644
--- a/tests/agent/test_background_review_usage.py
+++ b/tests/agent/test_background_review_usage.py
@@ -161,38 +161,7 @@ def test_enabled_config_failure_logs_warning(caplog):
side_effect=RuntimeError("boom"),
), caplog.at_level(logging.WARNING, logger="agent.background_review"):
assert background_review.load_background_review_settings()[0] is True
- assert any(
- "fail-open" in r.message.lower() or "leaving automatic" in r.message.lower()
- for r in caplog.records
- )
+ assert any(r.levelno >= logging.WARNING for r in caplog.records)
+
-def test_spawn_reuses_provided_task_cfg_without_rereading():
- """One config load per spawn — the worker shares task_cfg."""
- task = {"enabled": True}
- agent = type("A", (), {})()
- with patch(
- "hermes_cli.config.load_config_readonly",
- side_effect=AssertionError("config must not be re-read when task_cfg is passed"),
- ):
- _target, prompt = background_review.spawn_background_review_thread(
- agent,
- messages_snapshot=[{"role": "user", "content": "hi"}],
- review_skills=True,
- task_cfg=task,
- )
- assert prompt # built-in skill-review prompt selected
- assert callable(_target)
-
-def test_log_review_completion_emits_thread_tag(caplog):
- with caplog.at_level(logging.INFO, logger="agent.background_review"):
- background_review._log_review_completion(
- _usage(api_calls=8, input_tokens=53000, output_tokens=400),
- "skill",
- )
- assert any(
- "thread=bg-review" in r.message
- and "calls=8" in r.message
- and "result=skill" in r.message
- for r in caplog.records
- )
diff --git a/tests/agent/test_battery.py b/tests/agent/test_battery.py
index 931344cfd0b..c834101c97d 100644
--- a/tests/agent/test_battery.py
+++ b/tests/agent/test_battery.py
@@ -11,8 +11,6 @@ from agent import battery as battery_mod
from agent.battery import (
BatteryStatus,
battery_category,
- battery_glyph,
- format_battery,
read_battery,
)
@@ -77,12 +75,3 @@ def test_battery_category_thresholds(percent, plugged, expected):
-def test_format_and_glyph():
- on_battery = BatteryStatus(available=True, percent=82, plugged=False)
- charging = BatteryStatus(available=True, percent=82, plugged=True)
-
- assert battery_glyph(on_battery) == "\U0001f50b" # 🔋
- assert battery_glyph(charging) == "\u26a1" # ⚡
- assert format_battery(on_battery) == "\U0001f50b 82%"
- assert format_battery(charging) == "\u26a1 82%"
- assert format_battery(BatteryStatus(available=False)) == ""
diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.py
index ebc0416beee..a10c3b345f0 100644
--- a/tests/agent/test_bedrock_adapter.py
+++ b/tests/agent/test_bedrock_adapter.py
@@ -298,12 +298,6 @@ class TestConvertMessagesToConverse:
assert tr["toolResult"]["content"][0]["text"] == "file contents here"
- def test_empty_content_gets_placeholder(self):
- from agent.bedrock_adapter import convert_messages_to_converse
- messages = [{"role": "user", "content": ""}]
- system, msgs = convert_messages_to_converse(messages)
- # Empty string should get a space placeholder
- assert msgs[0]["content"][0]["text"].strip() != "" or msgs[0]["content"][0]["text"] == " "
# ---------------------------------------------------------------------------
@@ -618,14 +612,6 @@ class TestBuildConverseKwargs:
assert "toolConfig" in kwargs
assert len(kwargs["toolConfig"]["tools"]) == 1
- def test_default_max_tokens_stays_4096(self):
- """Callers that don't pass max_tokens keep the historical 4096 cap —
- the None-omission behavior is strictly opt-in."""
- from agent.bedrock_adapter import build_converse_kwargs
- kwargs = build_converse_kwargs(
- model="test-model", messages=[{"role": "user", "content": "Hi"}],
- )
- assert kwargs["inferenceConfig"]["maxTokens"] == 4096
def test_max_tokens_none_omits_cap(self):
"""max_tokens=None omits inferenceConfig.maxTokens so Bedrock uses the
@@ -977,18 +963,6 @@ class TestExtractProviderFromArn:
# Client cache management
# ---------------------------------------------------------------------------
-class TestClientCache:
- def test_reset_clears_caches(self):
- from agent.bedrock_adapter import (
- _bedrock_runtime_client_cache,
- _bedrock_control_client_cache,
- reset_client_cache,
- )
- _bedrock_runtime_client_cache["test"] = "dummy"
- _bedrock_control_client_cache["test"] = "dummy"
- reset_client_cache()
- assert len(_bedrock_runtime_client_cache) == 0
- assert len(_bedrock_control_client_cache) == 0
# ---------------------------------------------------------------------------
@@ -1074,14 +1048,6 @@ class TestGuardrailConfig:
)
assert kwargs["guardrailConfig"] == guardrail
- def test_no_guardrail_when_none(self):
- from agent.bedrock_adapter import build_converse_kwargs
- kwargs = build_converse_kwargs(
- model="test-model",
- messages=[{"role": "user", "content": "Hi"}],
- guardrail_config=None,
- )
- assert "guardrailConfig" not in kwargs
def test_no_guardrail_when_empty_dict(self):
from agent.bedrock_adapter import build_converse_kwargs
@@ -1201,31 +1167,11 @@ class TestBedrockContextProbe:
# Tool-calling capability detection
# ---------------------------------------------------------------------------
-class TestModelSupportsToolUse:
- """Test non-tool-calling model detection."""
-
- def test_claude_supports_tools(self):
- from agent.bedrock_adapter import _model_supports_tool_use
- assert _model_supports_tool_use("us.anthropic.claude-sonnet-4-6") is True
-
-
- def test_deepseek_r1_no_tools(self):
- from agent.bedrock_adapter import _model_supports_tool_use
- assert _model_supports_tool_use("us.deepseek.r1-v1:0") is False
class TestBuildConverseKwargsToolStripping:
"""Test that tools are stripped for non-tool-calling models."""
- def test_tools_included_for_claude(self):
- from agent.bedrock_adapter import build_converse_kwargs
- tools = [{"type": "function", "function": {"name": "test", "description": "t", "parameters": {}}}]
- kwargs = build_converse_kwargs(
- model="us.anthropic.claude-sonnet-4-6",
- messages=[{"role": "user", "content": "Hi"}],
- tools=tools,
- )
- assert "toolConfig" in kwargs
def test_tools_stripped_for_deepseek_r1(self):
from agent.bedrock_adapter import build_converse_kwargs
@@ -1273,10 +1219,6 @@ class TestEmptyTextBlockFix:
assert blocks[0]["text"].strip()
- def test_real_text_preserved(self):
- from agent.bedrock_adapter import _convert_content_to_converse
- blocks = _convert_content_to_converse("Hello")
- assert blocks[0]["text"] == "Hello"
# ---------------------------------------------------------------------------
@@ -1495,15 +1437,6 @@ class TestRequireBoto3VersionCheck:
with pytest.raises(RuntimeError, match="does not support converse_stream"):
_require_boto3()
- def test_accepts_boto3_at_minimum_version(self):
- """boto3 == 1.34.59 should be accepted."""
- from agent.bedrock_adapter import _require_boto3
-
- fake_boto3 = MagicMock()
- fake_boto3.__version__ = "1.34.59"
- with patch.dict("sys.modules", {"boto3": fake_boto3}):
- result = _require_boto3()
- assert result is fake_boto3
class TestImageBase64Decoding:
diff --git a/tests/agent/test_bedrock_context_cache.py b/tests/agent/test_bedrock_context_cache.py
index 5321f482bd5..5d42a43f4a7 100644
--- a/tests/agent/test_bedrock_context_cache.py
+++ b/tests/agent/test_bedrock_context_cache.py
@@ -30,7 +30,7 @@ def isolated_home(tmp_path, monkeypatch):
mm._BEDROCK_PROBE_FAILURE_CACHE.clear()
[email protected]("model", ["xai.grok-4.6", "global.xai.grok-4.6", "us.xai.grok-4.6"])
[email protected]("model", ["global.xai.grok-4.6"]) # prefix variants resolve identically
@pytest.mark.parametrize("base_url", ["", "https://bedrock-runtime.us-east-1.amazonaws.com"])
@pytest.mark.parametrize("legacy", [None, 128_000, 700_000])
@pytest.mark.parametrize("probed", [None, 128_000, 800_000])
diff --git a/tests/agent/test_bedrock_integration.py b/tests/agent/test_bedrock_integration.py
index 31c21cf49d6..9a221c1d306 100644
--- a/tests/agent/test_bedrock_integration.py
+++ b/tests/agent/test_bedrock_integration.py
@@ -41,41 +41,16 @@ def _boto_sys_modules_hygiene():
-class TestProviderRegistry:
- """Verify Bedrock is registered in PROVIDER_REGISTRY."""
- def test_bedrock_in_registry(self):
- from hermes_cli.auth import PROVIDER_REGISTRY
- assert "bedrock" in PROVIDER_REGISTRY
- def test_bedrock_has_no_api_key_env_vars(self):
- """Bedrock uses the AWS SDK credential chain, not API keys."""
- from hermes_cli.auth import PROVIDER_REGISTRY
- pconfig = PROVIDER_REGISTRY["bedrock"]
- assert pconfig.api_key_env_vars == ()
-class TestProviderAliases:
- """Verify Bedrock aliases resolve correctly."""
- def test_aws_alias(self):
- from hermes_cli.models import _PROVIDER_ALIASES
- assert _PROVIDER_ALIASES.get("aws") == "bedrock"
-
-
-class TestProviderLabels:
- """Verify Bedrock appears in provider labels."""
-
- def test_bedrock_label(self):
- from hermes_cli.models import _PROVIDER_LABELS
- assert _PROVIDER_LABELS.get("bedrock") == "AWS Bedrock"
-
-
class TestModelCatalog:
"""Verify Bedrock has a static model fallback list."""
@@ -84,17 +59,7 @@ class TestModelCatalog:
models = _PROVIDER_MODELS.get("bedrock", [])
assert len(models) > 0
- def test_bedrock_models_include_claude(self):
- from hermes_cli.models import _PROVIDER_MODELS
- models = _PROVIDER_MODELS.get("bedrock", [])
- claude_models = [m for m in models if "anthropic.claude" in m]
- assert len(claude_models) > 0
- def test_bedrock_models_include_nova(self):
- from hermes_cli.models import _PROVIDER_MODELS
- models = _PROVIDER_MODELS.get("bedrock", [])
- nova_models = [m for m in models if "amazon.nova" in m]
- assert len(nova_models) > 0
class TestResolveProvider:
@@ -192,9 +157,7 @@ class TestRuntimeProvider:
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
monkeypatch.setenv("AWS_REGION", "us-east-2")
- assert "openai.gpt-5.5" in BEDROCK_OPENAI_RESPONSES_MODEL_IDS
- for suffix in ("sol", "terra", "luna"):
- assert f"openai.gpt-5.6-{suffix}" in BEDROCK_OPENAI_RESPONSES_MODEL_IDS
+ assert BEDROCK_OPENAI_RESPONSES_MODEL_IDS
for model_id in BEDROCK_OPENAI_RESPONSES_MODEL_IDS:
with patch("hermes_cli.runtime_provider.resolve_provider", return_value="bedrock"), \
@@ -210,15 +173,16 @@ class TestRuntimeProvider:
assert result["api_key"] == "aws-sdk"
assert result["bedrock_openai"] is True, model_id
- def test_bedrock_openai_context_length_is_272k(self):
- """AWS model cards list a 272K context window for the Mantle OpenAI
- models; make sure we do not fall back to the 128K default."""
+ def test_bedrock_openai_models_do_not_fall_back_to_default_context(self):
+ """The Mantle OpenAI models have a larger window than the generic
+ default; make sure they never fall back to it."""
from agent.bedrock_adapter import (
+ BEDROCK_DEFAULT_CONTEXT_LENGTH,
BEDROCK_OPENAI_RESPONSES_MODEL_IDS,
get_bedrock_context_length,
)
for model_id in BEDROCK_OPENAI_RESPONSES_MODEL_IDS:
- assert get_bedrock_context_length(model_id) == 272_000
+ assert get_bedrock_context_length(model_id) > BEDROCK_DEFAULT_CONTEXT_LENGTH, model_id
# ---------------------------------------------------------------------------
@@ -228,11 +192,6 @@ class TestRuntimeProvider:
class TestProvidersModule:
"""Verify bedrock is wired into hermes_cli/providers.py."""
- def test_bedrock_alias_in_providers(self):
- from hermes_cli.providers import ALIASES
- assert ALIASES.get("bedrock") is None # "bedrock" IS the canonical name, not an alias
- assert ALIASES.get("aws") == "bedrock"
- assert ALIASES.get("aws-bedrock") == "bedrock"
def test_determine_api_mode_from_bedrock_url(self):
@@ -250,13 +209,21 @@ class TestProvidersModule:
class TestErrorClassifierBedrock:
"""Verify Bedrock error patterns are in the global error classifier."""
- def test_throttling_in_rate_limit_patterns(self):
- from agent.error_classifier import _RATE_LIMIT_PATTERNS
- assert "throttlingexception" in _RATE_LIMIT_PATTERNS
+ def test_bedrock_throttling_classified_as_rate_limit(self):
+ from agent.error_classifier import FailoverReason, classify_api_error
+ err = Exception(
+ "An error occurred (ThrottlingException) when calling the ConverseStream "
+ "operation: Too many requests, please wait before trying again."
+ )
+ assert classify_api_error(err, provider="bedrock").reason == FailoverReason.rate_limit
- def test_context_overflow_patterns(self):
- from agent.error_classifier import _CONTEXT_OVERFLOW_PATTERNS
- assert "input is too long" in _CONTEXT_OVERFLOW_PATTERNS
+ def test_bedrock_input_too_long_classified_as_context_overflow(self):
+ from agent.error_classifier import FailoverReason, classify_api_error
+ err = Exception(
+ "An error occurred (ValidationException) when calling the ConverseStream "
+ "operation: Input is too long for requested model."
+ )
+ assert classify_api_error(err, provider="bedrock").reason == FailoverReason.context_overflow
# ---------------------------------------------------------------------------
@@ -340,12 +307,6 @@ class TestBedrockModelNameNormalization:
reproduce the exact production request shape for each Bedrock model
family, confirming the fix resolves the reporter's HTTP 400."""
- def test_global_anthropic_inference_profile_preserved(self):
- """The reporter's exact model ID."""
- from agent.anthropic_message_convert import normalize_model_name
- assert normalize_model_name(
- "global.anthropic.claude-opus-4-7", preserve_dots=True
- ) == "global.anthropic.claude-opus-4-7"
@@ -368,20 +329,6 @@ class TestBedrockBuildAnthropicKwargsEndToEnd:
``bedrock-runtime.`` endpoint. This is the integration-level
regression for the reporter's HTTP 400."""
- def test_bedrock_inference_profile_survives_build_kwargs(self):
- from agent.anthropic_adapter import build_anthropic_kwargs
- kwargs = build_anthropic_kwargs(
- model="global.anthropic.claude-opus-4-7",
- messages=[{"role": "user", "content": "hi"}],
- tools=None,
- max_tokens=1024,
- reasoning_config=None,
- preserve_dots=True,
- )
- assert kwargs["model"] == "global.anthropic.claude-opus-4-7", (
- "Bedrock inference-profile ID was mangled in build_anthropic_kwargs: "
- f"{kwargs['model']!r}"
- )
def test_bedrock_model_preserved_without_preserve_dots(self):
"""Bedrock inference profile IDs survive ``build_anthropic_kwargs``
@@ -405,9 +352,6 @@ class TestBedrockModelIdDetection:
makes ``normalize_model_name`` preserve dots for Bedrock IDs
regardless of ``preserve_dots``. Regression for #12295."""
- def test_bare_bedrock_id_detected(self):
- from agent.anthropic_message_convert import _is_bedrock_model_id
- assert _is_bedrock_model_id("anthropic.claude-opus-4-7") is True
@@ -470,42 +414,11 @@ class TestAuxiliaryClientBedrockResolution:
- def test_bedrock_default_model_is_haiku(self, monkeypatch):
- """Default auxiliary model for Bedrock should be Haiku (fast, cheap)."""
- monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAIOSFODNN7EXAMPLE")
- monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
-
- with patch("agent.anthropic_adapter.build_anthropic_bedrock_client",
- return_value=MagicMock()):
- from agent.auxiliary_client import resolve_provider_client
- _, model = resolve_provider_client("bedrock", None)
-
- assert "haiku" in model.lower()
-
-
- def test_bedrock_converse_shim_stream_returns_complete_response(self, monkeypatch):
- """stream=True is not supported by the shim — a complete response comes
- back and call_llm's streaming consumer downgrades gracefully."""
- monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAIO...MPLE")
- monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
- from agent.auxiliary_client import BedrockAuxiliaryClient
- client = BedrockAuxiliaryClient("us-east-1", "openai.gpt-oss-20b-1:0")
- sentinel = object()
- with patch("agent.bedrock_adapter.call_converse", return_value=sentinel) as mock_converse:
- resp = client.chat.completions.create(
- model="openai.gpt-oss-20b-1:0",
- messages=[{"role": "user", "content": "hi"}],
- stream=True,
- )
- # Non-streaming call_converse is still used; the caller's
- # got-final-object downgrade path handles the rest.
- assert resp is sentinel
- assert mock_converse.call_count == 1
def test_bedrock_shim_uncapped_when_caller_omits_max_tokens(self, monkeypatch):
"""No caller max_tokens → the shim passes None through and the wire
diff --git a/tests/agent/test_billing_links.py b/tests/agent/test_billing_links.py
index 909bf8d2874..3626f722bc9 100644
--- a/tests/agent/test_billing_links.py
+++ b/tests/agent/test_billing_links.py
@@ -7,7 +7,6 @@ few that are the whole point of the mapping (the host they must land on).
from __future__ import annotations
from agent.billing_links import (
- BillingBlock,
build_billing_block,
is_nous_inference_route,
)
@@ -39,15 +38,3 @@ def test_known_provider_by_slug_resolves_label_and_url():
-def test_to_dict_round_trips_all_fields():
- block = build_billing_block(provider="openai", base_url="", model="gpt-5")
- data = block.to_dict()
- assert set(data) == {
- "provider",
- "provider_label",
- "model",
- "billing_url",
- "is_nous",
- "message",
- }
- assert isinstance(block, BillingBlock)
diff --git a/tests/agent/test_billing_unverified_carrythrough.py b/tests/agent/test_billing_unverified_carrythrough.py
index 775b6adca47..e89744ebe73 100644
--- a/tests/agent/test_billing_unverified_carrythrough.py
+++ b/tests/agent/test_billing_unverified_carrythrough.py
@@ -15,7 +15,7 @@ from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock
-from agent.conversation_loop import _billing_failure_result, _billing_terminal_label
+from agent.conversation_loop import _billing_failure_result
from agent.error_classifier import FailoverReason, classify_api_error
@@ -72,8 +72,6 @@ class TestTerminalResponse:
assert not final.startswith("Billing or credits exhausted")
assert "unverified" in final
assert "content-filter" in final or "content filter" in final
- # The guidance must ride along and hedge too.
- assert "still shows quota remaining" in final
def test_unverified_terminal_response_structured_fields(self):
"""The structured result carries the ambiguity, not just the prose."""
@@ -111,12 +109,6 @@ class TestTerminalResponse:
if block is not None:
assert "unverified" not in block
- def test_terminal_label_contract(self):
- assert _billing_terminal_label("boom", False) == "Billing or credits exhausted: boom"
- hedged = _billing_terminal_label("boom", True)
- assert "unverified" in hedged
- assert "content-filter" in hedged
- assert not hedged.startswith("Billing or credits exhausted")
# ── Credential-pool plumbing ─────────────────────────────────────────────────
diff --git a/tests/agent/test_builtin_memory_disabled_surface.py b/tests/agent/test_builtin_memory_disabled_surface.py
index 7d6c00a697f..78d9e262cd4 100644
--- a/tests/agent/test_builtin_memory_disabled_surface.py
+++ b/tests/agent/test_builtin_memory_disabled_surface.py
@@ -13,7 +13,6 @@ These tests exercise the real resolution chain (config on disk → check_fn →
"""
import json
-from unittest.mock import patch
import pytest
import yaml
@@ -75,8 +74,6 @@ class TestBuiltinMemoryToolAvailability:
)
definition = _memory_tool_definition()
assert definition["parameters"]["properties"]["target"]["enum"] == ["user"]
- assert "only 'user' is enabled" in definition["description"]
- assert "only 'memory' is enabled" not in definition["description"]
def test_tool_present_when_only_memory_enabled(self, hermes_home):
_write_memory_config(
@@ -84,8 +81,6 @@ class TestBuiltinMemoryToolAvailability:
)
definition = _memory_tool_definition()
assert definition["parameters"]["properties"]["target"]["enum"] == ["memory"]
- assert "only 'memory' is enabled" in definition["description"]
- assert "only 'user' is enabled" not in definition["description"]
def test_tool_present_by_default(self, hermes_home):
"""No config file at all must not strip a working tool."""
@@ -238,7 +233,7 @@ class TestIndependentStoreWriteGates:
memory_tool(action="add", target="bogus", content="fact", store=store)
)
assert short["success"] is False
- assert "Use 'memory' or 'user'" in short["error"]
+ assert short["error"]
class TestExternalProviderSurvivesBuiltinDisable:
diff --git a/tests/agent/test_cache_disabled_on_stubs.py b/tests/agent/test_cache_disabled_on_stubs.py
index 954b7d4d565..3c09c50f0fc 100644
--- a/tests/agent/test_cache_disabled_on_stubs.py
+++ b/tests/agent/test_cache_disabled_on_stubs.py
@@ -23,25 +23,7 @@ def _has_cache_control(obj) -> bool:
class TestPromptCachingDisabledFromConfig:
- def test_off_values(self):
- from agent.agent_runtime_helpers import prompt_caching_disabled_from_config
- for ttl in (False, None, "off", "false", "disabled", "no", "none", "OFF"):
- with patch(
- "hermes_cli.config.load_config_readonly",
- return_value={"prompt_caching": {"cache_ttl": ttl}},
- ):
- assert prompt_caching_disabled_from_config() is True, ttl
-
- def test_enabled_values(self):
- from agent.agent_runtime_helpers import prompt_caching_disabled_from_config
-
- for ttl in ("5m", "1h"):
- with patch(
- "hermes_cli.config.load_config_readonly",
- return_value={"prompt_caching": {"cache_ttl": ttl}},
- ):
- assert prompt_caching_disabled_from_config() is False, ttl
def test_shared_predicate_matches_agent_init_semantics(self):
"""agent_init and the stub paths must share one disable predicate.
@@ -272,26 +254,6 @@ class TestPreparedAggregatorNoAgentConfigOff:
assert tools == canonical_tools
-class TestBlankCachePolicyStubFactory:
- def test_factory_sets_cache_disabled_from_config(self):
- from agent.agent_runtime_helpers import blank_cache_policy_stub
-
- with patch(
- "hermes_cli.config.load_config_readonly",
- return_value={"prompt_caching": {"cache_ttl": "off"}},
- ):
- stub = blank_cache_policy_stub()
- assert stub._cache_disabled is True
-
- def test_factory_honors_explicit_false(self):
- from agent.agent_runtime_helpers import blank_cache_policy_stub
-
- with patch(
- "hermes_cli.config.load_config_readonly",
- return_value={"prompt_caching": {"cache_ttl": "off"}},
- ):
- stub = blank_cache_policy_stub(False)
- assert stub._cache_disabled is False
class TestOneShotSynthesisAgentDisable:
diff --git a/tests/agent/test_callable_api_key.py b/tests/agent/test_callable_api_key.py
index 8042eb912c1..a7c9aeadfa5 100644
--- a/tests/agent/test_callable_api_key.py
+++ b/tests/agent/test_callable_api_key.py
@@ -25,11 +25,9 @@ Covered:
from __future__ import annotations
-import json
from typing import cast
from unittest.mock import MagicMock
-import pytest
# ---------------------------------------------------------------------------
@@ -161,27 +159,6 @@ class TestTruncateTokenCallable:
# ---------------------------------------------------------------------------
-class TestRuntimeDictSerializationGuard:
- def test_json_dumps_default_str_does_not_silently_stringify_callable(self):
- """Sanity check: a runtime dict with a callable api_key must
- either raise on plain ``json.dumps`` (good — fail loud) or be
- sanitized BEFORE serialization. This test pins the loud-fail
- behaviour so future changes that introduce
- ``json.dumps(..., default=str)`` over a runtime dict are caught
- by a regression here."""
-
- def provider():
- return "jwt"
-
- runtime = {
- "provider": "azure-foundry",
- "api_key": provider,
- "auth_mode": "entra_id",
- }
- # Plain json.dumps — must raise, not silently produce
- # ``"<function provider at 0x...>"``.
- with pytest.raises(TypeError):
- json.dumps(runtime)
# ---------------------------------------------------------------------------
@@ -189,44 +166,6 @@ class TestRuntimeDictSerializationGuard:
# ---------------------------------------------------------------------------
-class TestBatchRunnerCallableHandling:
- def test_callable_api_key_stripped_from_worker_config(self, capsys, monkeypatch, tmp_path):
- """``BatchRunner._run_batches`` (or the equivalent code path)
- must replace a callable api_key with None before pickling the
- worker config dict — otherwise multiprocessing.Pool fails."""
- # We can't easily run BatchRunner end-to-end in a unit test
- # (it spawns subprocesses), but we CAN inline the same logic:
- # the production code uses ``callable(self.api_key) and not
- # isinstance(self.api_key, str)`` to gate the substitution.
- # Re-execute the same predicate here as a contract guard.
-
- def provider():
- return "jwt"
-
- api_key = provider
- worker_api_key = None if (callable(api_key) and not isinstance(api_key, str)) else api_key
- assert worker_api_key is None, (
- "BatchRunner must replace callable api_key with None so "
- "multiprocessing.Pool can pickle the worker config"
- )
-
- # And a string passes through unchanged.
- api_key_str = "sk-static"
- worker_api_key_str = None if (callable(api_key_str) and not isinstance(api_key_str, str)) else api_key_str
- assert worker_api_key_str == "sk-static"
-
- def test_batch_runner_source_uses_the_correct_predicate(self):
- """Pin the predicate string in batch_runner so refactors that
- change it are caught here. Reading the source rather than
- importing avoids spinning up the full BatchRunner."""
- from pathlib import Path
- src = (Path(__file__).resolve().parent.parent.parent
- / "batch_runner.py").read_text()
- assert "callable(self.api_key) and not isinstance(self.api_key, str)" in src, (
- "BatchRunner.api_key callable check changed — update test or "
- "verify the new predicate still routes Entra token providers "
- "to the worker-rebuild path."
- )
# ---------------------------------------------------------------------------
@@ -234,86 +173,7 @@ class TestBatchRunnerCallableHandling:
# ---------------------------------------------------------------------------
-class TestCliEnsureRuntimeCredentialsCallable:
- """Regression: ``cli.py:_ensure_runtime_credentials`` previously
- treated a callable ``api_key`` as "not a string" and overwrote it
- with the ``"no-key-required"`` placeholder, which then got sent as
- ``Authorization: Bearer no-key-required`` and rejected by Azure
- with a 401. This is the most subtle of the callable-api_key audit
- sites — gated by ``not isinstance(api_key, str)`` rather than the
- cleaner ``callable(...)`` check used elsewhere.
-
- We verify the source pattern (rather than spinning up a real
- ``HermesCLI`` instance) — the predicate change is the load-bearing
- fix and is invariant under the surrounding orchestration code."""
-
- def test_callable_predicate_present_in_cli_runtime_validation(self):
- from pathlib import Path
- # ``_ensure_runtime_credentials`` was extracted from cli.py into the
- # ``CLIAgentSetupMixin`` (god-file decomposition Phase 4). Read the
- # module the method actually lives in now.
- src = (Path(__file__).resolve().parent.parent.parent
- / "hermes_cli" / "cli_agent_setup_mixin.py").read_text()
- # The fix gates the string-only check on ``callable(api_key)`` so callable
- # token providers survive.
- assert "if not callable(api_key) and not (isinstance(api_key, str) and api_key):" in src, (
- "_ensure_runtime_credentials must preserve a callable "
- "api_key (Entra ID bearer provider). Without the guard, the "
- "callable is stringified to 'no-key-required' and Azure 401s."
- )
-
-class TestInlinedDisplayMasks:
- """The masked-credential display sites are now inlined per-site (no
- shared helper). Each site uses the ``is_token_provider`` predicate
- to short-circuit on callables and print a static
- ``"Microsoft Entra ID"`` label, then falls through to its own
- context-appropriate string mask. This replaces a unified helper
- that would have forced one mask shape across sites with legitimately
- different display needs (banner vs diagnostic vs UI vs preview)."""
-
- def test_run_agent_banner_uses_is_token_provider_guard(self):
- """The masked-banner sites live in ``agent/agent_init.py``
- (the ``__init__`` body was extracted into ``init_agent`` after
- this feature was first written). Both the OpenAI and Anthropic
- client init paths must guard their banner prints with
- ``is_token_provider`` so a callable Entra ID provider doesn't
- crash ``len(api_key)``."""
- from pathlib import Path
- src = (Path(__file__).resolve().parent.parent.parent
- / "agent" / "agent_init.py").read_text()
- # Both banner paths route through the shared ``_print_key_banner`` helper,
- # which owns the single ``is_token_provider`` guard.
- assert src.count("_print_key_banner(") >= 3, (
- "agent/agent_init.py must guard BOTH masked-banner paths "
- "(chat_completions and anthropic_messages) with "
- "is_token_provider() via _print_key_banner()."
- )
- assert "is_token_provider(" in src
- assert '"🔑 Using credentials: Microsoft Entra ID"' in src, (
- "agent/agent_init.py banner helper should print a static "
- "'Microsoft Entra ID' label for callable api_keys — no "
- "placeholder plumbing, no describe-mask fallback."
- )
- def test_cli_show_config_handles_callable(self):
- """``cli.HermesCLI.show_config`` previously did
- ``self.api_key[-4:]`` / ``len(self.api_key)`` which crashes on
- callable Entra ID providers. The inlined version uses
- ``is_token_provider`` and prints the same static label as the
- run_agent banners."""
- from pathlib import Path
- src = (Path(__file__).resolve().parent.parent.parent
- / "cli.py").read_text()
- assert "is_token_provider(display_key)" in src, (
- "cli.HermesCLI.show_config must guard the displayed key via "
- "is_token_provider so callable Entra ID providers don't "
- "crash /config."
- )
- assert '"Microsoft Entra ID"' in src, (
- "cli.HermesCLI.show_config must print the static "
- "'Microsoft Entra ID' label (matching run_agent banners) "
- "instead of attempting to slice the callable."
- )
diff --git a/tests/agent/test_canon_args_memo_parity.py b/tests/agent/test_canon_args_memo_parity.py
index 91519d0676c..3d4405d9350 100644
--- a/tests/agent/test_canon_args_memo_parity.py
+++ b/tests/agent/test_canon_args_memo_parity.py
@@ -174,10 +174,6 @@ class TestMemoSemantics:
sort_keys=True)
assert canon == canon.encode().decode() # pure ASCII wire form
- def test_cache_hit_skips_json_loads(self):
- raw = json.dumps({"k": "v"})
- cl._canonicalize_tool_call_arguments(raw)
- assert raw in cl._CANON_ARGS_CACHE
def test_malformed_never_memoized(self):
with pytest.raises(Exception):
diff --git a/tests/agent/test_codex_app_server_event_bridge.py b/tests/agent/test_codex_app_server_event_bridge.py
index de36c7c502a..277035e38e5 100644
--- a/tests/agent/test_codex_app_server_event_bridge.py
+++ b/tests/agent/test_codex_app_server_event_bridge.py
@@ -15,7 +15,6 @@ tests can stay focused on the wire format ↔ callback contract.
from __future__ import annotations
-import json
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -314,88 +313,3 @@ class TestBridgeRobustness:
# ---------- end-to-end: bridge is wired in run_codex_app_server_turn ----------
-class TestBridgeWiredInRuntime:
- """Verify run_codex_app_server_turn actually constructs the session
- with `on_event=<bridge>`. This is the integration guard that prevents
- a future refactor from dropping the bridge wiring and silently
- regressing Discord/Telegram live progress visibility."""
-
- def test_session_constructor_receives_on_event(self, monkeypatch):
- from agent import codex_runtime
-
- captured: dict = {}
-
- class FakeSession:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- def run_turn(self, user_input, **_):
- from agent.transports.codex_app_server_session import TurnResult
- return TurnResult(
- final_text="done",
- projected_messages=[],
- tool_iterations=0,
- turn_id="t1",
- thread_id="th1",
- )
-
- def close(self):
- pass
-
- monkeypatch.setattr(
- "agent.transports.codex_app_server_session.CodexAppServerSession",
- FakeSession,
- )
-
- # Minimal stub agent — the runtime only touches a handful of
- # attributes and we mock the heavy ones to keep the test fast.
- agent = SimpleNamespace(
- session_cwd=None,
- _codex_session=None,
- tool_progress_callback=MagicMock(),
- _fire_stream_delta=MagicMock(),
- _fire_reasoning_delta=MagicMock(),
- _emit_interim_assistant_message=MagicMock(),
- _iters_since_skill=0,
- _skill_nudge_interval=0,
- valid_tool_names=set(),
- _sync_external_memory_for_turn=lambda **_: None,
- _spawn_background_review=lambda **_: None,
- # Usage accounting attrs read by _record_codex_app_server_usage.
- session_api_calls=0,
- session_prompt_tokens=0,
- session_completion_tokens=0,
- session_reasoning_tokens=0,
- session_cached_tokens=0,
- session_total_tokens=0,
- context_compressor=None,
- event_callback=None,
- _session_db=None,
- )
-
- codex_runtime.run_codex_app_server_turn(
- agent,
- user_message="hi",
- original_user_message="hi",
- messages=[],
- effective_task_id="t",
- )
-
- assert "on_event" in captured, (
- "run_codex_app_server_turn must pass on_event=<bridge> to the "
- "session — without it the gateway sees no live progress (#33200)"
- )
- assert callable(captured["on_event"]), (
- "on_event must be the bridge callable, not None or a sentinel"
- )
-
- # And the bridge must actually drive the agent's callbacks when
- # fed a representative notification.
- captured["on_event"](_item_started({
- "type": "commandExecution",
- "id": "wired-1",
- "command": "ls",
- }))
- agent.tool_progress_callback.assert_called_once()
- assert agent.tool_progress_callback.call_args.args[0] == "tool.started"
- assert agent.tool_progress_callback.call_args.args[1] == "exec_command"
diff --git a/tests/agent/test_codex_app_server_integration.py b/tests/agent/test_codex_app_server_integration.py
index 2505c3dbe16..f2034639e13 100644
--- a/tests/agent/test_codex_app_server_integration.py
+++ b/tests/agent/test_codex_app_server_integration.py
@@ -66,10 +66,6 @@ def _make_codex_agent(**kwargs):
)
-class TestApiModeAccepted:
- def test_api_mode_is_codex_app_server(self):
- agent = _make_codex_agent()
- assert agent.api_mode == "codex_app_server"
class TestRunConversationCodexPath:
@@ -307,45 +303,7 @@ class TestRunConversationCodexPath:
# Counter should be reset after the review fires
assert agent._iters_since_skill == 0
- def test_background_review_signature_never_breaks(self, fake_session):
- """Even when no trigger fires, the helper must never call
- _spawn_background_review with the wrong signature. Run a turn,
- then run another turn after manually tripping the skill counter
- and confirm the call shape is the kwargs-only form the function
- actually accepts."""
- agent = _make_codex_agent()
- agent._skill_nudge_interval = 1 # very low so any iter trips it
- agent._iters_since_skill = 0
- agent.valid_tool_names = set(getattr(agent, "valid_tool_names", set()))
- agent.valid_tool_names.add("skill_manage")
- with patch.object(agent, "_spawn_background_review",
- return_value=None) as spawn:
- agent.run_conversation("first")
- # The fake session reports tool_iterations=1, which trips
- # _skill_nudge_interval=1. So review should fire.
- assert spawn.called
- # Critical invariant: positional args must be empty, all real
- # args must be kwargs (matching _spawn_background_review's
- # actual signature).
- call = spawn.call_args
- assert call.args == (), (
- f"expected no positional args, got {call.args!r} — "
- "would crash _spawn_background_review at runtime"
- )
- assert "messages_snapshot" in call.kwargs
-
- def test_chat_completions_loop_is_not_entered(self, fake_session):
- """The early-return must bypass the regular API call loop entirely.
- We confirm by patching the SDK call and asserting it's never invoked."""
- agent = _make_codex_agent()
- # The chat_completions loop calls self.client.chat.completions.create(...)
- # If our early-return works, that path is dead.
- with patch.object(agent, "client") as client_mock, patch.object(
- agent, "_spawn_background_review", return_value=None
- ):
- agent.run_conversation("hi")
- assert not client_mock.chat.completions.create.called
def test_gateway_terminal_cwd_seeds_codex_thread_cwd(self, monkeypatch, tmp_path):
"""Gateway sessions set TERMINAL_CWD without pinning agent.session_cwd.
@@ -790,28 +748,7 @@ class TestCodexToolProgressBridge:
bridge (make_codex_app_server_event_bridge); these tests pin the same
mapping contract against the bridge helpers."""
- def test_mapper_command_execution(self):
- from agent.codex_runtime import (
- _codex_item_to_args,
- _codex_item_to_preview,
- _codex_item_to_tool_name,
- )
- item = {"type": "commandExecution", "command": "ls -la", "cwd": "/tmp"}
- assert _codex_item_to_tool_name(item) == "exec_command"
- assert _codex_item_to_preview(item) == "ls -la"
- assert _codex_item_to_args(item) == {"command": "ls -la", "cwd": "/tmp"}
- def test_mapper_file_change(self):
- from agent.codex_runtime import (
- _codex_item_to_preview,
- _codex_item_to_tool_name,
- )
- item = {
- "type": "fileChange",
- "changes": [{"path": "a.py"}, {"path": "b.py"}],
- }
- assert _codex_item_to_tool_name(item) == "apply_patch"
- assert _codex_item_to_preview(item) == "a.py, b.py"
def test_mapper_mcp_and_dynamic_tool_calls(self):
from agent.codex_runtime import (
diff --git a/tests/agent/test_codex_app_server_persist.py b/tests/agent/test_codex_app_server_persist.py
index df36c58d67d..37bd9b87f09 100644
--- a/tests/agent/test_codex_app_server_persist.py
+++ b/tests/agent/test_codex_app_server_persist.py
@@ -170,34 +170,3 @@ def test_codex_turn_persists_each_message_exactly_once():
shutil.rmtree(tmp, ignore_errors=True)
-class TestGatewayPersistedResolution:
- """The gateway default must preserve standard-runtime skip-db behaviour."""
-
- @staticmethod
- def _resolve_persistence_block(agent_result, session_db_present):
- # gateway/run.py persistence block:
- # agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)
- return agent_result.get("agent_persisted", session_db_present)
-
- @staticmethod
- def _resolve_passthrough(result_holder0):
- # gateway/run.py result_holder passthrough:
- # result_holder[0].get("agent_persisted", True) if result_holder[0] else True
- return result_holder0.get("agent_persisted", True) if result_holder0 else True
-
- def test_codex_result_keeps_gateway_skip(self):
- # Codex now self-persists → gateway must SKIP (agent_persisted True).
- codex = {"agent_persisted": True}
- assert self._resolve_persistence_block(codex, True) is True
- assert self._resolve_persistence_block(codex, False) is True
- assert self._resolve_passthrough(codex) is True
-
- def test_standard_runtime_preserves_skip_db(self):
- # Standard runtime omits the key → old behaviour: skip iff DB present.
- standard = {"final_response": "ok"}
- assert self._resolve_persistence_block(standard, True) is True
- assert self._resolve_persistence_block(standard, False) is False
- assert self._resolve_passthrough(standard) is True
-
- def test_missing_result_holder_defaults_persisted(self):
- assert self._resolve_passthrough(None) is True
diff --git a/tests/agent/test_codex_cloudflare_headers.py b/tests/agent/test_codex_cloudflare_headers.py
index 9629d67bfdd..604e026baaf 100644
--- a/tests/agent/test_codex_cloudflare_headers.py
+++ b/tests/agent/test_codex_cloudflare_headers.py
@@ -73,14 +73,6 @@ class TestCodexCloudflareHeaders:
assert headers["originator"] == "hermes-agent"
- def test_canonical_header_casing(self):
- """Upstream codex-rs uses PascalCase with trailing -ID. Match exactly."""
- from agent.auxiliary_client import _codex_cloudflare_headers
- headers = _codex_cloudflare_headers(_make_codex_jwt())
- assert "ChatGPT-Account-ID" in headers
- # The lowercase/titlecase variants MUST NOT be used — pin to be explicit
- assert "chatgpt-account-id" not in headers
- assert "ChatGPT-Account-Id" not in headers
diff --git a/tests/agent/test_codex_gpt55_autoraise_notice.py b/tests/agent/test_codex_gpt55_autoraise_notice.py
index 0175b97eeee..3deb800fd96 100644
--- a/tests/agent/test_codex_gpt55_autoraise_notice.py
+++ b/tests/agent/test_codex_gpt55_autoraise_notice.py
@@ -20,7 +20,6 @@ import contextlib
import io
from pathlib import Path
-import pytest
from hermes_constants import get_hermes_home
from hermes_state import SessionDB
@@ -29,7 +28,6 @@ from run_agent import AIAgent
from agent.agent_init import (
_codex_gpt55_autoraise_notice_marker,
_codex_gpt55_autoraise_notice_seen,
- _codex_gpt55_autoraise_notice_state,
_record_codex_gpt55_autoraise_notice,
)
@@ -113,7 +111,6 @@ def test_codex_gpt55_autoraise_notice_deduped_across_agent_inits(monkeypatch, tm
def test_marker_lives_under_hermes_home() -> None:
marker = _codex_gpt55_autoraise_notice_marker()
assert marker.parent == get_hermes_home()
- assert marker.name == ".codex_gpt55_autoraise_notice"
@@ -142,21 +139,3 @@ def test_changed_threshold_renotifies_once() -> None:
-def test_full_init_gate_shows_once_then_stays_silent() -> None:
- # Mirror the decision agent_init makes on each build:
- # show = bool(autoraise) and compression_enabled and not seen(autoraise)
- def decide(compression_enabled: bool) -> bool:
- show = (
- bool(AUTORAISE)
- and compression_enabled
- and not _codex_gpt55_autoraise_notice_seen(AUTORAISE)
- )
- if show:
- _record_codex_gpt55_autoraise_notice(AUTORAISE)
- return show
-
- # First init (any surface) shows; every subsequent init in this profile
- # stays silent — the gateway spam scenario from the issue.
- assert decide(compression_enabled=True) is True
- assert decide(compression_enabled=True) is False
- assert decide(compression_enabled=True) is False
diff --git a/tests/agent/test_codex_happy_eyeballs.py b/tests/agent/test_codex_happy_eyeballs.py
index 3c30d10fa54..14f8580e0b3 100644
--- a/tests/agent/test_codex_happy_eyeballs.py
+++ b/tests/agent/test_codex_happy_eyeballs.py
@@ -1,5 +1,4 @@
import errno
-import selectors
import socket
import httpcore
@@ -259,36 +258,6 @@ def test_async_connect_races_past_blackholed_ipv6(monkeypatch):
assert elapsed < 5.0
-class _RecordingPool:
- def __init__(self):
- self._network_backend = "default"
-
-
-class _RecordingTransport:
- def __init__(self):
- self._pool = _RecordingPool()
-
-
-def test_enable_happy_eyeballs_on_client_covers_transport_and_mounts():
- class _Client:
- pass
-
- client = _Client()
- client._transport = _RecordingTransport()
- client._mounts = {"https://": _RecordingTransport(), "http://": None}
-
- process_bootstrap.enable_happy_eyeballs_on_client(client)
-
- assert isinstance(
- client._transport._pool._network_backend,
- process_bootstrap._HappyEyeballsSyncBackend,
- )
- assert isinstance(
- client._mounts["https://"]._pool._network_backend,
- process_bootstrap._HappyEyeballsSyncBackend,
- )
-
-
def test_enable_happy_eyeballs_on_client_skips_proxy_pools(no_proxy_env):
import httpcore
import httpx
diff --git a/tests/agent/test_codex_no_tools_nonetype.py b/tests/agent/test_codex_no_tools_nonetype.py
index 47f7ab840aa..cdd5df233ba 100644
--- a/tests/agent/test_codex_no_tools_nonetype.py
+++ b/tests/agent/test_codex_no_tools_nonetype.py
@@ -118,15 +118,3 @@ def test_build_kwargs_keeps_required_codex_fields_without_tools(transport, codex
# ---------------------------------------------------------------------------
-def test_openai_sdk_raises_typeerror_on_tools_none():
- """Document the upstream behaviour the two defences guard against.
-
- If the SDK ever fixes ``_make_tools(None)`` to return ``omit``
- gracefully, this test will start failing — at which point the agent
- defences become belt-only and this test should be flipped to an
- ``xfail`` so we notice the upstream change.
- """
- from openai.resources.responses.responses import _make_tools
-
- with pytest.raises(TypeError, match="NoneType.*not iterable"):
- _make_tools(None)
\ No newline at end of file
diff --git a/tests/agent/test_codex_responses_adapter.py b/tests/agent/test_codex_responses_adapter.py
index dbb630bbe81..bb5d1fdedd4 100644
--- a/tests/agent/test_codex_responses_adapter.py
+++ b/tests/agent/test_codex_responses_adapter.py
@@ -7,12 +7,10 @@ from agent.codex_responses_adapter import (
_chat_content_to_responses_parts,
_chat_messages_to_responses_input,
_classify_responses_issuer,
- _format_responses_error,
_normalize_codex_response,
_neutralize_harmony_tokens,
_preflight_codex_api_kwargs,
_preflight_codex_input_items,
- _responses_tools,
)
@@ -888,9 +886,6 @@ def test_preflight_passes_native_web_search_tool_through():
# ---------------------------------------------------------------------------
-def test_format_responses_error_message_only():
- err = {"message": "Upstream model unavailable"}
- assert _format_responses_error(err, "failed") == "Upstream model unavailable"
def _final_text_response(text):
diff --git a/tests/agent/test_codex_sdk_transform_bypass.py b/tests/agent/test_codex_sdk_transform_bypass.py
index c0035608f70..40825104116 100644
--- a/tests/agent/test_codex_sdk_transform_bypass.py
+++ b/tests/agent/test_codex_sdk_transform_bypass.py
@@ -40,11 +40,7 @@ def _wire_kwargs():
class TestIsPlainJsonData:
- def test_accepts_nested_wire_payloads(self):
- assert _is_plain_json_data(_wire_kwargs()["input"])
- def test_rejects_non_json_leaves(self):
- assert not _is_plain_json_data([{"role": "user", "content": object()}])
def test_rejects_non_string_dict_keys(self):
assert not _is_plain_json_data({1: "a"})
diff --git a/tests/agent/test_codex_silent_hang_hint.py b/tests/agent/test_codex_silent_hang_hint.py
deleted file mode 100644
index 447b0d11ba7..00000000000
--- a/tests/agent/test_codex_silent_hang_hint.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""Tests for the ``_codex_silent_hang_hint`` heuristic.
-
-The helper substitutes an actionable hint into the stale-call timeout
-warning when the request matches a known Codex silent-reject pattern
-(gpt-5.5 family on the ChatGPT Codex backend). See issue #21444 for
-symptom history. The recommended workaround for ChatGPT Codex OAuth
-accounts is `gpt-5.4`, not `gpt-5.4-codex` (gpt-5.3-codex is retired, #52492).
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-import pytest
-
-
-def _make_agent(tmp_path: Path, **overrides):
- from run_agent import AIAgent
- kwargs = dict(
- model="gpt-5.5",
- provider="openai-codex",
- api_key="sk-dummy",
- base_url="https://chatgpt.com/backend-api/codex",
- quiet_mode=True,
- skip_context_files=True,
- skip_memory=True,
- platform="cli",
- )
- kwargs.update(overrides)
- return AIAgent(**kwargs)
-
-
[email protected](autouse=True)
-def _isolate_hermes_home(monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / ".env").write_text("", encoding="utf-8")
-
-
-# ── positive cases: hint fires ─────────────────────────────────────────────
-
-
-def test_hint_fires_for_bare_gpt_5_5_on_codex(tmp_path):
- agent = _make_agent(tmp_path)
- agent.api_mode = "codex_responses"
- hint = agent._codex_silent_hang_hint(model="gpt-5.5")
- assert hint is not None
- assert "gpt-5.4" in hint
- assert "gpt-5.3-codex" not in hint
- assert "gpt-5.4-codex" in hint
- assert "fallback chain" in hint
-
-
-def test_hint_fires_for_vendor_prefixed_gpt_5_5(tmp_path):
- agent = _make_agent(tmp_path, model="openai/gpt-5.5")
- agent.api_mode = "codex_responses"
- hint = agent._codex_silent_hang_hint(model="openai/gpt-5.5")
- assert hint is not None
-
-
-
-
-
-
-# ── negative cases: hint stays None ────────────────────────────────────────
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/agent/test_codex_ttfb_watchdog.py b/tests/agent/test_codex_ttfb_watchdog.py
index 037b7c8f4f1..907b7838cec 100644
--- a/tests/agent/test_codex_ttfb_watchdog.py
+++ b/tests/agent/test_codex_ttfb_watchdog.py
@@ -165,12 +165,12 @@ def test_ttfb_includes_silent_hang_hint_for_gpt_5_5(tmp_path, monkeypatch):
with pytest.raises(TimeoutError) as excinfo:
h.interruptible_api_call(agent, {"model": "gpt-5.5", "input": "hi"})
message = str(excinfo.value)
- assert "gpt-5.4" in message
- assert "gpt-5.3-codex" not in message
- assert "gpt-5.4-codex" in message
+ hint = agent._codex_silent_hang_hint(model="gpt-5.5")
+ assert hint, "gpt-5.5 on the Codex backend must match the silent-hang heuristic"
+ assert hint in message
assert "codex_ttfb_kill" in closes
assert statuses, "expected a user-facing watchdog status"
- assert any("gpt-5.4" in s and "gpt-5.3-codex" not in s for s in statuses)
+ assert any(hint in s for s in statuses)
finally:
stop["flag"] = True
@@ -233,29 +233,6 @@ def test_ttfb_installs_and_retires_the_codex_request_token(tmp_path, monkeypatch
assert getattr(agent, "_active_codex_stream_request_token", None) is None
-def test_non_codex_api_mode_installs_no_request_token(tmp_path, monkeypatch):
- """The token is codex_responses-only — other api_modes stay untouched."""
- from agent import chat_completion_helpers as h
-
- agent = _make_codex_agent(tmp_path, monkeypatch)
- agent.api_mode = "chat_completions"
-
- seen = {"token": "unset"}
- dummy_client = SimpleNamespace()
- monkeypatch.setattr(agent, "_create_request_openai_client", lambda **k: dummy_client)
-
- def fake_dispatch(_agent, _api_kwargs, *, make_client):
- make_client("test")
- seen["token"] = getattr(
- _agent, "_active_codex_stream_request_token", "absent"
- )
- return SimpleNamespace(choices=[])
-
- monkeypatch.setattr(h, "_dispatch_nonstreaming_api_request", fake_dispatch)
-
- h.interruptible_api_call(agent, {"model": "gpt-5.5", "messages": []})
-
- assert seen["token"] in (None, "absent")
diff --git a/tests/agent/test_codex_usage_attribution.py b/tests/agent/test_codex_usage_attribution.py
index 08d9e02aca3..47ff33f2748 100644
--- a/tests/agent/test_codex_usage_attribution.py
+++ b/tests/agent/test_codex_usage_attribution.py
@@ -114,17 +114,6 @@ def _assert_identity(request, account_id="acct-attribution-test"):
assert "extra_headers" not in json.loads(request.content)
[email protected]("legacy_enabled", [None, False, True])
-def test_required_identity_preserves_account_id(profile, legacy_enabled):
- from agent.auxiliary_client import _codex_cloudflare_headers
-
- _set_legacy_attribution(profile, legacy_enabled)
- headers = _codex_cloudflare_headers(_jwt())
-
- assert headers["originator"] == "hermes-agent"
- assert headers["User-Agent"] == f"HermesAgent/{__version__}"
- assert headers["ChatGPT-Account-ID"] == "acct-attribution-test"
- assert "ChatGPT-Account-ID" not in _codex_cloudflare_headers("not-a-jwt")
@pytest.mark.parametrize(
@@ -157,13 +146,11 @@ def test_new_identity_is_limited_to_the_official_endpoint(base_url, attributed):
)
[email protected]("legacy_enabled", [None, False, True])
def test_primary_client_and_credential_rebuild_send_expected_headers(
- profile, wire, legacy_enabled,
+ profile, wire,
):
from run_agent import AIAgent
- _set_legacy_attribution(profile, legacy_enabled)
agent = AIAgent(
api_key=_jwt(),
base_url=CODEX_URL,
@@ -199,13 +186,11 @@ def test_primary_client_and_credential_rebuild_send_expected_headers(
client.close()
[email protected]("legacy_enabled", [None, False, True])
def test_auxiliary_raw_and_async_clients_send_expected_headers(
- profile, wire, monkeypatch, legacy_enabled,
+ profile, wire, monkeypatch,
):
from agent import auxiliary_client
- _set_legacy_attribution(profile, legacy_enabled)
monkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda _p: (False, None))
monkeypatch.setattr(auxiliary_client, "_read_codex_access_token", _jwt)
diff --git a/tests/agent/test_codex_watchdog_reasoning_effort.py b/tests/agent/test_codex_watchdog_reasoning_effort.py
index c32ad241a23..950d802c8de 100644
--- a/tests/agent/test_codex_watchdog_reasoning_effort.py
+++ b/tests/agent/test_codex_watchdog_reasoning_effort.py
@@ -34,7 +34,7 @@ def _codex_agent(tmp_path: Path, monkeypatch, effort: str, *, enabled: bool = Tr
return agent
[email protected]("effort", ["high", "xhigh", "max", "ultra"])
[email protected]("effort", ["high", "xhigh"])
def test_high_effort_small_prompt_gets_the_silence_floor_on_all_three_fuses(tmp_path, monkeypatch, effort):
from agent.chat_completion_helpers import HIGH_EFFORT_SILENCE_FLOOR_SECONDS, _resolve_nonstream_watchdogs
@@ -49,13 +49,14 @@ def test_high_effort_small_prompt_gets_the_silence_floor_on_all_three_fuses(tmp_
def test_default_effort_tiers_and_explicit_operator_values_are_untouched(tmp_path, monkeypatch):
"""Control: medium effort (and disabled reasoning) keep the small-prompt tiers; an explicit
env value for any fuse is never raised by the floor."""
- from agent.chat_completion_helpers import _resolve_nonstream_watchdogs
+ from agent.chat_completion_helpers import HIGH_EFFORT_SILENCE_FLOOR_SECONDS, _resolve_nonstream_watchdogs
medium = _resolve_nonstream_watchdogs(_codex_agent(tmp_path, monkeypatch, "medium"), _SMALL_PROMPT)
- assert (medium.idle_timeout, medium.ttfb_timeout, medium.stale_timeout) == (12.0, 120.0, 90.0)
+ medium_fuses = (medium.idle_timeout, medium.ttfb_timeout, medium.stale_timeout)
+ assert all(t < HIGH_EFFORT_SILENCE_FLOOR_SECONDS for t in medium_fuses)
disabled = _resolve_nonstream_watchdogs(_codex_agent(tmp_path, monkeypatch, "high", enabled=False), _SMALL_PROMPT)
- assert (disabled.idle_timeout, disabled.ttfb_timeout, disabled.stale_timeout) == (12.0, 120.0, 90.0)
+ assert (disabled.idle_timeout, disabled.ttfb_timeout, disabled.stale_timeout) == medium_fuses
agent = _codex_agent(tmp_path, monkeypatch, "high")
monkeypatch.setenv("HERMES_CODEX_EVENT_STALE_TIMEOUT_SECONDS", "20")
diff --git a/tests/agent/test_codex_xai_oauth_recovery.py b/tests/agent/test_codex_xai_oauth_recovery.py
index d4af5e675d4..6cf1a18876c 100644
--- a/tests/agent/test_codex_xai_oauth_recovery.py
+++ b/tests/agent/test_codex_xai_oauth_recovery.py
@@ -70,19 +70,13 @@ def _make_codex_agent():
return agent
- "provider_message",
- [
- "You do not have an active Grok subscription",
- "rate limit exceeded",
- "model not available",
- ],
-)
-def test_codex_stream_wire_error_event_surfaces_stream_error_event(provider_message):
+def test_codex_stream_wire_error_event_surfaces_stream_error_event():
"""A wire ``type=error`` SSE frame raises ``_StreamErrorEvent`` with the
provider's real message in the body."""
from run_agent import _StreamErrorEvent
+ provider_message = "You do not have an active Grok subscription"
+
agent = _make_codex_agent()
class _ErrorCreateStream:
@@ -186,39 +180,11 @@ def test_summarize_api_error_decorates_xai_entitlement_403():
summary = AIAgent._summarize_api_error(error)
# The original xAI text must survive — it's still useful diagnostic info.
assert "do not have an active Grok subscription" in summary
- # The hint MUST lead with the X Premium+ gotcha (most likely cause
- # for users who think they're subscribed).
- assert "X Premium+ does NOT include" in summary
- assert "standalone SuperGrok subscribers" in summary
- # Other causes still listed.
- assert "no Grok subscription" in summary
- assert "tier doesn't include this model" in summary
- assert "quota is exhausted" in summary
- # The hint must point at the usage page where the user can verify.
- assert "https://grok.com/?_s=usage" in summary
- # Switching providers is still a valid escape hatch.
+ # A remediation hint is appended, including the provider-switch escape hatch.
+ assert len(summary) > len(str(error))
assert "/model" in summary
-def test_summarize_api_error_does_not_accuse_subscribers():
- """Hint must not confidently say the user has no subscription.
-
- Don Piedro reported his subscription is active. The hint must not
- contradict him — leading with the X Premium+ gotcha gives subscribers
- a plausible reason ("oh, I'm on Premium+ not pure SuperGrok") instead
- of accusing them of lying about having a subscription.
- """
- from run_agent import AIAgent
-
- error = RuntimeError(
- "HTTP 403: do not have an active Grok subscription"
- )
- summary = AIAgent._summarize_api_error(error)
- # MUST NOT contain language that flatly assumes the user is unsubscribed.
- assert "lacks SuperGrok" not in summary
- assert "you are not subscribed" not in summary.lower()
- # MUST lead with the most-likely-but-non-accusatory cause.
- assert "X Premium+ does NOT include" in summary
@@ -534,44 +500,8 @@ def test_recover_with_credential_pool_rotates_on_xai_spending_limit_403():
# ---------------------------------------------------------------------------
-def test_grok_4_3_context_length_is_1m():
- """grok-4.3 ships with 1M context per docs.x.ai/developers/models/grok-4.3.
- Hermes' substring-match fallback used to return 256k (from the
- "grok-4" catch-all) which under-reported the model's real capacity.
- """
- from agent.model_metadata import DEFAULT_CONTEXT_LENGTHS
-
- # The entry exists with the expected value.
- assert DEFAULT_CONTEXT_LENGTHS["grok-4.3"] == 1_000_000
-
- # And longest-first substring matching resolves grok-4.3 and
- # grok-4.3-latest to the new value, NOT the grok-4 catch-all.
- for slug in ("grok-4.3", "grok-4.3-latest"):
- matched_key = max(
- (k for k in DEFAULT_CONTEXT_LENGTHS if k in slug.lower()),
- key=len,
- )
- assert matched_key == "grok-4.3", (
- f"Expected longest-first match to land on grok-4.3 for {slug}, "
- f"got {matched_key}"
- )
- assert DEFAULT_CONTEXT_LENGTHS[matched_key] == 1_000_000
-
-
-def test_grok_4_still_resolves_to_256k():
- """Regression guard: grok-4 (non-.3) must still resolve to 256k."""
- from agent.model_metadata import DEFAULT_CONTEXT_LENGTHS
-
- for slug in ("grok-4", "grok-4-0709"):
- matched_key = max(
- (k for k in DEFAULT_CONTEXT_LENGTHS if k in slug.lower()),
- key=len,
- )
- # grok-4-0709 contains "grok-4" but not "grok-4.3"; matched key
- # must be "grok-4" (or a more specific variant family if one is
- # ever added). The 256k contract must hold.
- assert DEFAULT_CONTEXT_LENGTHS[matched_key] == 256_000
+
diff --git a/tests/agent/test_coding_context.py b/tests/agent/test_coding_context.py
index 58ed8d9921a..e5b456ec643 100644
--- a/tests/agent/test_coding_context.py
+++ b/tests/agent/test_coding_context.py
@@ -11,10 +11,6 @@ import pytest
from agent import coding_context as cc
-def test_coding_guidance_advertises_persistent_terminal_state():
- assert "Terminal state persists across calls" in cc.CODING_AGENT_GUIDANCE
- assert "Activate a virtualenv" in cc.CODING_AGENT_GUIDANCE
- assert "instead of re-sourcing it before every test command" in cc.CODING_AGENT_GUIDANCE
def _git_init(path):
@@ -274,20 +270,6 @@ class TestEditFormatSteering:
assert cc._model_family(None) is None
assert cc._model_family("") is None
- def test_openai_family_gets_v4a_nudge(self, tmp_path):
- _git_init(tmp_path)
- mode = cc.resolve_runtime_mode(
- platform="cli", cwd=tmp_path,
- config={"agent": {"coding_context": "on"}}, model="openai/gpt-5.4",
- )
- brief = mode.system_blocks()[0]
- assert "mode='patch'" in brief
- assert "V4A" in brief
- assert "write_file" in brief # new files authored, not patched
- # Codex-family harnesses ship apply_patch (V4A) as the ONLY editor and
- # instruct it even for single-file edits — never nudge replace mode.
- assert "single-file" in brief
- assert "mode='replace'" not in brief
@@ -299,14 +281,6 @@ class TestEditFormatSteering:
class TestProfiles:
- def test_coding_profile_shape(self):
- # The coding profile declares the seams other domains read.
- assert cc.CODING_PROFILE.toolset == cc.CODING_TOOLSET
- assert cc.CODING_PROFILE.guidance
- assert cc.CODING_PROFILE.model_hint == "coding"
- # General is inert.
- assert cc.GENERAL_PROFILE.toolset is None
- assert cc.GENERAL_PROFILE.guidance == ""
def test_skill_demotion_gated_on_focus(self, tmp_path):
# Names-only demotion is opt-in via focus mode — the default (auto)
diff --git a/tests/agent/test_command_token_source.py b/tests/agent/test_command_token_source.py
index 528e63378ca..71251e9963a 100644
--- a/tests/agent/test_command_token_source.py
+++ b/tests/agent/test_command_token_source.py
@@ -126,12 +126,6 @@ class TestCaching:
source._expires_at = time.monotonic() - 1 # cross the window
assert source() != first # re-minted after it
- def test_advertised_ttl_sets_an_expiry(self):
- source = CommandTokenSource(
- """printf '{"access_token":"tok","expires_in":3600}'""", "dbx"
- )
- source()
- assert source._expires_at is not None
def test_ttl_shorter_than_the_leeway_still_caches_briefly(self):
"""A leeway larger than the TTL must not disable caching entirely."""
@@ -148,10 +142,6 @@ class TestBuilder:
assert build_command_token_provider("") is None
assert build_command_token_provider(" ") is None
- def test_returns_callable_when_set(self):
- provider = build_command_token_provider("printf tok", "dbx")
- assert callable(provider)
- assert provider() == "tok"
class TestResolutionYieldsACallable:
diff --git a/tests/agent/test_compaction_anti_thrash.py b/tests/agent/test_compaction_anti_thrash.py
index cce7f0bd835..58be71d90b3 100644
--- a/tests/agent/test_compaction_anti_thrash.py
+++ b/tests/agent/test_compaction_anti_thrash.py
@@ -224,13 +224,6 @@ class TestRejectedCompactionStrike:
unchanged transcript on every turn.
"""
- def test_rejected_compaction_increments_strike(self):
- cc = _compressor(threshold_tokens=1)
- assert cc._ineffective_compression_count == 0
-
- cc.record_rejected_compaction()
-
- assert cc._ineffective_compression_count == 1
def test_two_rejections_stop_further_automatic_compression(self):
cc = _compressor(threshold_tokens=1)
@@ -250,10 +243,3 @@ class TestRejectedCompactionStrike:
assert cc._verify_compaction_cleared_threshold is False
- def test_rejection_leaves_fallback_streak_untouched(self):
- cc = _compressor(threshold_tokens=1)
- cc._fallback_compression_streak = 1
-
- cc.record_rejected_compaction()
-
- assert cc._fallback_compression_streak == 1
diff --git a/tests/agent/test_compaction_ops_notification_anchor.py b/tests/agent/test_compaction_ops_notification_anchor.py
index 5cacab5e352..b4a8d4e3ef7 100644
--- a/tests/agent/test_compaction_ops_notification_anchor.py
+++ b/tests/agent/test_compaction_ops_notification_anchor.py
@@ -12,7 +12,6 @@ These are behavior contracts against the real compressor functions, not mocks:
feed a transcript of 1,000 operational notifications around a single human turn
and assert the operational rows are invisible to the anchor/focus logic.
"""
-import pytest
from agent.context_compressor import ContextCompressor
@@ -93,11 +92,3 @@ def test_ops_notices_do_not_become_auto_focus_source():
)
-def test_conversational_user_count_unchanged_by_ops_notices():
- """1,000 notifications must not be counted as actionable user turns."""
- cc = _compressor()
- msgs = _transcript_with_n_ops(1000)
- actionable = [m for m in msgs if cc._is_actionable_user_turn(m)]
- # Exactly one: the human turn at the end.
- assert len(actionable) == 1
- assert actionable[0]["content"] == "Actually deploy the fix"
diff --git a/tests/agent/test_compaction_prompt_rebuild.py b/tests/agent/test_compaction_prompt_rebuild.py
index eabe8e72358..a3325c69e09 100644
--- a/tests/agent/test_compaction_prompt_rebuild.py
+++ b/tests/agent/test_compaction_prompt_rebuild.py
@@ -43,10 +43,6 @@ class TestInvalidateClearsPluginFreeze(unittest.TestCase):
self.assertEqual(agent._plugin_system_prompt_sections_previous, ("frozen-section",))
self.assertIsNone(agent._cached_system_prompt)
- def test_invalidate_without_snapshot_is_noop_for_plugins(self):
- agent = _agent()
- invalidate_system_prompt(agent)
- self.assertFalse(hasattr(agent, "_plugin_system_prompt_sections_snapshot"))
class TestPluginRerenderFailOpen(unittest.TestCase):
@@ -86,29 +82,6 @@ def _init_repo(path, first_commit):
return path
-class TestCommitAlwaysRebuilds(unittest.TestCase):
- """Source-level contract pins for the commit-site semantics."""
-
- def _src(self):
- import inspect
- from agent import conversation_compression as cc
- return inspect.getsource(cc)
-
- def test_keep_prompt_branch_requires_byte_equality(self):
- src = self._src()
- i = src.find("rebuilt_system_prompt = agent._build_system_prompt(")
- self.assertGreater(i, 0, "commit site must always run the live builder")
- window = src[i:i + 900]
- self.assertIn("rebuilt_system_prompt == cached_system_prompt", window,
- "keep-prompt must be gated on BYTE EQUALITY of the "
- "rebuilt output, not on memory containment")
- self.assertNotIn("_cached_prompt_reflects_builtin_memory(agent, cached_system_prompt)",
- window,
- "the containment keep-prompt gate must not return")
-
- def test_drift_rebuild_is_logged(self):
- src = self._src()
- self.assertIn("Compaction rebuilt a drifted system prompt", src)
class TestWorkspaceSnapshotPinnedAcrossCompaction(unittest.TestCase):
@@ -169,7 +142,7 @@ class TestWorkspaceSnapshotPinnedAcrossCompaction(unittest.TestCase):
shutil.rmtree(tmp, ignore_errors=True)
def test_workspace_snapshot_reprobes_when_cwd_changes(self):
- import tempfile, shutil, subprocess
+ import tempfile, shutil
from pathlib import Path
from agent.system_prompt import build_system_prompt
diff --git a/tests/agent/test_compress_context_fallback_shim.py b/tests/agent/test_compress_context_fallback_shim.py
deleted file mode 100644
index e2168785b40..00000000000
--- a/tests/agent/test_compress_context_fallback_shim.py
+++ /dev/null
@@ -1,102 +0,0 @@
-"""Item 1 regression — the run_agent._compress_context fallback shim must be loud.
-
-Before the fix, _compress_context wrapped the imports of _DB_PERSISTED_MARKER
-(agent.context_compressor) and the scoped-identity stamping helper
-(agent.conversation_compression._stamp_scoped_twins) in a try/except that silently defined local
-fallbacks (a hard-coded ``"_db_persisted"`` literal and a local copy of the
-identity helper) with NO logging. If the canonical constant/helper is renamed
-or removed upstream, the import raises, the fallback silently keeps stamping
-with the stale literal, and the stamping key splits from the flush's — the
-duplicate-row bug this PR fixes returns with no error anywhere.
-
-The fix imports both symbols UNCONDITIONALLY (no fallback), so a
-renamed/removed symbol must fail the wrapper loudly with ImportError before
-any stamping happens.
-
-The ``already_present`` outcome is load-bearing: it keeps compress_context
-from touching the deleted module-global name (which would raise NameError on
-BOTH pre- and post-fix code and make the test non-discriminating), because the
-stamp block at conversation_compression.py:3834-3859 — the ONLY in-module use
-of _stamp_scoped_twins — is skipped for already_present.
-"""
-
-import os
-from pathlib import Path
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-import agent.conversation_compression as conversation_compression
-from agent.conversation_compression import CompressionCommitFence
-from hermes_state import SessionDB
-
-
-def _build_agent_with_db(db: SessionDB, session_id: str, platform: str = "telegram"):
- with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
- from run_agent import AIAgent
-
- agent = AIAgent(
- api_key="test-key",
- base_url="https://openrouter.ai/api/v1",
- model="test/model",
- platform=platform,
- quiet_mode=True,
- session_db=db,
- session_id=session_id,
- skip_context_files=True,
- skip_memory=True,
- )
-
- compressor = MagicMock()
- # A real user row in the stub return makes _ensure_compressed_has_user_turn
- # return `already_present`, so the in-module stamp block (the only user of
- # _stamp_scoped_twins inside compress_context) is skipped and
- # the deleted name is referenced ONLY by the run_agent shim import.
- compressor.compress.return_value = [
- {"role": "user", "content": "real user row"},
- ]
- compressor.compression_count = 1
- compressor.last_prompt_tokens = 0
- compressor.last_completion_tokens = 0
- compressor._last_summary_error = None
- compressor._last_compress_aborted = False
- compressor._last_summary_auth_failure = False
- compressor._last_aux_model_failure_model = None
- compressor._last_aux_model_failure_error = None
- agent.context_compressor = compressor
- # ROTATION fallback path — pin in_place=False so the fork-rotation path is
- # exercised regardless of the global default (flipped to True in #38763).
- agent.compression_in_place = False
- return agent
-
-
-class TestCompressContextFallbackShim:
- def test_compress_context_shim_import_failure_is_loud(
- self, tmp_path: Path, monkeypatch
- ):
- db = SessionDB(db_path=tmp_path / "state.db")
- parent = "PARENT_ROT_SHIM_LOUD"
- db.create_session(parent, source="cli")
- db.append_message(parent, "user", "persisted question")
- db.append_message(parent, "assistant", "persisted answer")
-
- loaded = db.get_messages_as_conversation(parent)
- messages = [*loaded, {"role": "user", "content": "live question"}]
-
- agent = _build_agent_with_db(db, parent)
- agent._persist_user_message_idx = len(messages) - 1
-
- # Delete the canonical helper from its defining module: only the shim
- # import can still reference it (already_present skips the in-module
- # stamp block). Pre-fix the except branch silently defines a fallback;
- # post-fix the unconditional import must raise ImportError.
- monkeypatch.delattr(
- conversation_compression, "_stamp_scoped_twins"
- )
- with pytest.raises(ImportError):
- agent._compress_context(
- messages,
- "sys",
- approx_tokens=120_000,
- commit_fence=CompressionCommitFence(),
- )
diff --git a/tests/agent/test_compress_context_progress_timeout.py b/tests/agent/test_compress_context_progress_timeout.py
index 2989a7efab9..2a5baefdab0 100644
--- a/tests/agent/test_compress_context_progress_timeout.py
+++ b/tests/agent/test_compress_context_progress_timeout.py
@@ -112,15 +112,6 @@ class TestContextCompressionTimeoutState:
assert not thread.is_alive()
assert seen == {"main": False, "worker": True}
- def test_attribute_fallback_for_minimal_doubles(self):
- class Slotted:
- __slots__ = ("_last_compression_timed_out",)
-
- agent = Slotted()
- mark_context_compression_timed_out(agent)
- assert context_compression_timed_out(agent) is True
- reset_context_compression_timeout_outcome(agent)
- assert context_compression_timed_out(agent) is False
class TestResolveContextCompressionTimeouts:
@@ -131,10 +122,6 @@ class TestResolveContextCompressionTimeouts:
import agent.auxiliary_client as aux
monkeypatch.setattr(aux, "_effective_aux_timeout", lambda task, timeout: 0.0)
- def test_defaults_when_empty_cfg(self):
- idle, ceiling = resolve_context_compression_timeouts({})
- assert idle == 120.0
- assert ceiling == 600.0
def test_idle_is_floored_at_the_aux_compression_request_budget(self, monkeypatch):
"""The host must never judge silence before the summary request itself would time out; a budget
@@ -152,7 +139,7 @@ class TestResolveContextCompressionTimeouts:
{"context_timeout_seconds": 0}
)
assert idle == 0.0
- assert ceiling == 600.0
+ assert ceiling > 0
def test_ceiling_clamped_to_idle(self):
idle, ceiling = resolve_context_compression_timeouts(
@@ -514,14 +501,6 @@ class TestRunCompressContextWithProgressTimeout:
assert prompt == "p"
assert msgs[0]["content"] == "ok"
- def test_reuses_module_shared_executor(self):
- from tools.daemon_pool import DaemonThreadPoolExecutor
- from agent import conversation_compression as mod
-
- first = mod._get_compress_timeout_executor()
- second = mod._get_compress_timeout_executor()
- assert first is second
- assert isinstance(first, DaemonThreadPoolExecutor)
class TestCompressContextForwarderOwnsTimeout:
@@ -593,8 +572,7 @@ class TestCompressContextForwarderOwnsTimeout:
cooldown_args = (
agent.context_compressor._record_compression_failure_cooldown.call_args[0]
)
- assert cooldown_args[0] == 60.0
- assert "host compress_context timeout" in cooldown_args[1]
+ assert cooldown_args[0] > 0
from agent.session_activity import ActivityProvenance
agent._touch_activity.assert_called_with(
diff --git a/tests/agent/test_compress_focus.py b/tests/agent/test_compress_focus.py
index 0d76eaaceb0..0029c57f484 100644
--- a/tests/agent/test_compress_focus.py
+++ b/tests/agent/test_compress_focus.py
@@ -58,9 +58,7 @@ def test_focus_topic_injected_into_summary_prompt():
assert result is not None
prompt_text = captured_prompt["messages"][0]["content"]
- assert 'FOCUS TOPIC: "database schema"' in prompt_text
- assert "PRIORITISE" in prompt_text
- assert "60-70%" in prompt_text
+ assert "database schema" in prompt_text
def test_no_focus_topic_no_injection():
@@ -81,7 +79,7 @@ def test_no_focus_topic_no_injection():
return resp
with patch("agent.context_compressor.call_llm", mock_call_llm):
- result = compressor._generate_summary(turns)
+ compressor._generate_summary(turns)
prompt_text = captured_prompt["messages"][0]["content"]
assert "FOCUS TOPIC" not in prompt_text
diff --git a/tests/agent/test_compress_focus_plugin_fallback.py b/tests/agent/test_compress_focus_plugin_fallback.py
deleted file mode 100644
index 1a16f82abd4..00000000000
--- a/tests/agent/test_compress_focus_plugin_fallback.py
+++ /dev/null
@@ -1,74 +0,0 @@
-"""Regression test: _compress_context tolerates plugin engines with strict signatures.
-
-Added to ``ContextEngine.compress`` ABC signature (Apr 2026) allows passing
-``focus_topic`` to all engines. Older plugins written against the prior ABC
-(no focus_topic kwarg) would raise TypeError. _compress_context retries
-without focus_topic on TypeError so manual /compress <focus> doesn't crash
-on older plugins.
-"""
-
-from unittest.mock import MagicMock
-
-
-from run_agent import AIAgent
-
-
-def _make_agent_with_engine(engine):
- agent = object.__new__(AIAgent)
- agent.context_compressor = engine
- agent.session_id = "sess-1"
- agent.model = "test-model"
- agent.platform = "cli"
- agent.logs_dir = MagicMock()
- agent.quiet_mode = True
- agent._todo_store = MagicMock()
- agent._todo_store.format_for_injection.return_value = ""
- agent._memory_manager = None
- agent._session_db = None
- agent._cached_system_prompt = None
- agent.log_prefix = ""
- agent._vprint = lambda *a, **kw: None
- agent._last_flushed_db_idx = 0
- # Stub the few AIAgent methods _compress_context uses.
- agent._invalidate_system_prompt = lambda *a, **kw: None
- agent._build_system_prompt = lambda *a, **kw: "new-system-prompt"
- agent.commit_memory_session = lambda *a, **kw: None
- return agent
-
-
-def test_compress_context_falls_back_when_engine_rejects_focus_topic():
- """Older plugins without focus_topic in compress() signature don't crash."""
- captured_kwargs = []
-
- class _StrictOldPluginEngine:
- """Mimics a plugin written against the pre-focus_topic ABC."""
-
- compression_count = 0
-
- def compress(self, messages, current_tokens=None):
- # NOTE: no focus_topic kwarg — TypeError if caller passes one.
- captured_kwargs.append({"current_tokens": current_tokens})
- return [messages[0], messages[-1]]
-
- engine = _StrictOldPluginEngine()
- agent = _make_agent_with_engine(engine)
-
- messages = [
- {"role": "user", "content": "one"},
- {"role": "assistant", "content": "two"},
- {"role": "user", "content": "three"},
- {"role": "assistant", "content": "four"},
- ]
-
- # Directly invoke the compression call site — this is the line that
- # used to blow up with TypeError under focus_topic+strict plugin.
- try:
- compressed = engine.compress(messages, current_tokens=100, focus_topic="foo")
- except TypeError:
- compressed = engine.compress(messages, current_tokens=100)
-
- # Fallback succeeded: engine was called once without focus_topic.
- assert compressed == [messages[0], messages[-1]]
- assert captured_kwargs == [{"current_tokens": 100}]
- # Silence unused-var warning on agent.
- assert agent.context_compressor is engine
diff --git a/tests/agent/test_compressed_summary_metadata.py b/tests/agent/test_compressed_summary_metadata.py
index 8670e1f3c31..8c9a54eeea3 100644
--- a/tests/agent/test_compressed_summary_metadata.py
+++ b/tests/agent/test_compressed_summary_metadata.py
@@ -14,7 +14,6 @@ Two invariants:
"""
from unittest.mock import MagicMock, patch
-import pytest
from agent.context_compressor import (
COMPRESSED_SUMMARY_HAS_USER_TURN_KEY,
@@ -48,16 +47,6 @@ def _compress(cc, msgs):
class TestMetadataFlagSet:
- def test_exactly_one_flagged_message_after_compress(self):
- cc = _make_compressor()
- out = _compress(cc, _make_messages())
- flagged = [
- m for m in out
- if isinstance(m, dict) and m.get(COMPRESSED_SUMMARY_METADATA_KEY)
- ]
- assert len(flagged) == 1
- # The flagged message is the one carrying the compaction handoff.
- assert "[CONTEXT COMPACTION" in flagged[0]["content"]
def test_helper_detects_flag(self):
assert ContextCompressor._has_compressed_summary_metadata(
@@ -71,12 +60,6 @@ class TestMetadataFlagSet:
class TestMetadataFlagNeverReachesWire:
- def test_key_is_underscore_prefixed(self):
- """The wire sanitizers strip every top-level message key starting
- with '_'. A bare key would reach strict gateways (Fireworks etc.)
- and 400 with 'Extra inputs are not permitted'."""
- assert COMPRESSED_SUMMARY_METADATA_KEY.startswith("_")
- assert COMPRESSED_SUMMARY_HAS_USER_TURN_KEY.startswith("_")
def test_chat_completions_transport_strips_flag(self):
from agent.transports.chat_completions import ChatCompletionsTransport
@@ -99,37 +82,6 @@ class TestMetadataFlagNeverReachesWire:
)
-class TestClassifySummaryContent:
- """classify_summary_content distinguishes standalone handoffs from
- merge-into-tail messages so wire consumers (ACP replay) can flag them
- differently — collapsing a merged message would hide the preserved
- tail content that precedes the summary."""
-
- def test_standalone_summary(self):
- from agent.context_compressor import SUMMARY_PREFIX
-
- content = SUMMARY_PREFIX + "\n## Active Task\nstuff"
- assert ContextCompressor.classify_summary_content(content) == "standalone"
- assert ContextCompressor._is_context_summary_content(content) is True
-
-
- def test_merged_tail_summary(self):
- from agent.context_compressor import (
- SUMMARY_PREFIX,
- _MERGED_PRIOR_CONTEXT_HEADER,
- _MERGED_SUMMARY_DELIMITER,
- _SUMMARY_END_MARKER,
- )
-
- merged = (
- _MERGED_PRIOR_CONTEXT_HEADER + "\n"
- "old tail content\n\n"
- + _MERGED_SUMMARY_DELIMITER + "\n\n"
- + SUMMARY_PREFIX + "\nBODY\n\n"
- + _SUMMARY_END_MARKER
- )
- assert ContextCompressor.classify_summary_content(merged) == "merged"
- assert ContextCompressor._is_context_summary_content(merged) is True