The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py03 (499 removed)
teknium119f76d7498b7
diff --git a/tests/agent/test_in_place_compaction.py b/tests/agent/test_in_place_compaction.pyindex 93d8236151c..174d9f72414 100644--- a/tests/agent/test_in_place_compaction.py+++ b/tests/agent/test_in_place_compaction.py@@ -14,7 +14,6 @@ import tempfilefrom pathlib import Pathfrom unittest.mock import patch-import pytestdef _make_agent(session_db, session_id, *, in_place):@@ -207,44 +206,6 @@ class TestRotationFallbackWhenFlagOff:assert getattr(agent, "_last_compaction_in_place", False) is False-class TestInPlaceSignalForGateway:- """compress_context must expose a rotation-independent flag the gateway can- read (instead of an id-change diff) to re-baseline transcript handling."""-- def test_signal_set_on_in_place_unset_on_rotation(self):- from hermes_state import SessionDB- from agent.conversation_compression import compress_context-- with tempfile.TemporaryDirectory() as tmp:- db = SessionDB(db_path=Path(tmp) / "t.db")- # in-place → flag True- _seed(db, "s_ip", "ip")- a_ip = _make_agent(db, "s_ip", in_place=True)- compress_context(- a_ip, [{"role": "user", "content": "x"}] * 8,- approx_tokens=100_000, system_message="sys",- )- assert a_ip._last_compaction_in_place is True-- # rotation → flag False- _seed(db, "s_rot", "rot")- a_rot = _make_agent(db, "s_rot", in_place=False)- compress_context(- a_rot, [{"role": "user", "content": "x"}] * 8,- approx_tokens=100_000, system_message="sys",- )- assert a_rot._last_compaction_in_place is False---class TestInPlaceConfigDefault:- def test_flag_defaults_on(self):- """In-place is the default as of #38763 (rotation is now opt-out via- compression.in_place: false)."""- from hermes_cli.config import DEFAULT_CONFIG-- assert DEFAULT_CONFIG["compression"].get("in_place") is True--class TestInPlaceAntiGrowthGuard:"""A compression whose result is LARGER than its input must never bepersisted. In-place compaction commits inside compress_context() via@@ -349,32 +310,6 @@ class TestInPlaceAntiGrowthGuard:# only in-transcript todo re-injection) survives the salvage.assert any(m.get("_todo_snapshot_synthetic") for m in compressed)- def test_in_place_still_commits_shrinking_compression(self):- """The guard must not block legitimate compressions — a result SMALLER- than the input still commits in place (regression net for #83339)."""- from hermes_state import SessionDB- from agent.conversation_compression import compress_context-- with tempfile.TemporaryDirectory() as tmp:- db = SessionDB(db_path=Path(tmp) / "t.db")- sid = "20260619_shrink"- _seed(db, sid, "shrink")- agent = _make_agent(db, sid, in_place=True)- agent._last_flushed_db_idx = 5-- messages = [{"role": "user", "content": f"m{i}"} for i in range(8)]- compressed, _sp = compress_context(- agent, messages, approx_tokens=100_000, system_message="sys"- )-- # The fake compressor returns a small summary — commit happens.- assert agent._last_compaction_in_place is True- reloaded = db.get_messages_as_conversation(sid)- assert [m.get("content") for m in reloaded] == [- "[CONTEXT COMPACTION] summary of prior turns",- "recent reply",- ]-class TestCompactedTurnsStaySearchable:"""Teknium's review hinges on the pre-compaction transcript stayingdiff --git a/tests/agent/test_infinite_compaction_loop.py b/tests/agent/test_infinite_compaction_loop.pyindex 132c55a5d4a..f3745be8668 100644--- a/tests/agent/test_infinite_compaction_loop.py+++ b/tests/agent/test_infinite_compaction_loop.py@@ -15,11 +15,11 @@ The fix adds two safeguards:fires without burning anti-thrash strikes on transcript-shape facts."""-from unittest.mock import patch, MagicMock+from unittest.mock import patchimport time-from agent.context_compressor import ContextCompressor, _CHARS_PER_TOKEN+from agent.context_compressor import ContextCompressor# ---------------------------------------------------------------------------@@ -114,7 +114,6 @@ class TestCompressNoOpRegistersIneffective:)-# ---------------------------------------------------------------------------# Test: _find_tail_cut_by_tokens raw-budget fallback# ---------------------------------------------------------------------------@@ -144,32 +143,10 @@ class TestTailCutRawBudgetFallback:)--# ---------------------------------------------------------------------------# Test: Effective compression resets counter# ----------------------------------------------------------------------------class TestEffectiveCompressionResetsCounter:- """When compression actually saves tokens, the ineffective counter resets."""-- def test_effective_compression_resets_counter(self):- """After an effective compression, _ineffective_compression_count = 0."""- comp = _make_compressor(- summary_target_ratio=0.20,- config_context_length=96000,- )- messages = _build_session(30, words_per_turn=100)- comp._generate_summary = MagicMock(return_value="Compacted summary of earlier turns.")- comp.last_prompt_tokens = 73_000-- comp.compress(messages, current_tokens=73_000)-- assert comp._ineffective_compression_count == 0, (- f"Expected 0 ineffective compressions with effective compression, "- f"got {comp._ineffective_compression_count}"- )-# ---------------------------------------------------------------------------# Test: anti-thrashing in should_compress@@ -186,8 +163,6 @@ class TestAntiThrashing:assert not comp.should_compress(73_000)--# ---------------------------------------------------------------------------# Test: summary-LLM cooldown guard in should_compress (#11529)# ---------------------------------------------------------------------------@@ -207,8 +182,6 @@ class TestCooldownGuard:assert not comp.should_compress(73_000)--# ---------------------------------------------------------------------------# Test: #48621 — gpt-5.3-codex-spark short-session boundary#@@ -293,21 +266,3 @@ class TestPressureRealFloor:assert _pressure_with_real_floor(self._compressor(0), 10_000) == 10_000assert _pressure_with_real_floor(object(), 10_000) == 10_000- def test_anchored_pressure_is_never_floored(self):- """A valid usage anchor is provider-exact and wins as-is.-- On MoA turns the anchor deliberately uses the pre-fold aggregator- usage while ``last_real_prompt_tokens`` holds the folded figure;- flooring the anchored value would re-add the advisor fan-out tokens- the anchor exists to exclude. Pin the wiring shape: the floor is- applied only on the ``else`` (rough fallback) branch.- """- import inspect- from agent import turn_request_assembly-- src = inspect.getsource(turn_request_assembly.assemble_api_request)- i = src.index("if _anchored_pressure is not None:")- window = src[i : i + 400]- assert "request_pressure_tokens = _anchored_pressure" in window- assert "else:" in window- assert window.index("else:") < window.index("_pressure_with_real_floor(")diff --git a/tests/agent/test_injected_param_strip_retry_registry.py b/tests/agent/test_injected_param_strip_retry_registry.pyindex 867e8dd831f..2384c6f96a4 100644--- a/tests/agent/test_injected_param_strip_retry_registry.py+++ b/tests/agent/test_injected_param_strip_retry_registry.py@@ -131,20 +131,6 @@ class TestClassifierPathRegistryWalk:assert verdict.retryable is True, messageassert verdict.should_compress is False, message- @pytest.mark.parametrize("param", REGISTRY_PARAMS)- def test_turn_completes_via_retry(self, param):- """The full contract: 400 once naming the injected param, retry the- identical request, turn completes (#89503 — the turn used to die)."""- for msg_param in _error_shapes(param):- message, body = msg_param.values- transport = _FlakyTransport(- MockAPIError(message, status_code=400, body=copy.deepcopy(body))- )- result = _drive_conversation_retry(- transport, provider="openai-codex", model="gpt-5.6-sol",- )- assert result == {"ok": True}, message- assert transport.calls == 2, message@pytest.mark.parametrize("param", REGISTRY_PARAMS)def test_sender_route_still_fails_fast(self, param):diff --git a/tests/agent/test_insights.py b/tests/agent/test_insights.pyindex cecb348676f..1bfd2a3abc1 100644--- a/tests/agent/test_insights.py+++ b/tests/agent/test_insights.py@@ -1,6 +1,5 @@"""Tests for agent/insights.py — InsightsEngine analytics and reporting."""-import sqlite3import timeimport pytest@@ -140,10 +139,6 @@ def populated_db(db):class TestHasKnownPricing:- def test_known_commercial_model(self):- assert _has_known_pricing("gpt-4o", provider="openai") is True- assert _has_known_pricing("anthropic/claude-sonnet-4-20250514") is True- assert _has_known_pricing("gpt-4.1", provider="openai") is Truedef test_unknown_custom_model(self):assert _has_known_pricing("FP16_Hermes_4.5") is False@@ -158,20 +153,7 @@ class TestHasKnownPricing:class TestEstimateCost:- def test_basic_cost(self):- cost, status = _estimate_cost(- "anthropic/claude-sonnet-4-20250514",- 1_000_000,- 1_000_000,- provider="anthropic",- )- assert status == "estimated"- assert cost == pytest.approx(18.0, abs=0.01)- def test_zero_tokens(self):- cost, status = _estimate_cost("gpt-4o", 0, 0, provider="openai")- assert status == "estimated"- assert cost == 0.0def test_cache_aware_usage(self):cost, status = _estimate_cost(@@ -228,18 +210,11 @@ class TestInsightsEmpty:report = engine.generate(days=30)assert report["empty"] is Trueassert report["overview"] == {}+ # Both renderers must handle the empty report without crashing.+ assert engine.format_terminal(report)+ assert engine.format_gateway(report)- def test_empty_db_terminal_format(self, db):- engine = InsightsEngine(db)- report = engine.generate(days=30)- text = engine.format_terminal(report)- assert "No sessions found" in text- def test_empty_db_gateway_format(self, db):- engine = InsightsEngine(db)- report = engine.generate(days=30)- text = engine.format_gateway(report)- assert "No sessions found" in text# =========================================================================@@ -369,16 +344,6 @@ class TestInsightsPopulated:assert top_skill["last_used_at"] is not None- def test_activity_patterns(self, populated_db):- engine = InsightsEngine(populated_db)- report = engine.generate(days=30)- activity = report["activity"]-- assert len(activity["by_day"]) == 7- assert len(activity["by_hour"]) == 24- assert activity["active_days"] >= 1- assert activity["busiest_day"] is not None- assert activity["busiest_hour"] is not None@@ -453,21 +418,6 @@ class TestInsightsPopulated:]assert sorted(pinned) == sorted(unpinned), attr- def test_tool_and_skill_usage_invariant_to_partial_index(self, populated_db):- """The public tool/skill usage output is stable and exercises the- assistant tool_calls path for both scopes."""- engine = InsightsEngine(populated_db)- cutoff = 0.0-- tools = engine._get_tool_usage(cutoff)- tools_cli = engine._get_tool_usage(cutoff, source="cli")- skills = engine._get_skill_usage(cutoff)- skills_cli = engine._get_skill_usage(cutoff, source="cli")-- # Sanity: the fixture actually drives the assistant tool_calls path.- assert any(t["tool_name"] == "search_files" for t in tools)- assert any(t["tool_name"] == "search_files" for t in tools_cli)- assert isinstance(skills, list) and isinstance(skills_cli, list)def test_missing_index_falls_back_to_unpinned_queries(self, populated_db):"""INDEXED BY would be a hard error if the index is missing — which@@ -490,11 +440,6 @@ class TestInsightsPopulated:# And with the index present, the pin stays.assert "INDEXED BY" in InsightsEngine._GET_TOOL_CALLS_ALL- def test_get_skill_breakdown_matches_full_generate(self, populated_db):- engine = InsightsEngine(populated_db)- full = engine.generate(days=30)- focused = engine.get_usage_breakdown(days=30)["skills"]- assert focused == full["skills"]def test_get_usage_breakdown_matches_full_generate(self, populated_db):engine = InsightsEngine(populated_db)@@ -512,17 +457,6 @@ class TestInsightsPopulated:# github-code-review was in discord (s4), not cliassert "github-code-review" not in skill_names- def test_get_skill_breakdown_empty_db(self, db):- focused = InsightsEngine(db).get_usage_breakdown(days=30)["skills"]- assert focused == {- "summary": {- "total_skill_loads": 0,- "total_skill_edits": 0,- "total_skill_actions": 0,- "distinct_skills_used": 0,- },- "top_skills": [],- }def test_get_skill_usage_prefilter_ignores_non_skill_substring(self, db):# "my_skill_view_helper" contains "skill_view" as a substring; instr()@@ -546,18 +480,6 @@ class TestInsightsPopulated:# =========================================================================class TestTerminalFormatting:- def test_terminal_format_has_sections(self, populated_db):- engine = InsightsEngine(populated_db)- report = engine.generate(days=30)- text = engine.format_terminal(report)-- assert "Hermes Insights" in text- assert "Overview" in text- assert "Models Used" in text- assert "Top Tools" in text- assert "Top Skills" in text- assert "Activity Patterns" in text- assert "Notable Sessions" in text@@ -572,13 +494,10 @@ class TestTerminalFormatting:report = engine.generate(days=30)text = engine.format_terminal(report)- assert "N/A" not in text- assert "custom/self-hosted" not in text# Cost section surfaces unknown-cost sessions (#77223) instead of# hiding them — a custom model with no pricing data shows in the# Unknown bucket rather than silently reporting $0.assert "Unknown" in text- assert "no pricing data" in textclass TestGatewayFormatting:@@ -591,18 +510,6 @@ class TestGatewayFormatting:assert len(gateway_text) < len(terminal_text)- def test_gateway_format_hides_cache_details(self, populated_db):- """Gateway format omits internal cache details.-- Dollar figures now appear when there are estimated/included/unknown- cost buckets (#77223) — the old assertion that '$' is absent is no- longer correct because surfacing cost buckets is the fix.- """- engine = InsightsEngine(populated_db)- report = engine.generate(days=30)- text = engine.format_gateway(report)-- assert "cache" not in text.lower()@@ -628,21 +535,6 @@ class TestEdgeCases:assert models[0]["model"] == "unknown"assert models[0]["has_pricing"] is False- def test_custom_model_shows_zero_cost(self, db):- """Custom/self-hosted models should show $0 cost, not fake estimates."""- db.create_session(session_id="s1", source="cli", model="FP16_Hermes_4.5")- db.update_token_counts("s1", input_tokens=100000, output_tokens=50000)- db._conn.commit()-- engine = InsightsEngine(db)- report = engine.generate(days=30)- assert report["overview"]["estimated_cost"] == 0.0- assert "FP16_Hermes_4.5" in report["overview"]["models_without_pricing"]-- models = report["models"]- custom = next(m for m in models if m["model"] == "FP16_Hermes_4.5")- assert custom["cost"] == 0.0- assert custom["has_pricing"] is False@@ -720,7 +612,6 @@ class TestEdgeCases:# The cost section should appear with the buckets this DB has# (estimated + included; no unknown-cost session is created here)- assert "💰 Cost" in textassert "~$1.50" in text # estimatedassert "included" in text.lower()assert "subscription" in text.lower()@@ -749,45 +640,6 @@ class TestEdgeCases:assert "~$0.00 estimated" not in gateway_textassert "~$0.0046 estimated" in gateway_text- def test_cost_buckets_displayed_in_gateway_format(self, db):- """#77223: included/estimated/unknown cost buckets surface in gateway."""- db.create_session(session_id="est", source="cli", model="model-a")- db.update_token_counts(- "est", input_tokens=100, model="model-a",- billing_provider="custom",- estimated_cost_usd=2.25, actual_cost_usd=0.0,- cost_status="estimated", cost_source="provider", api_call_count=1,- )- db.create_session(session_id="inc", source="cli", model="gpt-5.4-mini")- db.update_token_counts(- "inc", input_tokens=200, model="gpt-5.4-mini",- billing_provider="openai-codex",- estimated_cost_usd=0.0, actual_cost_usd=0.0,- cost_status="included", cost_source="none", api_call_count=1,- )-- engine = InsightsEngine(db)- report = engine.generate(days=30)- text = engine.format_gateway(report)- assert "**Cost:**" in text- assert "~$2.25" in text- assert "included" in text.lower()-- def test_unknown_bucket_shown_for_costless_session(self, db):- """A session with no model still shows unknown cost bucket (#77223).-- The unknown bucket is surfaced so users can see they have sessions- with no pricing data, rather than silently reporting $0.- """- db.create_session(session_id="s1", source="cli", model="test")- db._conn.commit()-- engine = InsightsEngine(db)- report = engine.generate(days=30)- text = engine.format_terminal(report)- # The session has no cost data, so it falls in the "unknown" bucket.- assert "💰 Cost" in text- assert "Unknown" in textdiff --git a/tests/agent/test_interactive_interrupt.py b/tests/agent/test_interactive_interrupt.pydeleted file mode 100644index 970ebef6f59..00000000000--- a/tests/agent/test_interactive_interrupt.py+++ /dev/null@@ -1,201 +0,0 @@-#!/usr/bin/env python3-"""Interactive interrupt test that mimics the exact CLI flow.--Starts an agent in a thread with a mock delegate_task that takes a while,-then simulates the user typing a message via _interrupt_queue.--Logs every step to stderr (which isn't affected by redirect_stdout)-so we can see exactly where the interrupt gets lost.-"""--import logging-import queue-import sys-import threading-import time-import os--# Force stderr logging so redirect_stdout doesn't swallow it-logging.basicConfig(level=logging.DEBUG, stream=sys.stderr,- format="%(asctime)s [%(threadName)s] %(message)s")-log = logging.getLogger("interrupt_test")--sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from unittest.mock import MagicMock, patch-from agent.iteration_budget import IterationBudget-from run_agent import AIAgent-from tools.interrupt import set_interrupt--def make_slow_response(delay=2.0):- """API response that takes a while."""- def create(**kwargs):- log.info(f" 🌐 Mock API call starting (will take {delay}s)...")- time.sleep(delay)- log.info(" 🌐 Mock API call completed")- resp = MagicMock()- resp.choices = [MagicMock()]- resp.choices[0].message.content = "Done with the task"- resp.choices[0].message.tool_calls = None- resp.choices[0].message.refusal = None- resp.choices[0].finish_reason = "stop"- resp.usage.prompt_tokens = 100- resp.usage.completion_tokens = 10- resp.usage.total_tokens = 110- resp.usage.prompt_tokens_details = None- return resp- return create---def main() -> int:- set_interrupt(False)-- # ─── Create parent agent ───- parent = AIAgent.__new__(AIAgent)- parent._interrupt_requested = False- parent._interrupt_message = None- parent._active_children = []- parent._active_children_lock = threading.Lock()- parent.quiet_mode = True- parent.model = "test/model"- parent.base_url = "http://localhost:1"- parent.api_key = "test"- parent.provider = "test"- parent.api_mode = "chat_completions"- parent.platform = "cli"- parent.enabled_toolsets = ["terminal", "file"]- parent.providers_allowed = None- parent.providers_ignored = None- parent.providers_order = None- parent.provider_sort = None- parent.max_tokens = None- parent.reasoning_config = None- parent.prefill_messages = None- parent._session_db = None- parent._delegate_depth = 0- parent._delegate_spinner = None- parent.tool_progress_callback = None- parent.iteration_budget = IterationBudget(max_total=100)- parent._client_kwargs = {"api_key": "test", "base_url": "http://localhost:1"}-- # Monkey-patch parent.interrupt to log- _original_interrupt = AIAgent.interrupt-- def logged_interrupt(self, message=None):- log.info(f"🔴 parent.interrupt() called with: {message!r}")- log.info(f" _active_children count: {len(self._active_children)}")- _original_interrupt(self, message)- log.info(f" After interrupt: _interrupt_requested={self._interrupt_requested}")- for i, child in enumerate(self._active_children):- log.info(f" Child {i}._interrupt_requested={child._interrupt_requested}")-- parent.interrupt = lambda msg=None: logged_interrupt(parent, msg)-- # ─── Simulate the exact CLI flow ───- interrupt_queue = queue.Queue()- child_running = threading.Event()- agent_result = [None]-- def agent_thread_func():- """Simulates the agent_thread in cli.py's chat() method."""- log.info("🟢 agent_thread starting")-- with patch("agent.process_bootstrap.OpenAI") as MockOpenAI:- mock_client = MagicMock()- mock_client.chat.completions.create = make_slow_response(delay=3.0)- mock_client.close = MagicMock()- MockOpenAI.return_value = mock_client-- from tools.delegate_tool import _run_single_child-- # Signal that child is about to start- original_init = AIAgent.__init__-- def patched_init(self_agent, *a, **kw):- log.info("🟡 Child AIAgent.__init__ called")- original_init(self_agent, *a, **kw)- child_running.set()- log.info(- f"🟡 Child started, parent._active_children = {len(parent._active_children)}"- )-- with patch.object(AIAgent, "__init__", patched_init):- result = _run_single_child(- task_index=0,- goal="Do a slow thing",- context=None,- toolsets=["terminal"],- model="test/model",- max_iterations=3,- parent_agent=parent,- task_count=1,- override_provider="test",- override_base_url="http://localhost:1",- override_api_key="test",- override_api_mode="chat_completions",- )- agent_result[0] = result- log.info(f"🟢 agent_thread finished. Result status: {result.get('status')}")-- # ─── Start agent thread (like chat() does) ───- agent_thread = threading.Thread(target=agent_thread_func, name="agent_thread", daemon=True)- agent_thread.start()-- # ─── Wait for child to start ───- if not child_running.wait(timeout=10):- print("FAIL: Child never started", file=sys.stderr)- set_interrupt(False)- return 1-- # Give child time to enter its main loop and start API call- time.sleep(1.0)-- # ─── Simulate user typing a message (like handle_enter does) ───- log.info("📝 Simulating user typing 'Hey stop that'")- interrupt_queue.put("Hey stop that")-- # ─── Simulate chat() polling loop (like the real chat() method) ───- log.info("📡 Starting interrupt queue polling (like chat())")- interrupt_msg = None- poll_count = 0- while agent_thread.is_alive():- try:- interrupt_msg = interrupt_queue.get(timeout=0.1)- if interrupt_msg:- log.info(f"📨 Got interrupt message from queue: {interrupt_msg!r}")- log.info(" Calling parent.interrupt()...")- parent.interrupt(interrupt_msg)- log.info(" parent.interrupt() returned. Breaking poll loop.")- break- except queue.Empty:- poll_count += 1- if poll_count % 20 == 0: # Log every 2s- log.info(f" Still polling ({poll_count} iterations)...")-- # ─── Wait for agent to finish ───- log.info("⏳ Waiting for agent_thread to join...")- t0 = time.monotonic()- agent_thread.join(timeout=10)- elapsed = time.monotonic() - t0- log.info(f"✅ agent_thread joined after {elapsed:.2f}s")-- # ─── Check results ───- result = agent_result[0]- if result:- log.info(f"Result status: {result['status']}")- log.info(f"Result duration: {result['duration_seconds']}s")- if result["status"] == "interrupted" and elapsed < 2.0:- print("✅ PASS: Interrupt worked correctly!", file=sys.stderr)- set_interrupt(False)- return 0- print(f"❌ FAIL: status={result['status']}, elapsed={elapsed:.2f}s", file=sys.stderr)- set_interrupt(False)- return 1-- print("❌ FAIL: No result returned", file=sys.stderr)- set_interrupt(False)- return 1---if __name__ == "__main__":- sys.exit(main())diff --git a/tests/agent/test_interpreter_shutdown_turn_exit.py b/tests/agent/test_interpreter_shutdown_turn_exit.pyindex 75ffede76a5..3a68a12a018 100644--- a/tests/agent/test_interpreter_shutdown_turn_exit.py+++ b/tests/agent/test_interpreter_shutdown_turn_exit.py@@ -159,17 +159,7 @@ def test_non_quiet_mode_still_prints_error(monkeypatch, capsys):class TestSharedPredicate:- def test_matches_interpreter_variant(self):- from tools.interpreter_shutdown import interpreter_shutting_down-- exc = RuntimeError("cannot schedule new futures after interpreter shutdown")- assert interpreter_shutting_down(exc) is True-- def test_matches_plain_executor_variant(self):- from tools.interpreter_shutdown import interpreter_shutting_down- exc = RuntimeError("cannot schedule new futures after shutdown")- assert interpreter_shutting_down(exc) is Truedef test_ignores_unrelated_errors(self):from tools.interpreter_shutdown import interpreter_shutting_down@@ -177,18 +167,4 @@ class TestSharedPredicate:assert interpreter_shutting_down(RuntimeError("boom")) is Falseassert interpreter_shutting_down(None) is False- def test_cron_wrapper_delegates(self):- from cron.scheduler import _interpreter_shutting_down-- exc = RuntimeError("cannot schedule new futures after shutdown")- assert _interpreter_shutting_down(exc) is True- assert _interpreter_shutting_down(RuntimeError("boom")) is False-- def test_tool_executor_wrapper_delegates(self):- from agent.tool_executor import _is_interpreter_shutdown_submit_error- # The tool-executor predicate previously matched ONLY the fuller- # variant; via the shared home it now catches both.- exc = RuntimeError("cannot schedule new futures after shutdown")- assert _is_interpreter_shutdown_submit_error(exc) is True- assert _is_interpreter_shutdown_submit_error(RuntimeError("boom")) is Falsediff --git a/tests/agent/test_interrupt_compat.py b/tests/agent/test_interrupt_compat.pyindex 830c33a254e..2a40c2bd16d 100644--- a/tests/agent/test_interrupt_compat.py+++ b/tests/agent/test_interrupt_compat.py@@ -120,4 +120,6 @@ def test_tui_subagent_interrupt_is_an_explicit_hard_stop() -> None:with delegate_tool._active_subagents_lock:delegate_tool._active_subagents.pop(subagent_id, None)- assert agent.calls == [("hard", f"Interrupted via TUI ({subagent_id})", None)]+ assert len(agent.calls) == 1+ assert agent.calls[0][0] == "hard"+ assert subagent_id in agent.calls[0][1]diff --git a/tests/agent/test_interrupt_issuer_attribution.py b/tests/agent/test_interrupt_issuer_attribution.pyindex 8664fb24167..fa3a49fe038 100644--- a/tests/agent/test_interrupt_issuer_attribution.py+++ b/tests/agent/test_interrupt_issuer_attribution.py@@ -40,7 +40,7 @@ def test_system_producer_is_recorded_and_logged_at_publication(caplog):assert agent._interrupt_requested is Trueassert interrupt_issuer(agent) == "cron_inactivity_watchdog"published = [r.getMessage() for r in caplog.records if r.getMessage().startswith("Interrupt requested")]- assert published == ["Interrupt requested (hard): cron inactivity watchdog"]+ assert len(published) == 1 and "cron inactivity watchdog" in published[0]finally:set_interrupt(False)diff --git a/tests/agent/test_interrupt_propagation.py b/tests/agent/test_interrupt_propagation.pyindex ec5cc486153..88368c01b4e 100644--- a/tests/agent/test_interrupt_propagation.py+++ b/tests/agent/test_interrupt_propagation.py@@ -169,64 +169,6 @@ class TestInterruptPropagationToChild(unittest.TestCase):t.join(timeout=2)set_interrupt(False)- def test_concurrent_interrupt_propagation(self):- """Simulates exact CLI flow: parent runs delegate in thread, main thread interrupts."""- parent = self._make_bare_agent()- child = self._make_bare_agent()-- # Register child (simulating what _run_single_child does)- parent._active_children.append(child)-- # Simulate child running (checking flag in a loop)- child_detected = threading.Event()- def simulate_child_loop():- while not child._interrupt_requested:- time.sleep(0.05)- child_detected.set()-- child_thread = threading.Thread(target=simulate_child_loop, daemon=True)- child_thread.start()-- # Small delay, then interrupt from "main thread"- time.sleep(0.1)- parent.interrupt("user typed something new")-- # Child should detect within 200ms- detected = child_detected.wait(timeout=1.0)- assert detected, "Child never detected the interrupt!"- child_thread.join(timeout=1)- set_interrupt(False)-- def test_prestart_interrupt_binds_to_execution_thread(self):- """An interrupt that arrives before startup should bind to the agent thread."""- agent = self._make_bare_agent()- barrier = threading.Barrier(2)- result = {}-- agent.interrupt("stop before start")- assert agent._interrupt_requested is True- assert agent._interrupt_thread_signal_pending is True- assert is_interrupted() is False-- def run_thread():- from tools.interrupt import set_interrupt as _set_interrupt_for_test-- agent._execution_thread_id = threading.current_thread().ident- _set_interrupt_for_test(False, agent._execution_thread_id)- if agent._interrupt_requested:- _set_interrupt_for_test(True, agent._execution_thread_id)- agent._interrupt_thread_signal_pending = False- barrier.wait(timeout=5)- result["thread_interrupted"] = is_interrupted()-- t = threading.Thread(target=run_thread)- t.start()- barrier.wait(timeout=5)- t.join(timeout=2)-- assert result["thread_interrupted"] is True- assert agent._interrupt_thread_signal_pending is False-class TestPerThreadInterruptIsolation(unittest.TestCase):"""Verify that interrupting one agent does NOT affect another agent's thread.diff --git a/tests/agent/test_invalid_context_length_warning.py b/tests/agent/test_invalid_context_length_warning.pyindex 5fa6c7369fc..b3c3ca622da 100644--- a/tests/agent/test_invalid_context_length_warning.py+++ b/tests/agent/test_invalid_context_length_warning.py@@ -55,30 +55,5 @@ def test_string_k_suffix_context_length_warns():warning_calls = [c for c in mock_logger.warning.call_args_listif "Invalid" in str(c) and "256K" in str(c)]assert len(warning_calls) == 1- assert "plain integer" in str(warning_calls[0])-----def test_custom_providers_valid_context_length():- """Valid integer in custom_providers should work silently."""- custom_providers = [- {- "name": "LiteLLM",- "base_url": "http://localhost:4000/v1",- "models": {- "gpt5.4": {"context_length": 256000}- },- }- ]- with patch("run_agent.logger") as mock_logger:- agent = _build_agent(- {"default": "gpt5.4", "provider": "custom",- "base_url": "http://localhost:4000/v1"},- custom_providers=custom_providers,- model="gpt5.4",- )- for c in mock_logger.warning.call_args_list:- assert "Invalid" not in str(c)diff --git a/tests/agent/test_iron_proxy.py b/tests/agent/test_iron_proxy.pyindex 995c771f627..c0143ad09cf 100644--- a/tests/agent/test_iron_proxy.py+++ b/tests/agent/test_iron_proxy.py@@ -194,16 +194,6 @@ def test_load_mappings_handles_corrupt_json(hermes_home):-def _make_fake_tar(binary_name: str, payload: bytes = b"#!/bin/sh\necho ok\n") -> bytes:- """Build a tar.gz with one file at the root, named ``binary_name``."""-- buf = io.BytesIO()- with tarfile.open(fileobj=buf, mode="w:gz") as tf:- info = tarfile.TarInfo(name=binary_name)- info.size = len(payload)- info.mode = 0o755- tf.addfile(info, io.BytesIO(payload))- return buf.getvalue()@@ -599,15 +589,6 @@ def test_start_proxy_injects_management_key_env(hermes_home, monkeypatch):# ----------------------------------------------------------------------------def test_reset_for_tests_clears_version_cache_and_nonce():- """_reset_for_tests must clear _VERSION_CACHE and _proxy_nonce so- in-process callers don't see leakage between tests."""-- ip._VERSION_CACHE["dummy"] = "v0.0.0-fake"- ip._proxy_nonce = "fake-nonce-12345"- ip._reset_for_tests()- assert ip._VERSION_CACHE == {}- assert ip._proxy_nonce is None# ---------------------------------------------------------------------------diff --git a/tests/agent/test_iron_proxy_e2e.py b/tests/agent/test_iron_proxy_e2e.pydeleted file mode 100644index 37c3936c0da..00000000000--- a/tests/agent/test_iron_proxy_e2e.py+++ /dev/null@@ -1,368 +0,0 @@-"""End-to-end smoke test for the iron-proxy egress integration.--Spins up the REAL iron-proxy binary (auto-installed if not present), routes-a curl request through it against a local fake upstream, and verifies that-the Authorization header was swapped from a proxy token to a real secret.--Gated on the network. Skipped by default in CI unless the user explicitly-opts in with --run-e2e or HERMES_RUN_E2E=1. This is intentional — the test-downloads ~16MB and requires both `openssl` and `curl` to be present.-"""--from __future__ import annotations--import os-import socket-import subprocess-import threading-import time-from http.server import BaseHTTPRequestHandler, HTTPServer-from pathlib import Path-from typing import Optional--import pytest--from agent.proxy_sources import iron_proxy as ip---pytestmark = pytest.mark.skipif(- os.environ.get("HERMES_RUN_E2E", "0") != "1",- reason="E2E proxy test — set HERMES_RUN_E2E=1 to run (requires network + curl + openssl)",-)---def hermes_home(tmp_path, monkeypatch):- home = tmp_path / "hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- return home---def _free_port() -> int:- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:- s.bind(("127.0.0.1", 0))- return s.getsockname()[1]---class _CaptureHandler(BaseHTTPRequestHandler):- """Records the Authorization header of every incoming request."""-- captured_auth: Optional[str] = None # class-level so tests can read it-- def do_GET(self):- type(self).captured_auth = self.headers.get("Authorization")- body = b'{"ok": true}'- self.send_response(200)- self.send_header("Content-Type", "application/json")- self.send_header("Content-Length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def log_message(self, *args, **kwargs):- return # silence access log---def test_iron_proxy_swaps_authorization_header_end_to_end(hermes_home, monkeypatch):- """Real binary, real CA, real curl. Verify the proxy swaps a proxy-token- Authorization header for the real bearer value before forwarding."""-- if not __import__("shutil").which("curl"):- pytest.skip("curl not available")- if not __import__("shutil").which("openssl"):- pytest.skip("openssl not available")-- # ----- fake upstream ----------------------------------------------------- upstream_port = _free_port()- server = HTTPServer(("127.0.0.1", upstream_port), _CaptureHandler)- server_thread = threading.Thread(target=server.serve_forever, daemon=True)- server_thread.start()-- try:- # ----- iron-proxy install + CA + config ---------------------------- binary = ip.install_iron_proxy()- assert binary.exists()- ca_crt, ca_key = ip.ensure_ca_cert()- assert ca_crt.exists()-- real_secret = "sk-real-upstream-value-deadbeef"- monkeypatch.setenv("TEST_UPSTREAM_KEY", real_secret)- proxy_token = ip.mint_proxy_token("test")-- mapping = ip.TokenMapping(- proxy_token=proxy_token,- real_env_name="TEST_UPSTREAM_KEY",- upstream_hosts=("127.0.0.1",),- )-- tunnel_port = _free_port()- cfg = ip.build_proxy_config(- mappings=[mapping],- ca_cert=ca_crt,- ca_key=ca_key,- tunnel_port=tunnel_port,- allowed_hosts=["127.0.0.1"],- # Test target is on loopback — clear the default IMDS+loopback- # deny list so iron-proxy will dial 127.0.0.1.- upstream_deny_cidrs=[],- # Hermetic: pin the bind to loopback. Without this, Linux- # hosts with docker0 present would bind the bridge gateway- # (the production default) and the loopback curl below would- # never reach the proxy.- http_listen=[f"127.0.0.1:{tunnel_port}"],- )- ip.write_proxy_config(cfg)- ip.write_mappings([mapping])-- # ----- start the proxy --------------------------------------------- try:- status = ip.start_proxy()- except RuntimeError as exc:- pytest.skip(f"iron-proxy could not start in this environment: {exc}")- assert status.pid is not None-- # Wait up to 10s for the listener to come up.- for _ in range(50):- if ip._port_listening("127.0.0.1", tunnel_port):- break- time.sleep(0.2)- else:- pytest.fail("iron-proxy never started listening on the tunnel port")-- # ----- request through the proxy ----------------------------------- # The fake upstream listens on plain HTTP (not HTTPS). Plain-HTTP- # absolute-form forwards are served by the http_listen listener on- # tunnel_port + 1 (tunnel_port itself is the CONNECT/MITM listener- # that HTTPS_PROXY traffic hits). The secrets transform fires on- # the plain forward too, swapping the Authorization header.- result = subprocess.run(- [- "curl",- "--silent",- "--max-time", "10",- "-x", f"http://127.0.0.1:{tunnel_port + 1}",- "-H", f"Authorization: Bearer {proxy_token}",- f"http://127.0.0.1:{upstream_port}/",- ],- capture_output=True,- text=True,- )- assert result.returncode == 0, f"curl failed: {result.stderr}"- # Some iron-proxy versions return 200 with no body; only the swap matters.- captured = _CaptureHandler.captured_auth- assert captured is not None, "upstream never received the request"- assert real_secret in captured, (- f"Authorization header was not swapped — upstream saw: {captured!r}"- )- assert proxy_token not in captured, (- f"Proxy token leaked through to upstream: {captured!r}"- )-- finally:- # ----- cleanup ------------------------------------------------------- try:- ip.stop_proxy()- except Exception:- pass- server.shutdown()- server.server_close()---class _CaptureXApiKeyHandler(BaseHTTPRequestHandler):- """Records the x-api-key header of every incoming request."""-- captured_key: Optional[str] = None-- def do_GET(self):- type(self).captured_key = self.headers.get("x-api-key")- body = b'{"ok": true}'- self.send_response(200)- self.send_header("Content-Type", "application/json")- self.send_header("Content-Length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def log_message(self, *args, **kwargs):- return---def test_iron_proxy_swaps_x_api_key_header_end_to_end(hermes_home, monkeypatch):- """Header-auth providers: the secrets transform must swap the proxy- token out of a NON-Authorization header (x-api-key — the Anthropic- native scheme) on the pinned binary."""-- if not __import__("shutil").which("curl"):- pytest.skip("curl not available")- if not __import__("shutil").which("openssl"):- pytest.skip("openssl not available")-- upstream_port = _free_port()- server = HTTPServer(("127.0.0.1", upstream_port), _CaptureXApiKeyHandler)- threading.Thread(target=server.serve_forever, daemon=True).start()-- try:- binary = ip.install_iron_proxy()- assert binary.exists()- ca_crt, ca_key = ip.ensure_ca_cert()-- real_secret = "sk-ant-real-value-cafebabe"- monkeypatch.setenv("TEST_XAPI_KEY", real_secret)- proxy_token = ip.mint_proxy_token("anthropic")-- mapping = ip.TokenMapping(- proxy_token=proxy_token,- real_env_name="TEST_XAPI_KEY",- upstream_hosts=("127.0.0.1",),- match_headers=("x-api-key", "Authorization"),- )-- tunnel_port = _free_port()- cfg = ip.build_proxy_config(- mappings=[mapping],- ca_cert=ca_crt,- ca_key=ca_key,- tunnel_port=tunnel_port,- allowed_hosts=["127.0.0.1"],- upstream_deny_cidrs=[],- http_listen=[f"127.0.0.1:{tunnel_port}"],- )- ip.write_proxy_config(cfg)- ip.write_mappings([mapping])-- try:- status = ip.start_proxy()- except RuntimeError as exc:- pytest.skip(f"iron-proxy could not start in this environment: {exc}")- assert status.pid is not None-- for _ in range(50):- if ip._port_listening("127.0.0.1", tunnel_port):- break- time.sleep(0.2)- else:- pytest.fail("iron-proxy never started listening on the tunnel port")-- result = subprocess.run(- [- "curl",- "--silent",- "--max-time", "10",- "-x", f"http://127.0.0.1:{tunnel_port + 1}",- "-H", f"x-api-key: {proxy_token}",- f"http://127.0.0.1:{upstream_port}/",- ],- capture_output=True,- text=True,- )- assert result.returncode == 0, f"curl failed: {result.stderr}"- captured = _CaptureXApiKeyHandler.captured_key- assert captured is not None, "upstream never received the request"- assert real_secret in captured, (- f"x-api-key header was not swapped — upstream saw: {captured!r}"- )- assert proxy_token not in captured, (- f"Proxy token leaked through to upstream: {captured!r}"- )-- finally:- try:- ip.stop_proxy()- except Exception:- pass- server.shutdown()- server.server_close()---def test_iron_proxy_management_reload_end_to_end(hermes_home, monkeypatch):- """Real binary: the management listener comes up, an authenticated- POST /v1/reload succeeds after a config edit, and the edited ruleset- takes effect WITHOUT a restart (same pid)."""-- if not __import__("shutil").which("curl"):- pytest.skip("curl not available")- if not __import__("shutil").which("openssl"):- pytest.skip("openssl not available")-- upstream_port = _free_port()- server = HTTPServer(("127.0.0.1", upstream_port), _CaptureHandler)- threading.Thread(target=server.serve_forever, daemon=True).start()-- try:- binary = ip.install_iron_proxy()- assert binary.exists()- ca_crt, ca_key = ip.ensure_ca_cert()-- real_secret = "sk-real-reload-value-0badf00d"- monkeypatch.setenv("TEST_RELOAD_KEY", real_secret)- token_v1 = ip.mint_proxy_token("v1")-- def _write_cfg(mapping):- cfg = ip.build_proxy_config(- mappings=[mapping],- ca_cert=ca_crt,- ca_key=ca_key,- tunnel_port=tunnel_port,- allowed_hosts=["127.0.0.1"],- upstream_deny_cidrs=[],- http_listen=[f"127.0.0.1:{tunnel_port}"],- )- ip.write_proxy_config(cfg)- ip.write_mappings([mapping])-- tunnel_port = _free_port()- _write_cfg(ip.TokenMapping(- proxy_token=token_v1,- real_env_name="TEST_RELOAD_KEY",- upstream_hosts=("127.0.0.1",),- ))-- try:- status = ip.start_proxy()- except RuntimeError as exc:- pytest.skip(f"iron-proxy could not start in this environment: {exc}")- pid_before = status.pid- assert pid_before is not None-- for _ in range(50):- if ip._port_listening("127.0.0.1", tunnel_port):- break- time.sleep(0.2)- else:- pytest.fail("iron-proxy never started listening")-- # Rotate the sandbox-visible token in the config, then hot-reload.- token_v2 = ip.mint_proxy_token("v2")- _write_cfg(ip.TokenMapping(- proxy_token=token_v2,- real_env_name="TEST_RELOAD_KEY",- upstream_hosts=("127.0.0.1",),- ))- assert ip.reload_proxy() is True-- # Same daemon (no restart) ...- assert ip.get_status().pid == pid_before-- # ... but the NEW token now swaps.- _CaptureHandler.captured_auth = None- result = subprocess.run(- [- "curl", "--silent", "--max-time", "10",- "-x", f"http://127.0.0.1:{tunnel_port + 1}",- "-H", f"Authorization: Bearer {token_v2}",- f"http://127.0.0.1:{upstream_port}/",- ],- capture_output=True, text=True,- )- assert result.returncode == 0, f"curl failed: {result.stderr}"- captured = _CaptureHandler.captured_auth- assert captured is not None and real_secret in captured, (- f"post-reload token was not swapped — upstream saw: {captured!r}"- )-- finally:- try:- ip.stop_proxy()- except Exception:- pass- server.shutdown()- server.server_close()diff --git a/tests/agent/test_jsondecodeerror_retryable.py b/tests/agent/test_jsondecodeerror_retryable.pydeleted file mode 100644index a8ccb6f889c..00000000000--- a/tests/agent/test_jsondecodeerror_retryable.py+++ /dev/null@@ -1,99 +0,0 @@-"""Regression guard for #14782: json.JSONDecodeError must not be classified-as a local validation error by the main agent loop.--`json.JSONDecodeError` inherits from `ValueError`. The agent loop's-non-retryable classifier at run_agent.py treats `ValueError` / `TypeError`-as local programming bugs and skips retry. Without an explicit carve-out,-a transient provider hiccup (malformed response body, truncated stream,-routing-layer corruption) that surfaces as a JSONDecodeError would bypass-the retry path and fail the turn immediately.--This test mirrors the exact predicate shape used in run_agent.py so that-any future refactor of that predicate must preserve the invariant:-- JSONDecodeError → NOT local validation error (retryable)- UnicodeEncodeError → NOT local validation error (surrogate path)- bare ValueError → IS local validation error (programming bug)- bare TypeError → IS local validation error (programming bug)-"""-from __future__ import annotations--import json---def _mirror_agent_predicate(err: BaseException) -> bool:- """Exact shape of run_agent.py's is_local_validation_error check.-- Kept in lock-step with the source. If you change one, change both —- or, better, refactor the check into a shared helper and have both- sites import it.- """- import ssl-- return (- isinstance(err, (ValueError, TypeError))- and not isinstance(err, (UnicodeEncodeError, json.JSONDecodeError))- and not isinstance(err, ssl.SSLError)- # NoneType-is-not-iterable shape errors come from upstream SDK /- # provider response mismatches, not local programming bugs. See- # the agent/conversation_loop.py inline comment for #33136.- and not (- isinstance(err, TypeError)- and "nonetype" in str(err).lower()- and "not iterable" in str(err).lower()- )- )---class TestJSONDecodeErrorIsRetryable:-- def test_json_decode_error_is_not_local_validation(self):- """Provider returning malformed JSON surfaces as JSONDecodeError —- must be treated as transient so the retry path runs."""- try:- json.loads("{not valid json")- except json.JSONDecodeError as exc:- assert not _mirror_agent_predicate(exc), (- "json.JSONDecodeError must be excluded from the "- "ValueError/TypeError local-validation classification."- )- else:- raise AssertionError("json.loads should have raised")--- def test_bare_value_error_is_local_validation(self):- """Programming bugs that raise bare ValueError must still be- classified as local validation errors (non-retryable)."""- assert _mirror_agent_predicate(ValueError("bad arg"))-------class TestNoneTypeNotIterableIsRetryable:- """Regression for #33136 / closes lingering Telegram \"Non-retryable error (HTTP None)\".-- The chatgpt.com Codex backend (and any other upstream SDK / provider shim)- can surface ``TypeError: 'NoneType' object is not iterable`` as a wire-shape- mismatch, not a local programming bug. Even after #33042 made our own- consumer immune, third-party paths and mocked clients can still produce- this shape. The classifier should treat it as retryable so the normal- retry/fallback chain runs.- """-- def test_nonetype_not_iterable_is_retryable(self):- err = TypeError("'NoneType' object is not iterable")- assert not _mirror_agent_predicate(err), (- "TypeError('NoneType ... not iterable') must be excluded from "- "is_local_validation_error — it is a provider/SDK shape mismatch, "- "not a local bug. See #33136."- )--- def test_unrelated_type_error_remains_local_validation(self):- """TypeError without the NoneType-not-iterable pattern still aborts (programming bug)."""- assert _mirror_agent_predicate(TypeError("tools must be a list"))- assert _mirror_agent_predicate(TypeError("expected str, got int"))--diff --git a/tests/agent/test_kanban_budget_checkpoint.py b/tests/agent/test_kanban_budget_checkpoint.pyindex 6d3bae69a09..58e4de61893 100644--- a/tests/agent/test_kanban_budget_checkpoint.py+++ b/tests/agent/test_kanban_budget_checkpoint.py@@ -7,7 +7,7 @@ from tests.agent.test_iteration_budget_warning import _agent@pytest.mark.parametrize("ratio,scope,expected,kanban_notice", [- *[(ratio, "ordinary", False, False) for ratio in ("null", "true", "0", "1", ".nan", "junk")],+ *[(ratio, "ordinary", False, False) for ratio in ("null", "0", "junk")],("0.75", "ordinary", True, False),("null", "owner", True, True),("null", "non-owner", False, False),diff --git a/tests/agent/test_kanban_stop.py b/tests/agent/test_kanban_stop.pyindex a1c93cc50ea..6b1cc9fe223 100644--- a/tests/agent/test_kanban_stop.py+++ b/tests/agent/test_kanban_stop.py@@ -18,10 +18,6 @@ def clear_kanban_env(monkeypatch):return monkeypatch----def test_env_can_disable(clear_kanban_env):clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_abc")clear_kanban_env.setenv("HERMES_KANBAN_STOP_NUDGE", "0")@@ -75,7 +71,6 @@ def test_nudge_when_no_terminal_tool(clear_kanban_env):assert "kanban_complete" in nudgeassert "kanban_block" in nudgeassert "t_46be8aa5" in nudge- assert "protocol violation" in nudge.lower() or "protocol" in nudge.lower()def test_no_nudge_after_kanban_complete(clear_kanban_env):@@ -98,10 +93,6 @@ def test_no_nudge_after_kanban_complete(clear_kanban_env):assert build_kanban_stop_nudge(messages=messages) is None----# ── Integration: agent nudge + dispatcher bounded retry ──────────────# These tests verify the two layers compose correctly: the agent-side# nudge fires first (up to 2 attempts), and if the worker still exits@@ -110,10 +101,6 @@ def test_no_nudge_after_kanban_complete(clear_kanban_env):# for the dispatcher-side streak tests.----@pytest.mark.parametrize("tool_name,who",[diff --git a/tests/agent/test_last_reasoning_per_turn.py b/tests/agent/test_last_reasoning_per_turn.pydeleted file mode 100644index 3365e9ed49b..00000000000--- a/tests/agent/test_last_reasoning_per_turn.py+++ /dev/null@@ -1,43 +0,0 @@-"""Tests for per-turn reasoning extraction in AIAgent.run_conversation.--Verifies the reasoning field returned to display layers (CLI reasoning box,-gateway reasoning footer, TUI reasoning event) only reflects the CURRENT-turn's reasoning — never leaks from a prior turn — and is picked up-correctly when reasoning is attached to a tool-calling assistant step-rather than the final-answer assistant step.-"""-from __future__ import annotations---def _extract_last_reasoning(messages):- """Replica of the extraction loop in run_agent.py (~line 13867).-- Tests pin the loop's behaviour so that refactors can't silently- regress the per-turn semantic.- """- last_reasoning = None- for msg in reversed(messages):- if msg.get("role") == "user":- break- if msg.get("role") == "assistant" and msg.get("reasoning"):- last_reasoning = msg["reasoning"]- break- return last_reasoning---def test_simple_turn_reasoning_present():- messages = [- {"role": "user", "content": "hello"},- {"role": "assistant", "content": "hi", "reasoning": "greeting the user"},- ]- assert _extract_last_reasoning(messages) == "greeting the user"----------diff --git a/tests/agent/test_lean_single_aux_call.py b/tests/agent/test_lean_single_aux_call.pyindex 02ec5d6553a..5fa5081b024 100644--- a/tests/agent/test_lean_single_aux_call.py+++ b/tests/agent/test_lean_single_aux_call.py@@ -103,18 +103,6 @@ class TestLeanSingleAuxiliaryCall:summary = c._generate_summary(turns)assert _LEAN_SESSION_LOG_HEADING in summary- def test_prompt_requests_session_log_section(self):- c = _mk_compressor()- turns = _big_region(n_rounds=5)- with patch(- "agent.context_compressor.call_llm",- return_value=_llm_response(SUMMARY_BODY),- ) as mock_call:- c._generate_summary(turns)- prompt = mock_call.call_args.kwargs["messages"][0]["content"]- assert _LEAN_SESSION_LOG_HEADING in prompt- # The digest HARD RULES carried over into the single request.- assert "PRESERVE EXACTLY" in promptdef test_anchor_index_and_recovery_footer_present(self):c = _mk_compressor()diff --git a/tests/agent/test_learn_prompt.py b/tests/agent/test_learn_prompt.pyindex 4308e0beadf..0720baa838d 100644--- a/tests/agent/test_learn_prompt.py+++ b/tests/agent/test_learn_prompt.py@@ -6,12 +6,7 @@ builds a standards-guided prompt that the live agent runs as a normal turn, sothese are the load-bearing behavior contracts."""-from agent.learn_prompt import (- build_learn_prompt,- _AUTHORING_STANDARDS,- _KNOWLEDGE_SKILL_STANDARDS,- _SOURCE_HYGIENE,-)+from agent.learn_prompt import build_learn_promptclass TestBuildLearnPrompt:@@ -21,104 +16,10 @@ class TestBuildLearnPrompt:assert req in prompt--- def test_separates_sources_from_requirements(self):- # The reported bug (@GrenFX, Jun 2026): when a request leads with a- # path/URL, the agent fetched it and ignored the trailing prose. The- # prompt must tell the agent the request can MIX sources and- # requirements, and that prose after a source is authoring guidance to- # honor — not noise to drop.- prompt = build_learn_prompt(- "https://api.example.com/docs focus on the auth flow, skip deprecated bits"- )- low = prompt.lower()- # Carries the whole request verbatim (no truncation at the URL).- assert "focus on the auth flow, skip deprecated bits" in prompt- # Explicitly distinguishes sources from requirements.- assert "requirement" in low- # Names the failure mode it's guarding against.- assert "never fetch the first source" in low----- def test_teaches_the_full_hardline_standards(self):- # description length — otherwise distilled skills miss platform gating,- # author credit, and the tool-framing table. Lock the coverage in.- std = _AUTHORING_STANDARDS.lower()- # #1 description: the count-and-trim self-check (the reported bug).- assert "count" in std and "60" in std- # #3 platforms gating against OS-bound primitives.- assert "platforms" in std- # author is always the literal Hermes, never the host/OS identity (#52368).- assert "author: always the literal value `hermes`" in std- assert "never fill it from the host" in std- # #2 Hermes-tool framing names the wrapped tools, not shell utilities.- for tool in ("read_file", "search_files", "patch", "write_file"):- assert tool in std- # #6 scripts/references/templates layout.- assert "scripts/" in _AUTHORING_STANDARDS-- def test_teaches_the_knowledge_base_layout(self):- # Expansive sources (books, paper stacks, specs) must produce a lean- # SKILL.md index plus per-chapter references/ files loaded on demand —- # not one crammed file or a lossy summary. Ported from the- # book-to-skill layout (Aug 2026).- kb = _KNOWLEDGE_SKILL_STANDARDS.lower()- assert "references/" in _KNOWLEDGE_SKILL_STANDARDS- # On-demand loading goes through skill_view with a file_path.- assert "skill_view" in _KNOWLEDGE_SKILL_STANDARDS- # Structure, not summary — the load-bearing distillation rule.- assert "structure" in kb and "summary" in kb- # Copyright/quality line: synthesized notes, no verbatim reproduction.- assert "never reproduce" in kb- # Extend an existing skill rather than minting a near-duplicate.- assert "fold-in" in kb- # Large inputs must be persisted incrementally instead of overflowing- # the live conversation context before any reference file is written.- assert "one chapter or topic at a time" in kb- assert "never load an entire large corpus" in kb- assert "reconcile the skill.md index" in kb-- def test_prompt_embeds_all_three_standards_blocks(self):- prompt = build_learn_prompt("~/books/ddia.pdf")- assert _AUTHORING_STANDARDS in prompt- assert _KNOWLEDGE_SKILL_STANDARDS in prompt- assert _SOURCE_HYGIENE in prompt- # The shape decision is explicit: small source -> one file, large- # prose source -> knowledge-base layout.- assert "Pick the shape by the source" in prompt- assert "process it incrementally in step 2b" in prompt-- def test_source_hygiene_covers_invisible_unicode(self):- # Extracted document text is an injection vector (Trojan Source /- # invisible code points). The prompt must pin source text as data and- # name the invisible/bidi character classes to drop.- hyg = _SOURCE_HYGIENE.lower()- assert "data, not instructions" in hyg- assert "zero-width" in hyg- assert "bidi" in hyg or "bidirectional" in hyg-- def test_existing_skill_is_extended_instead_of_created_again(self):- prompt = build_learn_prompt("add these notes to my distributed-systems skill")- assert "First check the available skills" in prompt- assert "If one exists, load it with `skill_view`" in prompt- assert "Only when no matching skill exists" in prompt- assert 'action="create"' in prompt--class TestLearnRegistryWiring:- def test_learn_is_registered_and_resolves(self):- from hermes_cli.commands import resolve_command-- cmd = resolve_command("learn")- assert cmd is not None- assert cmd.name == "learn"---def test_learn_is_not_cli_only(self):from hermes_cli.commands import resolve_command- assert not resolve_command("learn").cli_only+ cmd = resolve_command("learn")+ assert cmd is not None and cmd.name == "learn"+ assert not cmd.cli_onlydiff --git a/tests/agent/test_length_continuation_thinking_exhaustion.py b/tests/agent/test_length_continuation_thinking_exhaustion.pyindex 63982fd2949..2c987b35739 100644--- a/tests/agent/test_length_continuation_thinking_exhaustion.py+++ b/tests/agent/test_length_continuation_thinking_exhaustion.py@@ -201,24 +201,6 @@ class TestThinkingOnlyTruncation:"continuation call.")- def test_thinking_only_truncation_sets_reasoning_off(self, loop_agent):- from tests.agent.test_run_agent import _mock_response-- loop_agent.client.chat.completions.create.side_effect = [- _thinking_only_length_response(),- _mock_response(- content="done", finish_reason=FINISH_REASON_LENGTH- ),- _full_response("finally complete."),- ]- _run(loop_agent, "write me a long report")-- calls = loop_agent.client.chat.completions.create.call_args_list- assert len(calls) == 3- # The thinking-only fragment set the flag; it was consumed by the- # next call, and the SECOND truncated fragment (which had visible- # text) does not set it again — so the third call sees thinking ON.- assert loop_agent._ephemeral_reasoning_off is Falsedef test_full_ceiling_with_empty_fragments_still_settles(self, loop_agent):"""All four attempts thinking-only: the turn must exit through the@@ -231,12 +213,10 @@ class TestThinkingOnlyTruncation:assert result["completed"] is Falseassert result["partial"] is True- assert "truncated after 4 continuation attempts" in (result.get("error") or "")assert result["final_response"], ("An all-empty ceiling exit must still surface a user-facing ""message instead of an invisible None.")- assert "reasoning" in (result["final_response"] or "").lower()assert _no_empty_assistant_rows(result["messages"]) == []assert loop_agent._ephemeral_reasoning_off is False, ("The ceiling exit must clear the pending one-shot override so the "diff --git a/tests/agent/test_local_stream_timeout.py b/tests/agent/test_local_stream_timeout.pyindex 78efcce9c5a..d40471239c6 100644--- a/tests/agent/test_local_stream_timeout.py+++ b/tests/agent/test_local_stream_timeout.py@@ -6,59 +6,11 @@ default 60s to HERMES_API_TIMEOUT (1800s) to avoid premature connectionkills during long prefill phases."""-import osimport pytest-from unittest.mock import patchfrom agent.model_metadata import is_local_endpoint-class TestLocalStreamReadTimeout:- """Verify stream read timeout auto-detection logic."""-- @pytest.mark.parametrize("base_url", [- "http://localhost:11434",- "http://127.0.0.1:8080",- "http://0.0.0.0:5000",- "http://192.168.1.100:8000",- "http://10.0.0.5:1234",- "http://host.docker.internal:11434",- "http://host.containers.internal:11434",- "http://host.lima.internal:11434",- ])- def test_local_endpoint_bumps_read_timeout(self, base_url):- """Local endpoint + default timeout -> bumps to base_timeout."""- with patch.dict(os.environ, {}, clear=False):- os.environ.pop("HERMES_STREAM_READ_TIMEOUT", None)- _base_timeout = float(os.getenv("HERMES_API_TIMEOUT", 1800.0))- _stream_read_timeout = float(os.getenv("HERMES_STREAM_READ_TIMEOUT", 120.0))- if _stream_read_timeout == 120.0 and base_url and is_local_endpoint(base_url):- _stream_read_timeout = _base_timeout- assert _stream_read_timeout == 1800.0-- def test_user_override_respected_for_local(self):- """User sets HERMES_STREAM_READ_TIMEOUT -> keep their value even for local."""- with patch.dict(os.environ, {"HERMES_STREAM_READ_TIMEOUT": "300"}, clear=False):- _base_timeout = float(os.getenv("HERMES_API_TIMEOUT", 1800.0))- _stream_read_timeout = float(os.getenv("HERMES_STREAM_READ_TIMEOUT", 120.0))- base_url = "http://localhost:11434"- if _stream_read_timeout == 120.0 and base_url and is_local_endpoint(base_url):- _stream_read_timeout = _base_timeout- assert _stream_read_timeout == 300.0--- def test_empty_base_url_keeps_default(self):- """No base_url set -> keep 120s default."""- with patch.dict(os.environ, {}, clear=False):- os.environ.pop("HERMES_STREAM_READ_TIMEOUT", None)- _base_timeout = float(os.getenv("HERMES_API_TIMEOUT", 1800.0))- _stream_read_timeout = float(os.getenv("HERMES_STREAM_READ_TIMEOUT", 120.0))- base_url = ""- if _stream_read_timeout == 120.0 and base_url and is_local_endpoint(base_url):- _stream_read_timeout = _base_timeout- assert _stream_read_timeout == 120.0--class TestIsLocalEndpoint:"""Direct unit tests for is_local_endpoint."""@@ -70,12 +22,14 @@ class TestIsLocalEndpoint:"http://192.168.1.100:8000","http://10.0.0.5:1234","http://172.17.0.1:11434",+ "http://host.docker.internal:11434",+ "http://host.containers.internal:11434",+ "http://host.lima.internal:11434",])def test_classic_local_addresses(self, url):assert is_local_endpoint(url) is True-@pytest.mark.parametrize("url", ["https://api.openai.com","https://openrouter.ai/api",diff --git a/tests/agent/test_lock_fallback_base_semantics.py b/tests/agent/test_lock_fallback_base_semantics.pyindex 5297e6f9bb8..cfd8954b6ad 100644--- a/tests/agent/test_lock_fallback_base_semantics.py+++ b/tests/agent/test_lock_fallback_base_semantics.py@@ -1,12 +1,4 @@-"""Pin BASE (main) semantics at the lock-fallback sites and the ``_is_openai_client_closed`` truth table.--Review-fix for the simplify-codebase PR: the refactor briefly rewrote several ``lock = getattr(agent,-"_x_lock", None); if lock is not None: with lock: <direct attr read>`` blocks as ``with getattr(...) or-nullcontext(): getattr(agent, slot, None)``, which (a) silently runs the critical section unlocked and (b)-turns a missing slot under the lock from a loud AttributeError into a silent None. These tests hold the-original shape: an initialized agent (lock present) reads its slots directly and fails loud; only-``object.__new__`` stubs (no lock) get the getattr fallback.-"""+"""Steer requeue/drain semantics and the ``_is_openai_client_closed`` truth table."""from __future__ import annotationsimport threading@@ -17,23 +9,6 @@ import pytestfrom agent.agent_runtime_helpers import _requeue_pending_steerfrom agent.client_lifecycle import ClientLifecycleMixinfrom agent.interrupt_control import InterruptControlMixin-from agent.session_persistence import SessionPersistenceMixin-from agent.stream_delivery import StreamDeliveryMixin-from gateway.run_agent_cache import GatewayAgentCacheMixin-from gateway.slash_commands import GatewaySlashCommandsMixin---class _RecLock:- def __init__(self):- self.entered = 0- self._lock = threading.Lock()-- def __enter__(self):- self.entered += 1- return self._lock.__enter__()-- def __exit__(self, *exc):- return self._lock.__exit__(*exc)class _Bare:@@ -43,51 +18,17 @@ class _Bare:# ---------------------------------------------------------------- steer requeue-def test_requeue_pending_steer_locked_path_reads_slot_directly_and_fails_loud():+def test_requeue_pending_steer_appends_to_existing_steer():agent = _Bare()- agent._pending_steer_lock = _RecLock()- with pytest.raises(AttributeError):- _requeue_pending_steer(agent, "new") # lock present but slot missing => real bug, loud+ agent._pending_steer_lock = threading.Lock()agent._pending_steer = "old"_requeue_pending_steer(agent, "new")assert agent._pending_steer == "old\nnew"- assert agent._pending_steer_lock.entered >= 1---def test_requeue_pending_steer_unlocked_stub_fallback():- agent = _Bare() # object.__new__-style stub: no lock, no slot- _requeue_pending_steer(agent, "new")- assert agent._pending_steer == "new"# ------------------------------------------------------- interrupt_control slots- "method, lock_attr, slot",- [- ("steer", "_pending_steer_lock", "_pending_steer"),- ("_drain_pending_steer", "_pending_steer_lock", "_pending_steer"),- ("_has_pending_redirect", "_pending_redirect_lock", "_pending_redirect"),- ("_drain_pending_redirect", "_pending_redirect_lock", "_pending_redirect"),- ],-)-def test_interrupt_control_slot_reads_fail_loud_only_under_lock(method, lock_attr, slot):- fn = getattr(InterruptControlMixin, method)- call = (lambda a: fn(a, "new")) if method == "steer" else fn-- locked = _Bare()- setattr(locked, lock_attr, threading.Lock())- with pytest.raises(AttributeError):- call(locked)-- unlocked = _Bare()- call(unlocked) # no lock: stub fallback, no raise-- setattr(locked, slot, "old")- call(locked) # slot present: normal path--def test_steer_and_drain_roundtrip_with_lock():agent = _Bare()agent._pending_steer_lock = threading.Lock()@@ -98,77 +39,6 @@ def test_steer_and_drain_roundtrip_with_lock():assert agent._pending_steer is None-# ---------------------------------------------------------- session persistence---def test_flush_messages_uses_lock_when_present_and_runs_unlocked_for_stubs():- class P(_Bare):- def _flush_messages_to_session_db_unlocked(self, messages, conversation_history=None):- return ("called", len(messages))-- locked = P()- locked._session_persist_lock = _RecLock()- assert SessionPersistenceMixin._flush_messages_to_session_db(locked, [{"role": "user"}]) == ("called", 1)- assert locked._session_persist_lock.entered == 1-- stub = P()- assert SessionPersistenceMixin._flush_messages_to_session_db(stub, [{"role": "user"}]) == ("called", 1)---# ---------------------------------------------------------------- stream writer---def test_stream_writer_lock_is_created_unconditionally_at_init():- from agent.agent_init import _STREAM_STATE-- assert _STREAM_STATE["_stream_writer_lock"] is threading.Lock- # The lazy path is only for __new__-built stubs and never replaces an existing lock.- agent = StreamDeliveryMixin.__new__(StreamDeliveryMixin)- agent._stream_writer_lock = existing = threading.Lock()- StreamDeliveryMixin._ensure_stream_writer_state(agent)- assert agent._stream_writer_lock is existing---# ------------------------------------------------------- gateway agent-cache sites---class _Runner(_Bare):- def _peek_session_state(self, key):- return None-- def _running_agent_ids(self):- return set()-- def _spawn_release_thread(self, *a, **k):- pass-- def _release_evicted_agent_soft(self, *a):- pass---def test_cached_agent_for_reads_only_under_lock():- runner = _Runner()- runner._agent_cache = {"k": ("AGENT", "sig")}- assert GatewaySlashCommandsMixin._cached_agent_for(runner, "k") is None # no lock: no unlocked read- runner._agent_cache_lock = _RecLock()- assert GatewaySlashCommandsMixin._cached_agent_for(runner, "k") == "AGENT"- assert runner._agent_cache_lock.entered == 1---def test_evict_cached_agent_reads_cache_directly_when_locked():- runner = _Runner()- runner._agent_cache_lock = threading.Lock()- with pytest.raises(AttributeError):- GatewayAgentCacheMixin._evict_cached_agent(runner, "k") # lock present, cache missing => loud- runner._agent_cache = {"k": ("AGENT", "sig")}- GatewayAgentCacheMixin._evict_cached_agent(runner, "k")- assert runner._agent_cache == {}- stub = _Runner()- stub._agent_cache = {"k": ("AGENT", "sig")}- GatewayAgentCacheMixin._evict_cached_agent(stub, "k") # lock-less test runner: evicts lock-free- assert stub._agent_cache == {}--# ------------------------------------------------------ _is_openai_client_closed@@ -208,12 +78,3 @@ def _duck(outer=None, inner=None, *, has_outer=True, has_inner=True):)def test_is_openai_client_closed_truth_table(client, expected):assert ClientLifecycleMixin._is_openai_client_closed(client) is expected---def test_cached_agent_for_lockless_fallback_only_when_requested():- # Manual codex /compress historically read the cache lock-free when the lock was absent.- runner = _Runner()- runner._agent_cache = {"k": ("AGENT", "sig")}- runner._agent_cache_lock = None- assert GatewaySlashCommandsMixin._cached_agent_for(runner, "k") is None- assert GatewaySlashCommandsMixin._cached_agent_for(runner, "k", lockless_fallback=True) == "AGENT"diff --git a/tests/agent/test_long_context_tier_429.py b/tests/agent/test_long_context_tier_429.pydeleted file mode 100644index 7909fc4de5d..00000000000--- a/tests/agent/test_long_context_tier_429.py+++ /dev/null@@ -1,126 +0,0 @@-"""Tests for Anthropic Sonnet long-context tier 429 handling.--When Claude Max users without "extra usage" hit the 1M context tier-on Sonnet, Anthropic returns HTTP 429 "Extra usage is required for long-context requests." This is NOT a transient rate limit — the agent should-reduce context_length to 200k and compress instead of retrying.--Only Sonnet is affected — Opus 1M is general access.-"""--from types import SimpleNamespace---# ----------------------------------------------------------------------------# Detection logic-# ------------------------------------------------------------------------------class TestLongContextTierDetection:- """Verify the detection heuristic matches the Anthropic error."""-- @staticmethod- def _is_long_context_tier_error(status_code, error_msg, model="claude-sonnet-4.6"):- error_msg = error_msg.lower()- return (- status_code == 429- and "extra usage" in error_msg- and "long context" in error_msg- and "sonnet" in model.lower()- )-- def test_matches_anthropic_error(self):- assert self._is_long_context_tier_error(- 429,- "Extra usage is required for long context requests.",- )--------- def test_rejects_partial_match(self):- """Both 'extra usage' AND 'long context' must be present."""- assert not self._is_long_context_tier_error(- 429, "extra usage required"- )- assert not self._is_long_context_tier_error(- 429, "long context requests not supported"- )---# ----------------------------------------------------------------------------# Context reduction-# ------------------------------------------------------------------------------class TestContextReduction:- """When the long-context tier error fires, context_length should- drop to 200k and the reduced flag should be set correctly."""-- def _make_compressor(self, context_length=1_000_000, threshold_percent=0.5):- c = SimpleNamespace(- context_length=context_length,- threshold_percent=threshold_percent,- threshold_tokens=int(context_length * threshold_percent),- _context_probed=False,- _context_probe_persistable=False,- )- return c-- def test_reduces_1m_to_200k(self):- comp = self._make_compressor(1_000_000)- reduced_ctx = 200_000-- if comp.context_length > reduced_ctx:- comp.context_length = reduced_ctx- comp.threshold_tokens = int(reduced_ctx * comp.threshold_percent)- comp._context_probed = True- comp._context_probe_persistable = False-- assert comp.context_length == 200_000- assert comp.threshold_tokens == 100_000- assert comp._context_probed is True- # Must NOT persist — subscription tier, not model capability- assert comp._context_probe_persistable is False-- def test_no_reduction_when_already_200k(self):- comp = self._make_compressor(200_000)- reduced_ctx = 200_000-- original = comp.context_length- if comp.context_length > reduced_ctx:- comp.context_length = reduced_ctx-- assert comp.context_length == original # unchanged----# ----------------------------------------------------------------------------# Integration: agent error handler path-# ------------------------------------------------------------------------------class TestAgentErrorPath:- """Verify the long-context 429 doesn't hit the generic rate-limit- or client-error handlers."""-- def test_long_context_429_not_treated_as_rate_limit(self):- """The error should be intercepted before the generic- is_rate_limited check fires a fallback switch."""- error_msg = "extra usage is required for long context requests."- status_code = 429- model = "claude-sonnet-4.6"-- _is_long_context_tier_error = (- status_code == 429- and "extra usage" in error_msg- and "long context" in error_msg- and "sonnet" in model.lower()- )- assert _is_long_context_tier_error--diff --git a/tests/agent/test_manual_compression_feedback.py b/tests/agent/test_manual_compression_feedback.pyindex 766fcb45c9b..3a02583aea7 100644--- a/tests/agent/test_manual_compression_feedback.py+++ b/tests/agent/test_manual_compression_feedback.py@@ -3,7 +3,6 @@from types import SimpleNamespacefrom agent.manual_compression_feedback import (- describe_compression_lock_skip,summarize_manual_compression,)@@ -15,8 +14,6 @@ def _messages(count: int) -> list[dict[str, str]]:]--def test_failure_reason_redaction_is_forced_at_ui_boundary(monkeypatch):messages = _messages(12)fake_secret = "sk-proj-" + "X" * 40@@ -59,10 +56,8 @@ def test_fallback_compression_reports_dropped_message_count():assert feedback["aborted"] is Falseassert feedback["fallback_used"] is True- assert feedback["headline"] == "Compressed with fallback: 12 → 4 messages"- assert "removed 8 message(s)" in feedback["note"]+ assert "12" in feedback["headline"] and "4" in feedback["headline"]+ assert "8" in feedback["note"]assert "invalid response" in feedback["note"]--diff --git a/tests/agent/test_memory_nudge_counter_hydration.py b/tests/agent/test_memory_nudge_counter_hydration.pydeleted file mode 100644index c3bbf7a9362..00000000000--- a/tests/agent/test_memory_nudge_counter_hydration.py+++ /dev/null@@ -1,121 +0,0 @@-"""Regression test for issue #22357 — gateway memory-nudge counter hydration.--The gateway creates a fresh AIAgent for each inbound message in several-common scenarios (cache miss, 1h idle eviction at gateway/run.py-_AGENT_CACHE_IDLE_TTL_SECS, config-signature mismatch, process restart).-A freshly built AIAgent has _turns_since_memory=0 and _user_turn_count=0.--Without hydration from conversation_history, the memory.nudge_interval-trigger (`_turns_since_memory >= _memory_nudge_interval`) can never be-reached: every turn looks like turn 1 to the counter, so a user can chat-for hours without ever seeing a "💾 Self-improvement review:" message.--This test pins the hydration behavior added at the top of run_conversation().-"""--from __future__ import annotations---def _make_minimal_agent():- """Build the smallest object that can run the hydration block.-- The hydration code only touches attributes — no I/O, no API calls.- We can just set up a SimpleNamespace-like object with the right fields- and call run_conversation's prelude logic via a thin wrapper.-- The hydration block itself is straightforward enough that we test it- by replicating it inline against the same inputs — that's the only- way to test ~10 lines deep inside a 500+ line method without rewriting- the whole agent loop.- """---def _run_hydration(conversation_history, memory_nudge_interval=10,- prior_turn_count=0, prior_turns_since_memory=0):- """Replicate the hydration block from run_agent.py:11128-11150.- Keeping this in sync with the production code is a one-line job; the- block has no dependencies on anything except primitives + history.- """- user_turn_count = prior_turn_count- turns_since_memory = prior_turns_since_memory-- if conversation_history and user_turn_count == 0:- prior_user_turns = sum(- 1 for m in conversation_history if m.get("role") == "user"- )- if prior_user_turns > 0:- user_turn_count = prior_user_turns- if memory_nudge_interval > 0 and turns_since_memory == 0:- turns_since_memory = prior_user_turns % memory_nudge_interval-- return user_turn_count, turns_since_memory---def test_no_history_leaves_counters_at_zero():- user_turn, since_mem = _run_hydration([], memory_nudge_interval=10)- assert user_turn == 0- assert since_mem == 0---def test_seven_user_turns_history_hydrates_to_seven():- """Mid-cycle history: 7 prior user turns, interval 10 → counter at 7."""- history = []- for i in range(7):- history.append({"role": "user", "content": f"q{i}"})- history.append({"role": "assistant", "content": f"a{i}"})-- user_turn, since_mem = _run_hydration(history, memory_nudge_interval=10)-- assert user_turn == 7- assert since_mem == 7 # 7 % 10 = 7, next 3 turns will trigger review-----def test_idempotent_when_counters_already_set():- """A cached agent with existing counters must NOT have them clobbered.-- Without the `_user_turn_count == 0` guard, cached agents would lose- their accumulated state every time they re-entered the function.- """- history = [{"role": "user", "content": "q1"}, {"role": "assistant", "content": "a1"}]- user_turn, since_mem = _run_hydration(- history, memory_nudge_interval=10,- prior_turn_count=15, prior_turns_since_memory=5,- )- # Existing counters preserved (cache hit case)- assert user_turn == 15- assert since_mem == 5-------def test_production_code_contains_hydration_block():- """Smoke test: confirm the hydration code is actually wired into the- turn path. If someone deletes it, tests above still pass against the- inline replica — this fails them awake.-- The agent-loop prologue now lives in ``agent/turn_context.py``- (``build_turn_context``), with the loop body in- ``agent/conversation_loop.py``. Assert the block is present in the- turn subsystem — if it disappears entirely, this guard fails loudly.- Either module counts so the guard tolerates legitimate relocation- within the turn subsystem.- """- from pathlib import Path- repo = Path(__file__).resolve().parents[2]- turn_src = "".join(- (repo / "agent" / name).read_text(encoding="utf-8")- for name in ("conversation_loop.py", "turn_context.py")- )- # Anchor on the unique comment + the modulo line.- assert "Hydrate per-session nudge counters from persisted history" in turn_src, (- "Hydration comment missing from the turn subsystem "- "(conversation_loop.py / turn_context.py)"- )- assert (- "agent._turns_since_memory = prior_user_turns % agent._memory_nudge_interval"- in turn_src- ), "Hydration modulo assignment missing from the turn subsystem"diff --git a/tests/agent/test_memory_provider.py b/tests/agent/test_memory_provider.pyindex e28f9bd5a8c..76a4aa56cf3 100644--- a/tests/agent/test_memory_provider.py+++ b/tests/agent/test_memory_provider.py@@ -80,13 +80,6 @@ class FakeMemoryProvider(MemoryProvider):self.memory_writes.append((action, target, content))-class MetadataMemoryProvider(FakeMemoryProvider):- """Provider that opts into write metadata."""-- def on_memory_write(self, action, target, content, metadata=None):- self.memory_writes.append((action, target, content, metadata or {}))--class MessagesMemoryProvider(FakeMemoryProvider):"""Provider that opts into completed-turn message context."""@@ -121,29 +114,6 @@ class BlockingPrefetchProvider(FakeMemoryProvider):# ----------------------------------------------------------------------------class TestMemoryProviderABC:- def test_cannot_instantiate_abstract(self):- """ABC cannot be instantiated directly."""- with pytest.raises(TypeError):- MemoryProvider()-- def test_concrete_provider_works(self):- """Concrete implementation can be instantiated."""- p = FakeMemoryProvider()- assert p.name == "fake"- assert p.is_available()-- def test_default_optional_hooks_are_noop(self):- """Optional hooks have default no-op implementations."""- p = FakeMemoryProvider()- # These should not raise- p.on_turn_start(1, "hello")- p.on_session_end([])- p.on_pre_compress([])- p.on_memory_write("add", "memory", "test")- p.queue_prefetch("query")- p.sync_turn("user", "assistant")- p.shutdown()# ---------------------------------------------------------------------------@@ -160,12 +130,6 @@ class TestMemoryManager:assert mgr.build_system_prompt() == ""assert mgr.prefetch_all("test") == ""- def test_add_provider(self):- mgr = MemoryManager()- p = FakeMemoryProvider("test1")- mgr.add_provider(p)- assert len(mgr.providers) == 1- assert [p.name for p in mgr.providers] == ["test1"]def test_get_provider_by_name(self):mgr = MemoryManager()@@ -788,18 +752,6 @@ class TestSequentialDispatchRouting:"""- def test_handle_tool_call_routes_to_provider(self):- """handle_tool_call dispatches to the correct provider's handler."""- mgr = MemoryManager()- provider = FakeMemoryProvider("hindsight", tools=[- {"name": "hindsight_recall", "description": "Recall", "parameters": {}},- {"name": "hindsight_retain", "description": "Retain", "parameters": {}},- ])- mgr.add_provider(provider)-- result = json.loads(mgr.handle_tool_call("hindsight_recall", {"query": "alice"}))- assert result["handled"] == "hindsight_recall"- assert result["args"] == {"query": "alice"}def test_tool_names_include_all_providers(self):@@ -824,89 +776,6 @@ class TestSequentialDispatchRouting:# ----------------------------------------------------------------------------class TestSetupFieldFiltering:- """Test the 'when' clause and 'default_from' logic used by the- memory setup wizard in hermes_cli/memory_setup.py.-- These features are generic — any memory plugin can use them in- get_config_schema(). Currently used by the hindsight plugin.- """-- def _filter_fields(self, schema, provider_config):- """Simulate the setup wizard's field filtering logic.-- Returns list of (key, effective_default) for fields that pass- the 'when' filter.- """- results = []- for field in schema:- key = field["key"]- default = field.get("default")-- # Dynamic default- default_from = field.get("default_from")- if default_from and isinstance(default_from, dict):- ref_field = default_from.get("field", "")- ref_map = default_from.get("map", {})- ref_value = provider_config.get(ref_field, "")- if ref_value and ref_value in ref_map:- default = ref_map[ref_value]-- # When clause- when = field.get("when")- if when and isinstance(when, dict):- if not all(provider_config.get(k) == v for k, v in when.items()):- continue-- results.append((key, default))- return results-- def test_when_clause_filters_fields(self):- """Fields with 'when' are skipped if the condition doesn't match."""- schema = [- {"key": "mode", "default": "cloud"},- {"key": "api_url", "default": "https://api.example.com", "when": {"mode": "cloud"}},- {"key": "api_key", "default": None, "when": {"mode": "cloud"}},- {"key": "llm_provider", "default": "openai", "when": {"mode": "local"}},- {"key": "llm_model", "default": "gpt-4o-mini", "when": {"mode": "local"}},- {"key": "budget", "default": "mid"},- ]-- # Cloud mode: should see mode, api_url, api_key, budget- cloud_fields = self._filter_fields(schema, {"mode": "cloud"})- cloud_keys = [k for k, _ in cloud_fields]- assert cloud_keys == ["mode", "api_url", "api_key", "budget"]-- # Local mode: should see mode, llm_provider, llm_model, budget- local_fields = self._filter_fields(schema, {"mode": "local"})- local_keys = [k for k, _ in local_fields]- assert local_keys == ["mode", "llm_provider", "llm_model", "budget"]--- def test_when_and_default_from_combined(self):- """when clause and default_from work together correctly."""- provider_models = {"groq": "openai/gpt-oss-120b", "openai": "gpt-4o-mini"}- schema = [- {"key": "mode", "default": "local"},- {"key": "llm_provider", "default": "openai", "when": {"mode": "local"}},- {"key": "llm_model", "default": "gpt-4o-mini",- "default_from": {"field": "llm_provider", "map": provider_models},- "when": {"mode": "local"}},- {"key": "api_url", "default": "https://api.example.com", "when": {"mode": "cloud"}},- ]-- # Local + groq: should see llm_model with groq default, no api_url- fields = self._filter_fields(schema, {"mode": "local", "llm_provider": "groq"})- keys = [k for k, _ in fields]- assert "llm_model" in keys- assert "api_url" not in keys- assert dict(fields)["llm_model"] == "openai/gpt-oss-120b"-- # Cloud: should see api_url, no llm_model- fields = self._filter_fields(schema, {"mode": "cloud"})- keys = [k for k, _ in fields]- assert "api_url" in keys- assert "llm_model" not in keys# ---------------------------------------------------------------------------@@ -945,14 +814,8 @@ class TestFlattenMessageContent:"""- def test_none_is_empty(self):- from agent.codex_responses_adapter import _summarize_user_message_for_log- assert _summarize_user_message_for_log(None, sep="\n") == ""- def test_scalar_fallback(self):- from agent.codex_responses_adapter import _summarize_user_message_for_log- assert _summarize_user_message_for_log(42, sep="\n") == "42"def test_flattened_output_is_regex_safe(self):"""The original failure: sanitize_context(list) raised TypeError."""@@ -1021,48 +884,6 @@ class TestOnMemoryWriteBridge:"""- def test_memory_manager_tool_injection_deduplicates(self):- """Memory manager tools already in self.tools (from plugin registry)- must not be appended again. Duplicate function names cause 400 errors- on providers that enforce unique names (e.g. Xiaomi MiMo via Nous Portal).-- Regression test for: duplicate mnemosyne_recall / mnemosyne_remember /- mnemosyne_stats in tools array → 400 from Nous Portal.- """- mgr = MemoryManager()- p = FakeMemoryProvider("ext", tools=[- {"name": "ext_recall", "description": "Recall", "parameters": {}},- {"name": "ext_remember", "description": "Remember", "parameters": {}},- ])- mgr.add_provider(p)-- # Simulate self.tools already containing one of the plugin tools- # (as if it was registered via ctx.register_tool → get_tool_definitions)- existing_tools = [- {"type": "function", "function": {"name": "ext_recall", "description": "Recall (from registry)", "parameters": {}}},- {"type": "function", "function": {"name": "web_search", "description": "Search", "parameters": {}}},- ]-- # Apply the same dedup logic from run_agent.py __init__- _existing_names = {- t.get("function", {}).get("name")- for t in existing_tools- if isinstance(t, dict)- }- for _schema in mgr.get_all_tool_schemas():- _tname = _schema.get("name", "")- if _tname and _tname in _existing_names:- continue- existing_tools.append({"type": "function", "function": _schema})- if _tname:- _existing_names.add(_tname)-- # ext_recall should NOT be duplicated; ext_remember should be added- tool_names = [t["function"]["name"] for t in existing_tools]- assert tool_names.count("ext_recall") == 1, f"ext_recall duplicated: {tool_names}"- assert tool_names.count("ext_remember") == 1- assert tool_names.count("web_search") == 1- assert len(existing_tools) == 3 # web_search + ext_recall + ext_rememberdef test_on_memory_write_tolerates_provider_failure(self):"""If a provider's on_memory_write raises, others still get notified."""@@ -1078,73 +899,6 @@ class TestOnMemoryWriteBridge:assert good.memory_writes == [("add", "user", "test")]-class TestHonchoCadenceTracking:- """Verify Honcho provider cadence gating depends on on_turn_start().-- Bug: _turn_count was never updated because on_turn_start() was not called- from run_conversation(). This meant cadence checks always passed (every- turn fired both context refresh and dialectic). Fixed by calling- on_turn_start(self._user_turn_count, msg) before prefetch_all().- """-- def test_turn_count_updates_on_turn_start(self):- """on_turn_start sets _turn_count, enabling cadence math."""- from plugins.memory.honcho import HonchoMemoryProvider- p = HonchoMemoryProvider()- assert p._turn_count == 0- p.on_turn_start(1, "hello")- assert p._turn_count == 1- p.on_turn_start(5, "world")- assert p._turn_count == 5-- def test_queue_prefetch_respects_dialectic_cadence(self):- """With dialecticCadence=3, dialectic should skip turns 2 and 3."""- from plugins.memory.honcho import HonchoMemoryProvider- p = HonchoMemoryProvider()- p._dialectic_cadence = 3- p._recall_mode = "context"- p._session_key = "test-session"- # Simulate a manager that records prefetch calls- class FakeManager:- def prefetch_context(self, key, query=None):- pass-- p._manager = FakeManager()-- # Simulate turn 1: last_dialectic_turn = -999, so (1 - (-999)) >= 3 -> fires- p.on_turn_start(1, "turn 1")- p._last_dialectic_turn = 1 # simulate it fired- p._last_context_turn = 1-- # Simulate turn 2: (2 - 1) = 1 < 3 -> should NOT fire dialectic- p.on_turn_start(2, "turn 2")- assert (p._turn_count - p._last_dialectic_turn) < p._dialectic_cadence-- # Simulate turn 3: (3 - 1) = 2 < 3 -> should NOT fire dialectic- p.on_turn_start(3, "turn 3")- assert (p._turn_count - p._last_dialectic_turn) < p._dialectic_cadence-- # Simulate turn 4: (4 - 1) = 3 >= 3 -> should fire dialectic- p.on_turn_start(4, "turn 4")- assert (p._turn_count - p._last_dialectic_turn) >= p._dialectic_cadence-- def test_injection_frequency_first_turn_with_1indexed(self):- """injection_frequency='first-turn' must inject on turn 1 (1-indexed)."""- from plugins.memory.honcho import HonchoMemoryProvider- p = HonchoMemoryProvider()- p._injection_frequency = "first-turn"-- # Turn 1 should inject (not skip)- p.on_turn_start(1, "first message")- assert p._turn_count == 1- # The guard is `_turn_count > 1`, so turn 1 passes through- should_skip = p._injection_frequency == "first-turn" and p._turn_count > 1- assert not should_skip, "First turn (turn 1) should NOT be skipped"-- # Turn 2 should skip- p.on_turn_start(2, "second message")- should_skip = p._injection_frequency == "first-turn" and p._turn_count > 1- assert should_skip, "Second turn (turn 2) SHOULD be skipped"class TestMemoryToolToolsetGate:@@ -1240,107 +994,9 @@ class TestMemoryToolToolsetGate:tools, names = self._run_memory_injection(None, None)assert tools == []- def test_multiple_schemas_all_blocked_together(self):- """When the gate is closed, no memory tools leak — not even partially."""- mgr = self._mgr_with_tools("fact_store", "memory_search", "memory_add")- tools, names = self._run_memory_injection(["terminal"], mgr)- assert tools == []- assert names == set()- def test_multiple_schemas_all_injected_when_enabled(self):- """When the gate is open, every memory tool schema is injected."""- mgr = self._mgr_with_tools("fact_store", "memory_search", "memory_add")- tools, names = self._run_memory_injection(None, mgr)- assert names == {"fact_store", "memory_search", "memory_add"}-class TestContextEngineToolsetGate:- """Issue #5544 (sibling): context engine tools follow the same gate.-- `agent.context_compressor.get_tool_schemas()` (e.g. lcm_grep, lcm_describe,- lcm_expand) was appended to AIAgent.tools unconditionally. Same blind- injection class as the memory bug; same local-model penalty. Gate name:- "context_engine" (matches the existing plugin-system convention).- """-- @staticmethod- def _run_context_engine_injection(enabled_toolsets, compressor):- """Simulate the gated context-engine injection block from agent_init.py."""- tools = []- valid_tool_names = set()- engine_tool_names = set()-- if (- compressor is not None- and tools is not None- and (- enabled_toolsets is None- or "context_engine" in enabled_toolsets- )- ):- _existing = {- t.get("function", {}).get("name")- for t in tools- if isinstance(t, dict)- }- for _schema in compressor.get_tool_schemas():- _tname = _schema.get("name", "")- if _tname and _tname in _existing:- continue- tools.append({"type": "function", "function": _schema})- if _tname:- valid_tool_names.add(_tname)- engine_tool_names.add(_tname)- _existing.add(_tname)-- return tools, valid_tool_names, engine_tool_names-- class _FakeCompressor:- def __init__(self, schemas):- self._schemas = schemas-- def get_tool_schemas(self):- return list(self._schemas)-- def _compressor_with(self, *tool_names):- return self._FakeCompressor(- [{"name": n, "description": n, "parameters": {}} for n in tool_names]- )-- def test_none_toolsets_injects(self):- """enabled_toolsets=None injects context-engine tools — backward compat."""- c = self._compressor_with("lcm_grep", "lcm_describe", "lcm_expand")- tools, names, engine_names = self._run_context_engine_injection(None, c)- assert engine_names == {"lcm_grep", "lcm_describe", "lcm_expand"}-- def test_context_engine_in_toolsets_injects(self):- """enabled_toolsets including 'context_engine' injects the tools."""- c = self._compressor_with("lcm_grep")- tools, names, engine_names = self._run_context_engine_injection(- ["terminal", "context_engine"], c- )- assert "lcm_grep" in engine_names-- def test_empty_toolsets_blocks_injection(self):- """`platform_toolsets: telegram: []` must suppress context-engine tools."""- c = self._compressor_with("lcm_grep")- tools, names, engine_names = self._run_context_engine_injection([], c)- assert tools == []- assert engine_names == set()-- def test_toolsets_without_context_engine_blocks_injection(self):- """A toolset list that doesn't name 'context_engine' suppresses injection."""- c = self._compressor_with("lcm_grep", "lcm_describe")- tools, names, engine_names = self._run_context_engine_injection(- ["terminal", "memory"], c- )- assert tools == []- assert engine_names == set()-- def test_no_compressor_no_injection(self):- """Gate is moot without a context_compressor."""- tools, names, engine_names = self._run_context_engine_injection(None, None)- assert tools == []class TestNormalizeToolSchema:@@ -1355,17 +1011,6 @@ class TestNormalizeToolSchema:"""- def test_already_wrapped_schema_is_unwrapped(self):- from agent.memory_manager import normalize_tool_schema- wrapped = {- "type": "function",- "function": {"name": "x_grep", "description": "d", "parameters": {}},- }- out = normalize_tool_schema(wrapped)- assert out is not None- assert out["name"] == "x_grep"- # Must be the inner function schema, not the wrapper.- assert "type" not in out or out.get("type") != "function"def test_non_dict_rejected(self):diff --git a/tests/agent/test_memory_provider_unavailable_warning.py b/tests/agent/test_memory_provider_unavailable_warning.pyindex d161a0a3b1d..49e135369f6 100644--- a/tests/agent/test_memory_provider_unavailable_warning.py+++ b/tests/agent/test_memory_provider_unavailable_warning.py@@ -19,10 +19,7 @@ def test_warns_once_and_dedupes(caplog):warnings = [r for r in caplog.records if "unavailable" in r.getMessage()]assert len(warnings) == 1, "should warn exactly once per provider (gateway dedup)"- msg = warnings[0].getMessage()- assert "hindsight" in msg- assert "hermes memory status" in msg- assert ".env" in msg # surfaces the systemd/gateway root cause+ assert "hindsight" in warnings[0].getMessage()def test_distinct_providers_each_warn(caplog):@@ -47,13 +44,3 @@ def test_provider_reason_is_appended(caplog):warnings = [r for r in caplog.records if "unavailable" in r.getMessage()]assert len(warnings) == 1assert hint in warnings[0].getMessage()---def test_empty_reason_adds_no_trailing_noise(caplog):- agent_init._warned_unavailable_providers.clear()- with caplog.at_level(logging.WARNING, logger="run_agent"):- agent_init._warn_memory_provider_unavailable("hindsight", "")-- msg = next(r.getMessage() for r in caplog.records if "unavailable" in r.getMessage())- # No dangling separator when there's no provider-specific hint.- assert msg.rstrip().endswith("service environment.")diff --git a/tests/agent/test_memory_recall_indicator.py b/tests/agent/test_memory_recall_indicator.pyindex 4179ea6f2cc..f89ddbd9069 100644--- a/tests/agent/test_memory_recall_indicator.py+++ b/tests/agent/test_memory_recall_indicator.py@@ -48,29 +48,6 @@ def test_no_status_returns_empty_string():assert mgr.describe_recall() == ""-def test_no_providers_returns_empty_string():- assert MemoryManager().describe_recall() == ""---def test_single_memory_is_singular():- mgr = MemoryManager()- mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 1)))- assert mgr.describe_recall() == "🧠 Hindsight — recalled 1 memory"---def test_multiple_memories_are_plural():- mgr = MemoryManager()- mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 3)))- assert mgr.describe_recall() == "🧠 Hindsight — recalled 3 memories"---def test_zero_count_renders_generic():- # count 0 = content injected but no discrete count (e.g. reflect synthesis).- mgr = MemoryManager()- mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 0)))- assert mgr.describe_recall() == "🧠 Hindsight — recalled relevant memory"--def test_aggregates_multiple_providers():# builtin is always accepted first; a second external is rejected, so use# builtin + one external to exercise the join path.@@ -78,8 +55,8 @@ def test_aggregates_multiple_providers():mgr.add_provider(_FakeProvider("builtin", RecallStatus("Notes", 2)))mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 5)))result = mgr.describe_recall()- assert "🧠 Notes — recalled 2 memories" in result- assert "🧠 Hindsight — recalled 5 memories" in result+ assert "Notes" in result and "2" in result+ assert "Hindsight" in result and "5" in resultdef test_failing_provider_is_skipped_not_fatal():@@ -87,4 +64,4 @@ def test_failing_provider_is_skipped_not_fatal():mgr.add_provider(_FakeProvider("builtin", None, raises=True))mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 1)))# The raising provider is swallowed; the healthy one still surfaces.- assert mgr.describe_recall() == "🧠 Hindsight — recalled 1 memory"+ assert "Hindsight" in mgr.describe_recall()diff --git a/tests/agent/test_memory_session_switch.py b/tests/agent/test_memory_session_switch.pyindex b4f913d4bf3..d65a2588740 100644--- a/tests/agent/test_memory_session_switch.py+++ b/tests/agent/test_memory_session_switch.py@@ -8,7 +8,6 @@ for scoped writes) keep writing into the old session's record."""-import pytestfrom agent.memory_manager import MemoryManagerfrom agent.memory_provider import MemoryProvider@@ -63,30 +62,6 @@ class _RecordingProvider(MemoryProvider):)-# ----------------------------------------------------------------------------# MemoryProvider ABC — default on_session_switch is a no-op-# ------------------------------------------------------------------------------class _MinimalProvider(MemoryProvider):- """Provider that does NOT override on_session_switch — ABC default must no-op."""-- @property- def name(self) -> str:- return "minimal"-- def is_available(self) -> bool:- return True-- def initialize(self, session_id, **kwargs): # pragma: no cover - unused- pass-- def get_tool_schemas(self):- return []----# ---------------------------------------------------------------------------# MemoryManager.on_session_switch — fan-out# ---------------------------------------------------------------------------@@ -111,8 +86,6 @@ def test_manager_fans_out_to_all_providers():assert call["extra"] == {"reason": "resume"}--def test_manager_isolates_provider_failures():"""A provider that raises must not block other providers."""@@ -134,8 +107,6 @@ def test_manager_isolates_provider_failures():assert good.switch_calls[0]["new"] == "new-sid"--# ---------------------------------------------------------------------------# MemoryManager.sync_all / queue_prefetch_all — session_id propagation# ---------------------------------------------------------------------------diff --git a/tests/agent/test_memory_sync_interrupted.py b/tests/agent/test_memory_sync_interrupted.pyindex 8cf07a80638..3f0c25ddf0c 100644--- a/tests/agent/test_memory_sync_interrupted.py+++ b/tests/agent/test_memory_sync_interrupted.py@@ -19,8 +19,6 @@ via ``__new__`` so the full ``run_conversation`` machinery isn't needed"""from unittest.mock import MagicMock-import pytest-def _bare_agent():"""Build an ``AIAgent`` with only the attributes@@ -67,39 +65,3 @@ class TestSyncExternalMemoryForTurn:kwargs = agent._memory_manager.sync_all.call_args.kwargsassert kwargs["turn_author"] == {"id": "bot:alpha", "name": "Alpha", "is_bot": True}assert kwargs["session_id"] == "test_session_001"-- @pytest.mark.parametrize("stash", ["human turn", "no stash yet"])- def test_human_turn_or_agent_without_stash_sends_no_author_keyword(self, stash):- """A bare agent built before any turn has no stash; the sync must not depend on it."""- agent = _bare_agent()- if stash == "human turn":- agent._turn_author = None-- agent._sync_external_memory_for_turn(- original_user_message="status?", final_response="All green.", interrupted=False,- )-- agent._memory_manager.sync_all.assert_called_once()- assert "turn_author" not in agent._memory_manager.sync_all.call_args.kwargs-- # --- Normal completed turn still syncs ----------------------------------- # --- Edge cases (pre-existing behaviour preserved) ----------------------- # --- Exception safety -------------------------------------------------- # --- Multimodal content flattening --------------------------------------- # --- The specific matrix the reporter asked about -------------------diff --git a/tests/agent/test_memory_user_id.py b/tests/agent/test_memory_user_id.pyindex ba6cf85f110..7eb36cb938c 100644--- a/tests/agent/test_memory_user_id.py+++ b/tests/agent/test_memory_user_id.py@@ -5,10 +5,8 @@ so each gateway user gets their own memory bucket instead of sharing a static on"""import json-import osfrom unittest.mock import MagicMock, patch-import pytestfrom agent.memory_provider import MemoryProviderfrom agent.memory_manager import MemoryManager@@ -304,23 +302,4 @@ class TestHonchoUserIdScoping:# ----------------------------------------------------------------------------class TestAIAgentUserIdPropagation:- """Verify AIAgent stores user_id and passes it to memory init kwargs."""-- def test_user_id_stored_on_agent(self):- """AIAgent should store user_id as instance attribute."""- with patch.dict(os.environ, {"HERMES_HOME": "/tmp/test_hermes"}):- from run_agent import AIAgent- agent = object.__new__(AIAgent)- # Manually set the attribute as __init__ does- agent._user_id = "test_user_42"- assert agent._user_id == "test_user_42"-- def test_user_id_none_by_default(self):- """AIAgent should have None user_id when not provided (CLI mode)."""- with patch.dict(os.environ, {"HERMES_HOME": "/tmp/test_hermes"}):- from run_agent import AIAgent- agent = object.__new__(AIAgent)- agent._user_id = None- assert agent._user_id is Nonediff --git a/tests/agent/test_message_sanitization_policy.py b/tests/agent/test_message_sanitization_policy.pyindex 74db041d987..60da18278ef 100644--- a/tests/agent/test_message_sanitization_policy.py+++ b/tests/agent/test_message_sanitization_policy.py@@ -38,12 +38,6 @@ class TestDeterministicCallId:"call_567cb168d22d"assert deterministic_call_id("", "", 0) == "call_feda901d71ea"- def test_deterministic_across_calls(self):- a = deterministic_call_id("web_search", '{"q":"x"}', 3)- b = deterministic_call_id("web_search", '{"q":"x"}', 3)- assert a == b- assert a.startswith("call_")- assert len(a) == len("call_") + 12def test_index_disambiguates(self):assert deterministic_call_id("t", "{}", 0) != deterministic_call_id("t", "{}", 1)@@ -52,11 +46,6 @@ class TestDeterministicCallId:out = deterministic_call_id("t", "bad \ud800 arg", 0)assert out.startswith("call_")- def test_run_agent_static_delegates(self):- from run_agent import AIAgent- assert AIAgent._deterministic_call_id("terminal", '{"command":"ls"}', 0) == \- deterministic_call_id("terminal", '{"command":"ls"}', 0)-# ---------------------------------------------------------------------------# coalesce_tool_call_id@@ -78,11 +67,6 @@ class TestCoalesceToolCallId:assert coalesce_tool_call_id(SimpleNamespace(call_id=None, id=" i ")) == "i"assert coalesce_tool_call_id(SimpleNamespace(call_id=None, id=None)) == ""- def test_run_agent_static_delegates(self):- from run_agent import AIAgent- tc = {"call_id": "c9", "id": "i9"}- assert AIAgent._get_tool_call_id_static(tc) == coalesce_tool_call_id(tc)-# ---------------------------------------------------------------------------# uniquify_tool_call_ids@@ -340,25 +324,6 @@ class TestPerProviderReasoningEcho:assert agent._needs_thinking_reasoning_pad() is Trueassert agent._reasoning_echo_opt_in() is True- def test_opt_in_does_not_replace_family_detection(self):- """Kimi-coding family still gets echo-back regardless of the flag."""- agent = self._make_agent(- reasoning_echo_flag=False,- provider="kimi-coding",- model="t9s/kimi-k3",- )- agent._needs_kimi_tool_reasoning = lambda: True- assert agent._needs_thinking_reasoning_pad() is True-- def test_opt_in_additive_with_family_detection(self):- """Flag on AND family match: both paths agree, still True."""- agent = self._make_agent(- reasoning_echo_flag=True,- provider="deepseek",- model="deepseek-v4-pro",- )- agent._needs_deepseek_tool_reasoning = lambda: True- assert agent._needs_thinking_reasoning_pad() is Truedef test_strict_fallback_strips_despite_primary_opt_in(self):"""Primary has flag=True, fallback switches to a strict provider.@@ -456,20 +421,4 @@ class TestPerProviderReasoningEcho:assert agent._reasoning_echo_flag is Trueassert agent.model == "glm-5.2"- def test_apply_policy_preserves_with_opt_in(self):- """apply_reasoning_content_policy preserves reasoning_content- when needs_thinking_pad is True (via opt-in)."""- from agent.message_sanitization import apply_reasoning_content_policy- source = {"role": "assistant", "content": "hi", "reasoning_content": "my thoughts"}- api_msg = {"role": "assistant", "content": "hi"}- apply_reasoning_content_policy(source, api_msg, needs_thinking_pad=True)- assert api_msg["reasoning_content"] == "my thoughts"-- def test_apply_policy_strips_without_opt_in(self):- """apply_reasoning_content_policy strips reasoning_content- when needs_thinking_pad is False (no opt-in, not echo family)."""- from agent.message_sanitization import apply_reasoning_content_policy- source = {"role": "assistant", "content": "hi", "reasoning_content": "my thoughts"}- api_msg = {"role": "assistant", "content": "hi"}- apply_reasoning_content_policy(source, api_msg, needs_thinking_pad=False)- assert "reasoning_content" not in api_msg+diff --git a/tests/agent/test_message_sequence_repair.py b/tests/agent/test_message_sequence_repair.pyindex ef001c495e2..b848a905704 100644--- a/tests/agent/test_message_sequence_repair.py+++ b/tests/agent/test_message_sequence_repair.py@@ -36,10 +36,6 @@ def test_drop_scaffolding_rewinds_orphan_tool_tail():assert messages == [{"role": "user", "content": "task"}]----# ── _repair_message_sequence ───────────────────────────────────────────────def test_repair_merges_consecutive_user_messages():@@ -157,18 +153,6 @@ def test_repair_keeps_tool_matching_only_call_id():assert any(m.get("role") == "tool" for m in messages)------------def test_repair_keeps_tool_result_keyed_by_response_item_id():"""The normalized call id must still pair the raw Responses item id."""from agent.agent_runtime_helpers import repair_message_sequence@@ -387,7 +371,6 @@ def test_repair_merge_preserves_api_content_sidecar_with_multimodal_content():assert messages[1]["api_content"] == "wire bytes"-def test_sanitize_consumes_all_responses_id_variants_for_duplicate_result():"""A sibling-id replay must not replace the first real result."""from agent.agent_runtime_helpers import sanitize_api_messages@@ -429,7 +412,6 @@ def test_tool_executor_uses_canonical_responses_pairing_id():) == "call_ABC"-# ── repair_message_sequence_with_cursor (#44837) ───────────────────────────from agent.agent_runtime_helpers import repair_message_sequence_with_cursor@@ -473,9 +455,6 @@ def test_cursor_rewinds_when_compaction_happens_before_cursor():assert messages[agent._last_flushed_db_idx] is unflushed_assistant---def test_flush_guard_clamps_overshooting_cursor():"""_flush_messages_to_session_db safety net: an overshooting cursor mustnot produce a negative-start slice that skips everything (#44837)."""@@ -512,21 +491,11 @@ def test_flush_guard_clamps_overshooting_cursor():# ── Pass 0: merge consecutive assistant messages (issue #29148, #49147) ─────--------# ── tool_call_id de-duplication (#58327) ────────────────────────────────────# Strict providers (DeepSeek) reject a payload where the same tool_call_id# appears more than once with HTTP 400 "Duplicate value for 'tool_call_id'".--def test_sanitize_deduplicates_duplicate_tool_results():"""sanitize_api_messages (final pre-API chokepoint) drops duplicate toolresults sharing a tool_call_id."""@@ -820,10 +789,6 @@ def test_repair_keeps_tool_result_when_tool_calls_are_sdk_objects():assert tool_msg["content"] == "file contents"----# ── Self-recovery: heal empty-content non-final messages ──────────────────# Repro of the production incident: a dead stream persisted an empty-content# assistant stub mid-transcript, and every later request 400'd with@@ -1073,14 +1038,6 @@ def test_compressor_sanitize_keeps_composite_keyed_pair():# ── _classify_tool_call_orphans ─────────────────────────────────────────-def test_classify_orphans_empty():- from agent.agent_runtime_helpers import _classify_tool_call_orphans- sv, rs, orphaned, missing = _classify_tool_call_orphans([])- assert sv == set()- assert rs == set()- assert orphaned == []- assert missing == []-def test_classify_orphans_clean_pair():from agent.agent_runtime_helpers import _classify_tool_call_orphans@@ -1095,26 +1052,6 @@ def test_classify_orphans_clean_pair():assert missing == []-def test_classify_orphans_detects_orphaned_result():- from agent.agent_runtime_helpers import _classify_tool_call_orphans- messages = [- {"role": "tool", "tool_call_id": "orphan_1", "content": "no matching call"},- ]- sv, rs, orphaned, missing = _classify_tool_call_orphans(messages)- assert [m["tool_call_id"] for m in orphaned] == ["orphan_1"]- assert missing == []---def test_classify_orphans_detects_missing_result():- from agent.agent_runtime_helpers import _classify_tool_call_orphans- messages = [- {"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f", "arguments": "{}"}}]},- ]- sv, rs, orphaned, missing = _classify_tool_call_orphans(messages)- assert orphaned == []- assert [tc["id"] for tc in missing] == ["call_1"]--def test_classify_orphans_mixed():from agent.agent_runtime_helpers import _classify_tool_call_orphansmessages = [@@ -1388,8 +1325,6 @@ def test_sanitize_stubs_interrupted_first_occurrence_keeps_replay_pair():assert out[5]["content"] == "real result"--# ── Bridged tool_call: wire-visible response name must echo the call name ──# Google matches functionResponse.name against functionCall.name and rejects a# mismatch with HTTP 400 INVALID_ARGUMENT. #72089 fixed this for the native@@ -1523,7 +1458,6 @@ def test_repair_user_merge_pops_persist_marker_on_stamped_survivor():assert _DB_PERSISTED_MARKER not in messages[0]-def test_repair_assistant_merge_pops_persist_marker_on_content_rewrite():agent = _bare_agent()stamped = {"role": "assistant", "content": "first reply", _DB_PERSISTED_MARKER: True}@@ -1540,7 +1474,6 @@ def test_repair_assistant_merge_pops_persist_marker_on_content_rewrite():assert _DB_PERSISTED_MARKER not in messages[1]-def test_repair_prune_unanswered_tool_calls_pops_persist_marker():"""Pass 2 rewrites ``msg["tool_calls"]`` in place on a stamped assistantrow; the marker must go or the DB keeps the unpruned call list."""diff --git a/tests/agent/test_meta_agent_init.py b/tests/agent/test_meta_agent_init.pyindex c916d513859..7b597a154ca 100644--- a/tests/agent/test_meta_agent_init.py+++ b/tests/agent/test_meta_agent_init.py@@ -1,6 +1,5 @@"""Tests for AIAgent provider=meta host-mandated api_mode."""-import pytestdef test_agent_init_meta_base_url_implies_codex_responses():@@ -37,22 +36,6 @@ def test_agent_init_explicit_chat_wins_over_mandate():assert agent.provider == "meta"-def test_agent_init_meta_provider_stays_meta():- from run_agent import AIAgent-- agent = AIAgent(- provider="meta",- base_url="https://api.meta.ai/v1",- api_key="sk-test-meta",- model="muse-spark-1.2",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )- assert agent.provider == "meta"- assert agent.provider != "custom"--def test_agent_init_custom_with_meta_url_also_mandates():from run_agent import AIAgent@@ -83,36 +66,6 @@ def test_agent_init_meta_url_case_insensitive():assert agent.api_mode == "codex_responses"-def test_agent_init_anthropic_url_implies_provider_and_api_mode():- """Regression for host-mandated api_mode shadowing provider-slug rewrite (#63425).-- When provider=None and base_url is api.anthropic.com, the elif chain must- still rewrite provider to "anthropic" before the credential-pool check.- The host-mandated fallback moved to the bottom of the cascade (fix/meta-prompt-caching)- ensures this; the old top-position mandated branch set api_mode without the slug rewrite- and caused credential-pool validation to discard anthropic-scoped pools.- """- from unittest.mock import MagicMock, patch-- from run_agent import AIAgent-- with patch("agent.anthropic_adapter.build_anthropic_client", return_value=MagicMock()), patch(- "agent.anthropic_credentials._is_oauth_token", return_value=False- ):- agent = AIAgent(- provider=None,- base_url="https://api.anthropic.com/v1",- api_key="sk-test-anthropic",- model="claude-sonnet-4-5",- api_mode=None,- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )- assert agent.provider == "anthropic"- assert agent.api_mode == "anthropic_messages"--def test_agent_init_anthropic_url_preserves_credential_pool():"""Anthropic-scoped credential pool must survive provider auto-detection.diff --git a/tests/agent/test_meta_usage_cache_reporting.py b/tests/agent/test_meta_usage_cache_reporting.pyindex 52034d2d8fd..d78f11d78b5 100644--- a/tests/agent/test_meta_usage_cache_reporting.py+++ b/tests/agent/test_meta_usage_cache_reporting.py@@ -17,13 +17,7 @@ def test_meta_cached_tokens_flows_to_cache_read():cu = normalize_usage(usage, api_mode="codex_responses")assert cu.cache_read_tokens == 3920assert cu.input_tokens == 80 # 4000 - 3920- # rendered cache line would be cache=3920/4000 (98%)- total = cu.prompt_tokens- assert total == 4000- pct = (cu.cache_read_tokens / total * 100) if total else 0- assert 97 <= pct <= 99- rendered = f"cache={cu.cache_read_tokens}/{total} ({pct:.0f}%)"- assert rendered == "cache=3920/4000 (98%)"+ assert cu.prompt_tokens == 4000def test_meta_cache_write_tokens():diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.pyindex 5bf893ab607..fa75a1b7a58 100644--- a/tests/agent/test_micro_compaction.py+++ b/tests/agent/test_micro_compaction.py@@ -20,7 +20,6 @@ The invariants that matter:from unittest.mock import patch-import pytestfrom agent.context_compressor import (COMPRESSED_SUMMARY_METADATA_KEY,@@ -384,32 +383,6 @@ class TestMicroCompaction:blob = json.dumps(payload)assert "answer 0" not in blob and "question 0" not in blob- def test_telemetry_reports_occupancy_without_forcing_resolution(self, caplog):- """Occupancy is the headline: how full the window is being kept.-- It must be read from the cached threshold only. The public- ``threshold_tokens`` property resolves lazily and can fire a- synchronous /models probe (#32221); telemetry must never be what- blocks a turn, so an unresolved window reports null instead.- """- import json- import logging-- cc = _compressor()- cc.threshold_tokens = 10_000 # pin; also populates the cache- messages = _conversation(exchanges=8)-- with caplog.at_level(logging.INFO, logger="agent.context_compressor"):- cc._micro_compact(messages)-- line = next(r.getMessage() for r in caplog.records- if "micro compaction telemetry:" in r.getMessage())- payload = json.loads(line.split("micro compaction telemetry: ", 1)[1])-- assert payload["threshold_tokens"] == 10_000- assert payload["occupancy_pct"] == pytest.approx(- payload["tokens_after"] / 10_000 * 100, abs=0.1- )def test_emitter_never_forces_window_resolution(self, caplog):"""The emitter reads the cached threshold, never the property.@@ -448,33 +421,6 @@ class TestMicroCompaction:assert payload["occupancy_pct"] is Noneassert payload["threshold_tokens"] is None- def test_first_pass_costs_marker_overhead_then_pays_it_back(self):- """The first pass can grow the transcript; later passes recover it.-- Inserting the summary marker costs a fixed block of scaffolding- (``SUMMARY_PREFIX``, the historical heading and the end marker —- currently ~450 tokens and grows when the preamble is lengthened).- On pass one that overhead is paid against a single absorbed exchange,- so the net can be positive. From pass two on the marker is replaced- rather than added, so the scaffolding is already paid for and each- absorbed exchange is pure saving. Anyone reading a single turn's- telemetry needs to know this before concluding it made things worse.- """- from agent.model_metadata import estimate_messages_tokens_rough-- cc = _compressor()- messages = _conversation(exchanges=10)- start = estimate_messages_tokens_rough(messages)-- messages = cc._micro_compact(messages)- after_first = estimate_messages_tokens_rough(messages)-- for _ in range(5):- messages = cc._micro_compact(messages)- after_many = estimate_messages_tokens_rough(messages)-- assert after_first > start, "expected one-time marker overhead"- assert after_many < after_first, "later passes must recover it"def test_cumulative_savings_accumulate_across_passes(self):"""Session-total savings go positive once marker overhead is paid back.@@ -712,26 +658,6 @@ class TestMicroCompaction:assert cc._micro_compact_rolling_summary == ""assert cc._micro_compact_cursor == 0- def test_persist_disabled_agent_never_micro_compacts(self):- """finalize_turn must skip micro-compaction on isolated fork agents.-- The background-review fork sets _persist_disabled=True; running a- pass there burns an aux-LLM call on a throwaway replay transcript- and, if the compressor ever holds a DB binding, would- archive_and_compact the CANONICAL session rows.- """- import inspect-- from agent import turn_finalizer-- # The micro-compaction gate lives in the helper finalize_turn calls.- src = inspect.getsource(turn_finalizer._micro_compact_after_turn)- micro_block = src.split("Post-turn micro-compaction", 1)[1]- # Scope to the micro block only: stop at the persist call that follows.- micro_block = micro_block.split("agent._persist_session", 1)[0]- assert "_persist_disabled" in micro_block, (- "micro-compaction gate must check agent._persist_disabled"- )def test_db_sync_passes_exact_carried_messages(self):"""Micro-compaction carries a prefix and suffix around its summary marker.@@ -845,26 +771,6 @@ class TestDefragFlushCursorInvalidation:cc._micro_compact(list(messages))assert cc._flush_scan_cursor_invalidated is False- def test_finalizer_consumes_flag_and_invalidates_agent_cursor(self):- """finalize_turn's micro-compaction block must translate the- compressor flag into agent._db_flush_scan_prefix = None (and reset- the flag) so the next flush re-examines the rewritten marker row."""- import inspect-- from agent import turn_finalizer-- # The micro-compaction gate lives in the helper finalize_turn calls.- src = inspect.getsource(turn_finalizer._micro_compact_after_turn)- micro_block = src.split("Post-turn micro-compaction", 1)[1]- micro_block = micro_block.split("agent._persist_session", 1)[0]- assert "_flush_scan_cursor_invalidated" in micro_block, (- "finalize_turn must consume the compressor's cursor-invalidation "- "flag raised by the defrag marker pop"- )- assert "agent._db_flush_scan_prefix = None" in micro_block, (- "finalize_turn must invalidate the bounded flush-scan cursor "- "when the defrag pop stripped a live marker's stamp"- )class TestMergeAdjacentUserTurnsPersistedMarker:diff --git a/tests/agent/test_minimax_provider.py b/tests/agent/test_minimax_provider.pyindex a6996e8179a..a2cc480c024 100644--- a/tests/agent/test_minimax_provider.py+++ b/tests/agent/test_minimax_provider.py@@ -3,33 +3,6 @@from unittest.mock import patch-class TestMinimaxContextLengths:- """Verify context length entries match official docs.-- M2.x series is 204,800; M3 is 1M (max output 512K).- Source: https://platform.minimax.io/docs/api-reference/text-anthropic-api- """-- def test_minimax_prefix_has_correct_context(self):- from agent.model_metadata import DEFAULT_CONTEXT_LENGTHS- assert DEFAULT_CONTEXT_LENGTHS["minimax"] == 204_800-- def test_minimax_models_resolve_via_prefix(self):- from agent.model_metadata import get_model_context_length- # M2.x models resolve to 204,800 via the "minimax" catch-all- for model in ("MiniMax-M2.7", "MiniMax-M2.5", "MiniMax-M2.1", "MiniMax-M2"):- ctx = get_model_context_length(model, "")- assert ctx == 204_800, f"{model} expected 204800, got {ctx}"-- def test_minimax_m3_resolves_to_1m(self):- from agent.model_metadata import get_model_context_length- # M3 must beat the generic "minimax" catch-all (204,800) and resolve to- # a 1M-class context. The exact value depends on the source: our- # hardcoded catalog says 1,000,000; the OpenRouter catalog reports- # 1,048,576 (1024²). Either is correct — assert "≥ 1M, not 204,800".- for model in ("MiniMax-M3", "minimax/minimax-m3", "minimax-m3"):- ctx = get_model_context_length(model, "")- assert ctx >= 1_000_000, f"{model} expected 1M-class, got {ctx}"class TestMinimaxM3StaleCacheGuard:@@ -39,12 +12,6 @@ class TestMinimaxM3StaleCacheGuard:to 1M, while leaving correct M2.x entries (204,800) untouched."""- def test_suggests_minimax_m3(self):- from agent.model_metadata import _model_name_suggests_minimax_m3- assert _model_name_suggests_minimax_m3("MiniMax-M3")- assert _model_name_suggests_minimax_m3("minimax/minimax-m3")- assert not _model_name_suggests_minimax_m3("MiniMax-M2.7")- assert not _model_name_suggests_minimax_m3("MiniMax-M2.5")@@ -88,65 +55,9 @@ class TestMinimaxThinkingSupport:# MiniMax should NOT get adaptive thinking or output_configassert "output_config" not in kwargs- def test_minimax_m25_gets_manual_thinking(self):- from agent.anthropic_adapter import build_anthropic_kwargs- kwargs = build_anthropic_kwargs(- model="MiniMax-M2.5",- messages=[{"role": "user", "content": "hello"}],- tools=None,- max_tokens=4096,- reasoning_config={"enabled": True, "effort": "high"},- )- assert "thinking" in kwargs- assert kwargs["thinking"]["type"] == "enabled"- def test_thinking_still_works_for_claude(self):- from agent.anthropic_adapter import build_anthropic_kwargs- kwargs = build_anthropic_kwargs(- model="claude-sonnet-4-20250514",- messages=[{"role": "user", "content": "hello"}],- tools=None,- max_tokens=4096,- reasoning_config={"enabled": True, "effort": "medium"},- )- assert "thinking" in kwargs-class TestMinimaxAuxModel:- """Verify auxiliary model is the current frontier standard (not highspeed).-- As of M3's release (2026-06-01) the minimax / minimax-cn provider- profiles advertise ``MiniMax-M3`` as their ``default_aux_model`` (the- same model users see in ``_PROVIDER_MODELS["minimax"]`` and in the- user-facing ``model.default`` for a Token-Plan install). The OAuth- / Coding Plan path sticks with M2.7 because M3 is not on that- tier — see ``test_minimax_profile.py`` for the per-provider split.-- The historical concern this class guards is the #4082 / #6082- regression: the highspeed variant costs 2x with no model-quality- benefit, so we still assert that no aux choice contains the substring- ``"highspeed"``.- """-- def test_minimax_aux_is_standard(self):- # Import model_tools to trigger plugin discovery so the- # ProviderProfile objects are registered in the providers- # registry before _get_aux_model_for_provider() is called.- # Without this, profile-based resolution can be order-dependent- # or fail outright in isolation (the minimax-* entries are- # no longer in _API_KEY_PROVIDER_AUX_MODELS_FALLBACK after the- # minimax-M3 default-aux-model cleanup, so the profile is- # the only path to a non-empty aux value).- import model_tools # noqa: F401- from agent.auxiliary_client import _get_aux_model_for_provider- assert _get_aux_model_for_provider("minimax") == "MiniMax-M3"- assert _get_aux_model_for_provider("minimax-cn") == "MiniMax-M3"-- def test_minimax_aux_not_highspeed(self):- import model_tools # noqa: F401- from agent.auxiliary_client import _get_aux_model_for_provider- assert "highspeed" not in _get_aux_model_for_provider("minimax")- assert "highspeed" not in _get_aux_model_for_provider("minimax-cn")class TestMinimaxBetaHeaders:@@ -192,16 +103,8 @@ class TestMinimaxBetaHeaders:# -- _common_betas_for_base_url unit tests ---------------------------- def test_common_betas_none_url(self):- from agent.anthropic_adapter import _common_betas_for_base_url, _COMMON_BETAS- assert _common_betas_for_base_url(None) == _COMMON_BETAS- def test_common_betas_minimax_url(self):- from agent.anthropic_adapter import _common_betas_for_base_url, _TOOL_STREAMING_BETA- betas = _common_betas_for_base_url("https://api.minimax.io/anthropic")- assert _TOOL_STREAMING_BETA not in betas- assert len(betas) > 0 # still has other betas@@ -220,37 +123,10 @@ class TestMinimaxApiMode:assert determine_api_mode("minimax") == "anthropic_messages"- def test_minimax_with_url_also_works(self):- from hermes_cli.providers import determine_api_mode- # Even with explicit base_url, provider lookup takes priority- assert determine_api_mode("minimax", "https://api.minimax.io/anthropic") == "anthropic_messages"--- def test_openai_returns_chat_completions(self):- from hermes_cli.providers import determine_api_mode- # Sanity check: standard providers are unaffected- result = determine_api_mode("deepseek")- assert result == "chat_completions"---class TestMinimaxMaxOutput:- """Verify _get_anthropic_max_output returns correct limits for MiniMax models.-- MiniMax max output is 131,072 tokens (source: OpenClaw model definitions,- cross-referenced with MiniMax API behavior).- """- def test_minimax_m27_output_limit(self):- from agent.anthropic_adapter import _get_anthropic_max_output- assert _get_anthropic_max_output("MiniMax-M2.7") == 131_072- def test_claude_output_unaffected(self):- from agent.anthropic_adapter import _get_anthropic_max_output- # Sanity: Claude limits are not broken by the MiniMax entry- assert _get_anthropic_max_output("claude-sonnet-4-6") == 64_000- assert _get_anthropic_max_output("claude-sonnet-5") == 128_000class TestMinimaxPreserveDots:diff --git a/tests/agent/test_moa_aggregator_cost_slot.py b/tests/agent/test_moa_aggregator_cost_slot.pyindex 787384609fc..63914b67842 100644--- a/tests/agent/test_moa_aggregator_cost_slot.py+++ b/tests/agent/test_moa_aggregator_cost_slot.py@@ -12,7 +12,6 @@ the session cost as advisor-fan-out only.from __future__ import annotationsfrom types import SimpleNamespace-from unittest.mock import patchimport pytest@@ -74,27 +73,3 @@ def test_create_populates_last_aggregator_slot(moa_config, monkeypatch):assert slot["model"] == "anthropic/claude-opus-4.8"assert slot["provider"] == "openrouter"assert slot["model"] != "closed"---def test_client_exposes_last_aggregator_slot(moa_config, monkeypatch):- """MoAClient delegates last_aggregator_slot to its completions facade so- session accounting can read it without touching internals."""- from agent.moa_loop import MoAClient-- def fake_call_llm(**kwargs):- return _response("acted" if kwargs.get("task") != "moa_reference" else "advice")-- monkeypatch.setattr("agent.moa_loop.call_llm", fake_call_llm)-- client = MoAClient("closed")- assert client.last_aggregator_slot is None-- client.chat.completions.create(- model="closed",- messages=[{"role": "user", "content": "clean the db"}],- )-- slot = client.last_aggregator_slot- assert slot is not None- assert slot["model"] == "anthropic/claude-opus-4.8"- assert slot["provider"] == "openrouter"diff --git a/tests/agent/test_moa_context_max_tokens.py b/tests/agent/test_moa_context_max_tokens.pyindex 5800b2a7764..6307e77112a 100644--- a/tests/agent/test_moa_context_max_tokens.py+++ b/tests/agent/test_moa_context_max_tokens.py@@ -70,30 +70,3 @@ def test_aggregator_call_never_receives_reference_max_tokens(hermes_home, monkeyassert "max_tokens" not in aggregator_calls[0]-def test_aggregator_call_uncapped_when_reference_max_tokens_unset(hermes_home, monkeypatch):- """Sanity check: with no reference_max_tokens configured, the reference- call still explicitly passes max_tokens=None (call_llm itself decides- whether to omit it on the wire), while the aggregator call structurally- never carries a max_tokens kwarg at all — the pre-#56756 default MoA- behavior for the aggregator, preserved regardless of the reference cap."""- from agent.moa_loop import aggregate_moa_context-- calls: list[dict] = []-- def fake_call_llm(**kwargs):- calls.append(kwargs)- return _response("advice" if kwargs.get("task") == "moa_reference" else "synthesis")-- monkeypatch.setattr("agent.moa_loop.call_llm", fake_call_llm)-- aggregate_moa_context(- user_prompt="clean the db",- api_messages=[{"role": "user", "content": "clean the db"}],- reference_models=[{"provider": "openrouter", "model": "openai/gpt-5.5"}],- aggregator={"provider": "openrouter", "model": "anthropic/claude-opus-4.8"},- )-- reference_calls = [c for c in calls if c.get("task") == "moa_reference"]- aggregator_calls = [c for c in calls if c.get("task") == "moa_aggregator"]- assert reference_calls[0]["max_tokens"] is None- assert "max_tokens" not in aggregator_calls[0]diff --git a/tests/agent/test_moa_loop_mode.py b/tests/agent/test_moa_loop_mode.pyindex e7c0f9facb1..38becba4ce4 100644--- a/tests/agent/test_moa_loop_mode.py+++ b/tests/agent/test_moa_loop_mode.py@@ -1,5 +1,4 @@from types import SimpleNamespace-from unittest.mock import MagicMockimport pytest@@ -536,24 +535,24 @@ def test_run_reference_prepends_advisory_system_prompt(monkeypatch):def test_references_run_in_parallel(monkeypatch):"""References fan out concurrently (delegate-batch semantics), not serially.- Each reference sleeps; wall-time must approximate the slowest single call,- not the sum. Order is preserved and a failing reference is isolated.+ The two dispatched references rendezvous on a barrier: a serial fan-out+ could never release it, so the call would fail instead of returning+ ``resp-p1``. Order is preserved and a failing reference is isolated."""- import time+ import threadingfrom agent import moa_loop# Force _extract_text down its fallback path (no transport normalize).monkeypatch.setattr(moa_loop, "get_transport", lambda *_a, **_k: None)- barrier_hits = []+ both_in_flight = threading.Barrier(2, timeout=10)def slow_call_llm(**kwargs):- barrier_hits.append(time.monotonic())model = kwargs["model"]if model == "boom":raise RuntimeError("kaboom")- time.sleep(0.5)+ both_in_flight.wait()return _response(f"resp-{kwargs['provider']}")monkeypatch.setattr(moa_loop, "call_llm", slow_call_llm)@@ -565,48 +564,18 @@ def test_references_run_in_parallel(monkeypatch):{"provider": "p3", "model": "ok"},]- start = time.monotonic()out = moa_loop._run_references_parallel(refs, [{"role": "user", "content": "hi"}], temperature=0.6, max_tokens=64)- elapsed = time.monotonic() - start- # Two 0.5s sleeps run concurrently → well under the 1.0s serial floor.- # Threshold sits at 0.95s (not tight against 0.5s) to tolerate CI- # thread-pool startup jitter while still failing hard if the two calls- # ran serially (which would be ≥1.0s).- assert elapsed < 0.95, f"references did not run in parallel (took {elapsed:.2f}s)"# Output order matches input order (stable Reference N labelling).assert [label for label, _, _ in out] == ["p1:ok", "moa:preset", "p2:boom", "p3:ok"]assert "recursively reference MoA" in out[1][1]assert out[2][1].startswith("[failed:")assert out[0][1] == "resp-p1"+ assert out[3][1] == "resp-p3"-def test_references_parallel_without_agent_is_unaffected(monkeypatch):- """No agent passed (the pre-fix call shape) must behave exactly as- before: block until every reference completes, no interrupt check."""- import time-- from agent import moa_loop-- monkeypatch.setattr(moa_loop, "get_transport", lambda *_a, **_k: None)- # Poll interval shorter than the reference's own sleep so the assertion- # below would catch a regression that waits a whole poll cycle extra.- monkeypatch.setattr(moa_loop, "_REFERENCE_POLL_INTERVAL_S", 0.05)-- def slow_call_llm(**kwargs):- time.sleep(0.2)- return _response(f"resp-{kwargs['provider']}")-- monkeypatch.setattr(moa_loop, "call_llm", slow_call_llm)-- refs = [{"provider": "p1", "model": "ok"}]- out = moa_loop._run_references_parallel(- refs, [{"role": "user", "content": "hi"}],- )-- assert out[0][1] == "resp-p1"def test_references_parallel_interrupt_aborts_wait(monkeypatch):@@ -627,9 +596,6 @@ def test_references_parallel_interrupt_aborts_wait(monkeypatch):def fake_call_llm(**kwargs):if kwargs["provider"] == "fast":- # Simulate the interrupt arriving right after the fast reference- # finishes, while the wedged one is still in flight.- fake_agent._interrupt_requested = Truereturn _response("fast output")# "wedged" — never returns within the test unless released, standing# in for a reference whose own (possibly very long) timeout hasn't@@ -647,6 +613,9 @@ def test_references_parallel_interrupt_aborts_wait(monkeypatch):start = time.monotonic()out = moa_loop._run_references_parallel(refs, [{"role": "user", "content": "hi"}], agent=fake_agent,+ # The interrupt arrives right after the fast reference is recorded,+ # while the wedged one is still in flight.+ progress_callback=lambda done, total, label: setattr(fake_agent, "_interrupt_requested", True),)elapsed = time.monotonic() - start@@ -659,26 +628,6 @@ def test_references_parallel_interrupt_aborts_wait(monkeypatch):release_wedged.set() # don't leak a blocked thread past the test-def _ref_config(home, fanout: str | None = None):- home.mkdir()- fanout_line = f"\n fanout: {fanout}" if fanout else ""- (home / "config.yaml").write_text(- f"""-moa:- default_preset: review- presets:- review:- reference_models:- - provider: openai-codex- model: gpt-5.5- - provider: openrouter- model: anthropic/claude-opus-4.8- aggregator:- provider: openrouter- model: anthropic/claude-opus-4.8{fanout_line}-""".strip(),- encoding="utf-8",- )@@ -1016,58 +965,6 @@ def test_aggregate_skips_aggregator_when_all_references_failed(monkeypatch):-def _facade_all_failed_fixture(monkeypatch, tmp_path, policy):- """Common scaffolding: a 'review' preset whose references ALL fail."""- from agent import moa_loop- from agent.usage_pricing import CanonicalUsage-- home = tmp_path / ".hermes"- home.mkdir()- (home / "config.yaml").write_text(- f"""-moa:- default_preset: review- presets:- review:- degraded_reference_policy: {policy}- reference_models:- - provider: openrouter- model: bad-model-a- - provider: openrouter- model: bad-model-b- aggregator:- provider: openrouter- model: aggregator-""".strip(),- encoding="utf-8",- )- monkeypatch.setenv("HERMES_HOME", str(home))- outputs = [- (- "bad-model-a",- "[failed: HTTP 401 key=super-secret]",- moa_loop._RefAccounting(CanonicalUsage(input_tokens=5), 0.05),- ),- (- "bad-model-b",- "[failed: timeout after 900s]",- moa_loop._RefAccounting(CanonicalUsage(input_tokens=3), 0.03),- ),- ]- aggregator_calls = []-- def fake_call_llm(**kwargs):- aggregator_calls.append(kwargs)- return _response("aggregator acted alone")-- monkeypatch.setattr(moa_loop, "_run_references_parallel", lambda *a, **k: outputs)- monkeypatch.setattr(moa_loop, "call_llm", fake_call_llm)- monkeypatch.setattr(- moa_loop,- "_slot_runtime",- lambda slot: {"provider": slot["provider"], "model": slot["model"]},- )- return moa_loop, outputs, aggregator_calls@@ -1122,7 +1019,6 @@ def test_late_completing_interrupted_reference_feeds_accounting_sink(monkeypatch"""A reference still in flight at interrupt time gets a placeholder inthe results, but its eventual REAL accounting must reach the sink."""import threading- import timefrom agent import moa_loopdiff --git a/tests/agent/test_moa_observability_bridge.py b/tests/agent/test_moa_observability_bridge.pyindex f0add6e15b9..b2ae9f2ee27 100644--- a/tests/agent/test_moa_observability_bridge.py+++ b/tests/agent/test_moa_observability_bridge.py@@ -109,19 +109,6 @@ class TestConversationLoopHelper:assert _moa_reference_metrics_for_hook(_Agent()) is None- def test_returns_metrics_for_a_moa_client(self):- from agent.conversation_loop import _moa_reference_metrics_for_hook-- payload = [slot_metrics(_acct(), "label")]-- class _Client:- def last_reference_metrics(self):- return payload-- class _Agent:- client = _Client()-- assert _moa_reference_metrics_for_hook(_Agent()) is payloaddef test_a_raising_accessor_is_swallowed(self):from agent.conversation_loop import _moa_reference_metrics_for_hookdiff --git a/tests/agent/test_moa_prepared_request_client_swap.py b/tests/agent/test_moa_prepared_request_client_swap.pyindex 0721b9f03f8..92cbeeff473 100644--- a/tests/agent/test_moa_prepared_request_client_swap.py+++ b/tests/agent/test_moa_prepared_request_client_swap.py@@ -42,21 +42,3 @@ def test_client_without_a_chat_attribute_is_not_a_facade():assert _moa_client_consumes_prepared_request(None) is False-def test_native_client_rejects_the_key_it_must_not_receive():- """Why the guard exists: the kwarg is fatal to a native client."""- native = _NativeCompletions()- try:- native.create(- model="2 model",- messages=[{"role": "user", "content": "hi"}],- _moa_prepared_request={"messages": [], "layers": 3},- )- except TypeError as exc:- assert "_moa_prepared_request" in str(exc)- else: # pragma: no cover - would mean the premise no longer holds- raise AssertionError("native client accepted the private MoA kwarg")-- # Without the key it is an ordinary call the rebuilt client can serve.- assert native.create(- model="2 model", messages=[{"role": "user", "content": "hi"}]- ) == "native ok"diff --git a/tests/agent/test_moa_prepared_request_leak.py b/tests/agent/test_moa_prepared_request_leak.pyindex 2e925a7d668..d4e44056835 100644--- a/tests/agent/test_moa_prepared_request_leak.py+++ b/tests/agent/test_moa_prepared_request_leak.py@@ -6,7 +6,7 @@ stays "moa". The dispatch must strip the MoA-internal key so the native SDKdoes not reject it."""import types-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockfrom agent.chat_completion_helpers import _dispatch_nonstreaming_api_request@@ -50,18 +50,3 @@ def test_moa_key_stripped_from_native_client():)-def test_no_moa_key_when_absent():- """Normal non-MoA call should work without the key present."""- agent = _make_agent(provider="openai")- api_kwargs = {- "model": "gpt-4",- "messages": [{"role": "user", "content": "hi"}],- }-- def _make_client(label=None):- return agent.client-- _dispatch_nonstreaming_api_request(agent, api_kwargs, make_client=_make_client)- call_kwargs = agent.client.chat.completions.create.call_args[1]- assert "_moa_prepared_request" not in call_kwargs- assert call_kwargs["model"] == "gpt-4"diff --git a/tests/agent/test_moa_reference_system_prompt.py b/tests/agent/test_moa_reference_system_prompt.pydeleted file mode 100644index 00bb1acfd20..00000000000--- a/tests/agent/test_moa_reference_system_prompt.py+++ /dev/null@@ -1,73 +0,0 @@-"""-Test that the MoA reference system prompt contains explicit warnings-against claiming tool execution.--Related issue: #61452-"""--from agent.moa_loop import _REFERENCE_SYSTEM_PROMPT---def test_reference_system_prompt_prohibits_claiming_execution():- """- Verify that the reference system prompt contains explicit warnings- against claiming tool execution.-- The prompt should:- 1. State that reference models cannot execute anything- 2. Warn against claiming/implying execution- 3. Provide bad/good examples-- This addresses #61452 where reference models were fabricating- tool execution in their text output.- """- prompt_lower = _REFERENCE_SYSTEM_PROMPT.lower()-- # Critical constraints- assert "you cannot call tools" in prompt_lower or "you do not execute" in prompt_lower, \- "Prompt must explicitly state that reference models cannot execute"-- assert "never claim" in prompt_lower or "never imply" in prompt_lower, \- "Prompt must warn against claiming/implying execution"-- # Check for examples (helps models understand what NOT to do)- assert "bad:" in prompt_lower or "avoid:" in prompt_lower, \- "Prompt should provide negative examples"-- # Specific action verbs that should NOT appear as claimed actions- # (these are common patterns of hallucinated execution)- forbidden_patterns = [- "i ran", "i executed", "i downloaded", "i accessed",- "i checked", "i called", "i browsed"- ]-- # The prompt should mention these as bad examples- # (i.e., in the context of what to avoid, not as instruction)- has_any_forbidden = any(- f"bad: \"{pattern}" in _REFERENCE_SYSTEM_PROMPT.lower() or- f"avoid \"{pattern}" in _REFERENCE_SYSTEM_PROMPT.lower()- for pattern in forbidden_patterns- )-- # At least one bad example pattern should exist- assert has_any_forbidden or "examples" in _REFERENCE_SYSTEM_PROMPT.lower(), \- "Prompt should contain examples of what to avoid"---def test_reference_system_prompt_structure():- """- Verify the reference system prompt has a clear structure.-- A well-structured prompt helps models follow instructions better.- """- # Prompt should not be empty- assert len(_REFERENCE_SYSTEM_PROMPT) > 100, \- "Reference system prompt should be substantive"-- # Should have multiple paragraphs (structured guidance)- assert _REFERENCE_SYSTEM_PROMPT.count("\n\n") >= 2, \- "Prompt should be structured with multiple sections"-- # Should contain the word "advisor" (defines role)- assert "advisor" in _REFERENCE_SYSTEM_PROMPT.lower(), \- "Prompt should clearly define the advisor role"diff --git a/tests/agent/test_moa_slot_api_mode.py b/tests/agent/test_moa_slot_api_mode.pyindex 494891b2d83..9fa27419daf 100644--- a/tests/agent/test_moa_slot_api_mode.py+++ b/tests/agent/test_moa_slot_api_mode.py@@ -10,7 +10,6 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom unittest.mock import patch-import pytestdef _response(content="ok"):@@ -40,20 +39,6 @@ class TestSlotRuntimeApiMode:assert result["api_key"] == "test-key"- @patch("hermes_cli.runtime_provider.resolve_runtime_provider")- def test_slot_runtime_omits_api_mode_when_empty(self, mock_resolve):- """Empty string api_mode is treated as absent."""- mock_resolve.return_value = {- "provider": "copilot",- "model": "gpt-5.5",- "base_url": "https://api.githubcopilot.com",- "api_key": "test-key",- "api_mode": "",- }- from agent.moa_loop import _slot_runtime-- result = _slot_runtime({"provider": "copilot", "model": "gpt-5.5"})- assert "api_mode" not in result@@ -194,14 +179,3 @@ def test_one_shot_aggregate_moa_context_passes_slot_extra_body(monkeypatch):assert agg_calls[0]["extra_body"] == {"enable_thinking": False}-class TestCallLlmApiMode:- """call_llm should accept and forward api_mode parameter."""-- def test_call_llm_accepts_api_mode_kwarg(self):- """call_llm signature includes api_mode parameter."""- import inspect- from agent.auxiliary_client import call_llm-- sig = inspect.signature(call_llm)- assert "api_mode" in sig.parameters- assert sig.parameters["api_mode"].default is Nonediff --git a/tests/agent/test_moa_slot_max_tokens.py b/tests/agent/test_moa_slot_max_tokens.pyindex 4aceb8e4b90..37af3ab281b 100644--- a/tests/agent/test_moa_slot_max_tokens.py+++ b/tests/agent/test_moa_slot_max_tokens.py@@ -9,7 +9,6 @@ from __future__ import annotationsfrom unittest.mock import MagicMock, patch-import pytestclass TestRunReferenceSlotMaxTokens:@@ -37,46 +36,4 @@ class TestRunReferenceSlotMaxTokens:assert captured_kwargs.get("max_tokens") == 2000- def test_slot_max_tokens_absent_falls_back_to_preset(self):- """When slot has no max_tokens, the preset-level cap is used."""- from agent.moa_loop import _run_reference-- captured_kwargs: dict = {}-- def fake_call_llm(**kwargs):- captured_kwargs.update(kwargs)- mock_resp = MagicMock()- mock_resp.choices = [MagicMock(message=MagicMock(content="advice"))]- mock_resp.usage = None- return mock_resp-- slot = {"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}-- with patch("agent.moa_loop._slot_runtime", return_value={"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}), \- patch("agent.moa_loop.call_llm", side_effect=fake_call_llm), \- patch("agent.moa_loop._maybe_apply_moa_cache_control", side_effect=lambda msgs, rt, **kwargs: msgs):- _run_reference(slot, [{"role": "user", "content": "hi"}], max_tokens=2000)-- assert captured_kwargs.get("max_tokens") == 2000-- def test_both_none_means_uncapped(self):- """When neither slot nor preset has max_tokens, it's None (uncapped)."""- from agent.moa_loop import _run_reference-- captured_kwargs: dict = {}-- def fake_call_llm(**kwargs):- captured_kwargs.update(kwargs)- mock_resp = MagicMock()- mock_resp.choices = [MagicMock(message=MagicMock(content="advice"))]- mock_resp.usage = None- return mock_resp-- slot = {"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}-- with patch("agent.moa_loop._slot_runtime", return_value={"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}), \- patch("agent.moa_loop.call_llm", side_effect=fake_call_llm), \- patch("agent.moa_loop._maybe_apply_moa_cache_control", side_effect=lambda msgs, rt, **kwargs: msgs):- _run_reference(slot, [{"role": "user", "content": "hi"}], max_tokens=None)- assert captured_kwargs.get("max_tokens") is Nonediff --git a/tests/agent/test_moa_streaming.py b/tests/agent/test_moa_streaming.pyindex edacc5c6ac2..e1c28b17f89 100644--- a/tests/agent/test_moa_streaming.py+++ b/tests/agent/test_moa_streaming.py@@ -153,16 +153,6 @@ def test_create_wraps_completed_aggregator_response_as_delta_chunk(monkeypatch,assert agg["stream"] is True-def test_create_non_stream_path_unchanged(monkeypatch, tmp_path):- """Default (no stream): the aggregator call carries NO stream/stream_options- keys, so the non-streaming path is byte-identical to before."""- facade, calls = _facade(monkeypatch, tmp_path)- facade.create(messages=[{"role": "user", "content": "q"}], tools=[])-- agg = next(c for c in calls if c["task"] == "moa_aggregator")- assert "stream" not in agg- assert "stream_options" not in agg- assert "timeout" not in aggdef test_create_forwards_stream_read_timeout(monkeypatch, tmp_path):diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.pyindex 29964bd8108..3d8736f3c70 100644--- a/tests/agent/test_model_metadata.py+++ b/tests/agent/test_model_metadata.py@@ -30,7 +30,6 @@ from agent.model_metadata import (save_context_length,fetch_model_metadata,_MODEL_CACHE_TTL,- estimate_request_tokens_rough,)@@ -43,24 +42,15 @@ class TestEstimateTokensRough:assert estimate_tokens_rough("") == 0- def test_known_length(self):- assert estimate_tokens_rough("a" * 400) == 100-----class TestEstimateMessagesTokensRough:-def test_tool_call_message(self):"""Tool call messages with no 'content' key still contribute tokens."""msg = {"role": "assistant", "content": None,"tool_calls": [{"id": "1", "function": {"name": "terminal", "arguments": "{}"}}]}result = estimate_messages_tokens_rough([msg])assert result > 0- assert result == (len(str(msg)) + 3) // 4def test_persistence_timestamp_does_not_change_estimate(self):"""Durability metadata must not create artificial context pressure."""@@ -204,25 +194,6 @@ class TestResponsesItemImageAccounting:class TestEstimateRequestTokensRough:- def test_caches_tools_estimate(self):- messages = [{"role": "user", "content": "hello"}]- tools = [- {- "type": "function",- "function": {- "name": "terminal",- "description": "Run a command",- "parameters": {"type": "object", "properties": {"command": {"type": "string"}}},- },- }- ]-- # json.dumps is used for params sizing; ensure the tools estimate is cached- # so repeated calls don't keep re-serializing the same schema list.- with patch("agent.model_metadata.json.dumps", wraps=__import__("json").dumps) as dumps:- estimate_request_tokens_rough(messages, system_prompt="x" * 8, tools=tools)- estimate_request_tokens_rough(messages, system_prompt="x" * 8, tools=tools)- assert dumps.call_count == 1def test_tools_cache_is_bounded(self):# A long-lived process builds many transient tool lists; the cache must@@ -342,19 +313,6 @@ class TestDefaultContextLengths:model, provider="kimi-coding", base_url=base_url) == 1_048_576- @pytest.mark.parametrize("model, provider, base_url", [- ("muse-spark-1.3-contributor", "opencode-go", "https://opencode.ai/zen/go/v1"),- ("muse-spark-1.3", "meta-ai", "https://api.meta.ai/v1"),- ("meta/muse-spark-1.3", "commandcode", "https://api.commandcode.ai/provider/v1"),- ])- def test_muse_spark_resolves_1m_without_network(self, model, provider, base_url):- """Muse Spark is 1,048,576 on every host even when models.dev and the- live /models probe are unavailable (fresh HERMES_HOME, offline)."""- with patch("agent.model_metadata.get_cached_context_length", return_value=None), \- patch("agent.model_metadata._query_ollama_api_show", return_value=None), \- patch("agent.model_metadata.fetch_endpoint_model_metadata", return_value={}), \- patch("agent.models_dev.fetch_models_dev", return_value={}):- assert get_model_context_length(model, provider=provider, base_url=base_url) == 1_048_576@staticmethoddef _upstage_ctx(model):@@ -430,51 +388,6 @@ class TestDefaultContextLengths:api_key="oauth-token",) == 256000- def test_deepseek_v4_models_1m_context(self):- from agent.model_metadata import get_model_context_length- from unittest.mock import patch as mock_patch-- expected_keys = {- "deepseek-v4-pro": 1_000_000,- "deepseek-v4-flash": 1_000_000,- "deepseek-chat": 1_000_000,- "deepseek-reasoner": 1_000_000,- # Version-less canonical Flash id (2026-09 Flash refresh).- "deepseek-flash": 1_000_000,- }- for key, value in expected_keys.items():- assert key in DEFAULT_CONTEXT_LENGTHS, f"{key} missing"- assert DEFAULT_CONTEXT_LENGTHS[key] == value, (- f"{key} should be {value}, got {DEFAULT_CONTEXT_LENGTHS[key]}"- )-- # Longest-first substring matching must resolve both the bare V4- # ids (native DeepSeek) and the vendor-prefixed forms (OpenRouter- # / Nous Portal) to 1M without probing down to the legacy 128K- # ``deepseek`` substring fallback.- with mock_patch("agent.model_metadata.fetch_model_metadata", return_value={}), \- mock_patch("agent.model_metadata.fetch_endpoint_model_metadata", return_value={}), \- mock_patch("agent.model_metadata.get_cached_context_length", return_value=None):- cases = [- ("deepseek-v4-pro", 1_000_000),- ("deepseek-v4-flash", 1_000_000),- ("deepseek/deepseek-v4-pro", 1_000_000),- ("deepseek/deepseek-v4-flash", 1_000_000),- ("deepseek-chat", 1_000_000),- ("deepseek-reasoner", 1_000_000),- ("deepseek-flash", 1_000_000),- ("deepseek/deepseek-flash", 1_000_000),- ]- for model_id, expected_ctx in cases:- actual = get_model_context_length(model_id)- assert actual == expected_ctx, (- f"{model_id}: expected {expected_ctx}, got {actual}"- )-----# =========================================================================# Codex OAuth context-window resolution (provider="openai-codex")@@ -492,7 +405,6 @@ class TestCodexOAuthContextLength:mm._codex_oauth_context_cache = {}-def test_live_catalogue_cache_is_scoped_to_access_token(self):"""Different OAuth tokens must not share entitlement-specific metadata."""from agent import model_metadata as mm@@ -610,50 +522,8 @@ class TestCodexOAuthContextLength:assert remaining.get(stale_key) == live_contextassert remaining.get(other_key) == 128_000- @pytest.mark.parametrize(- "slug",- [- "gpt-5.6-sol",- "gpt-5.6-terra",- "gpt-5.6-luna",- "gpt-5.6-sol-2026-07-09", # dated snapshot via gpt-5.6 family prefix- "gpt-5.4",- "gpt-daybreak-blue-latest", # Sol alias; exact verified slug- ],- )- def test_900k_variant_slug_bumped_to_live_verified_900k(self, slug):- """The backend accepts ~911K for these slugs (verified live Aug 2026),- but the large window is OPT-IN: only the explicit ``-900k`` picker- variant resolves to 900K. The catalog only knows the base slug, so- the resolver strips the suffix for the lookup, then applies the bump."""- from agent.model_metadata import get_model_context_length-- fake_response = MagicMock()- fake_response.status_code = 200- fake_response.json.return_value = {- "models": [{"slug": slug, "context_window": 272_000}]- }- with patch("agent.model_metadata.requests.get", return_value=fake_response), \- patch("agent.model_metadata.get_cached_context_length", return_value=None), \- patch("agent.model_metadata.save_context_length"):- ctx = get_model_context_length(- model=slug + "-900k",- base_url="https://chatgpt.com/backend-api/codex",- api_key="fake-token",- provider="openai-codex",- )- assert ctx == 900_000- @pytest.mark.parametrize(- "slug",- [- "gpt-5.6-sol",- "gpt-5.6-terra",- "gpt-5.6-luna",- "gpt-5.4",- "gpt-daybreak-blue-latest",- ],- )+ @pytest.mark.parametrize("slug", ["gpt-5.6-sol"])def test_base_slug_keeps_advertised_272k(self, slug):"""Base slugs (no ``-900k`` suffix) keep the advertised 272K — thecheaper default limit. The verified-above bump is opt-in only."""@@ -747,30 +617,8 @@ class TestCodexOAuthContextLength:)assert ctx == 272_000- @pytest.mark.parametrize("slug", ["gpt-5.5", "gpt-5.4-mini"])- def test_slugs_that_enforce_272k_keep_advertised_value(self, slug):- """gpt-5.5 and gpt-5.4-mini both rejected large inputs in the live probe (360K and 500K respectively) —- their 272K advertisement is real enforcement, so no bump applies- (gpt-5.4 is an exact-match entry precisely to exclude -mini)."""- from agent.model_metadata import get_model_context_length-- fake_response = MagicMock()- fake_response.status_code = 200- fake_response.json.return_value = {- "models": [{"slug": slug, "context_window": 272_000}]- }- with patch("agent.model_metadata.requests.get", return_value=fake_response), \- patch("agent.model_metadata.get_cached_context_length", return_value=None), \- patch("agent.model_metadata.save_context_length"):- ctx = get_model_context_length(- model=slug,- base_url="https://chatgpt.com/backend-api/codex",- api_key="fake-token",- provider="openai-codex",- )- assert ctx == 272_000- @pytest.mark.parametrize("slug", ["gpt-5.6-sol-900k", "gpt-daybreak-blue-latest-900k"])+ @pytest.mark.parametrize("slug", ["gpt-5.6-sol-900k"])def test_fallback_table_resolution_also_bumped(self, slug):"""When the live probe fails, the 272K fallback-table value for anopted-in ``-900k`` variant is bumped the same way (same enforcement@@ -791,7 +639,7 @@ class TestCodexOAuthContextLength:)assert ctx == 900_000- @pytest.mark.parametrize("slug", ["gpt-5.6-sol", "gpt-daybreak-blue-latest"])+ @pytest.mark.parametrize("slug", ["gpt-5.6-sol"])def test_fallback_table_base_slug_stays_272k(self, slug):"""Fallback-table resolution for BASE slugs stays at the advertised272K — the opt-in rule applies on the offline path too."""@@ -817,10 +665,6 @@ class TestCodexOAuthContextLength:# (model_id, is_valid_variant, expected_ctx, expected_wire_model)_900K_TABLE = [("gpt-5.6-sol-900k", True, 900_000, "gpt-5.6-sol"),- ("gpt-5.6-terra-900k", True, 900_000, "gpt-5.6-terra"),- ("gpt-5.6-luna-900k", True, 900_000, "gpt-5.6-luna"),- ("gpt-5.4-900k", True, 900_000, "gpt-5.4"),- ("gpt-daybreak-blue-latest-900k", True, 900_000, "gpt-daybreak-blue-latest"),# dated snapshot of a routable 5.6 base("gpt-5.6-sol-2026-07-09-900k", True, 900_000, "gpt-5.6-sol-2026-07-09"),# vendor-namespaced variant (display/aux callers) resolves too@@ -830,7 +674,6 @@ class TestCodexOAuthContextLength:("gpt-5.6-sol-pro-900k", False, 272_000, "gpt-5.6-sol-pro-900k"),# genuine 272K enforcers get no variant("gpt-5.5-900k", False, 272_000, "gpt-5.5-900k"),- ("gpt-5.4-mini-900k", False, 272_000, "gpt-5.4-mini-900k"),# arbitrary future family descendants are not auto-eligible("gpt-5.6-nova-900k", False, 272_000, "gpt-5.6-nova-900k"),]@@ -870,8 +713,6 @@ class TestCodexOAuthContextLength:assert ctx == expected_ctx--# =========================================================================# Custom endpoint model metadata# =========================================================================@@ -1001,7 +842,6 @@ class TestNousPortalContextResolution:mm._endpoint_model_metadata_cache_time.clear()-@patch("agent.model_metadata.fetch_endpoint_model_metadata")def test_empty_model_never_fuzzy_matches_endpoint_catalog(self, mock_fetch):"""An empty model name must not substring-match arbitrary catalog@@ -1107,8 +947,6 @@ class TestNousPortalContextResolution:)--# =========================================================================# get_model_context_length — resolution order# =========================================================================@@ -1122,12 +960,6 @@ class TestGetModelContextLength:assert get_model_context_length("test/model") == 32000------@patch("agent.model_metadata.fetch_model_metadata")def test_api_missing_context_length_key(self, mock_fetch):"""Model in API but without context_length → defaults to the top@@ -1228,68 +1060,6 @@ class TestGetModelContextLength:assert result == _longest_key_match(DEFAULT_CONTEXT_LENGTHS, "zai-org/glm-5-tee")[1]----- @patch("agent.model_metadata.fetch_model_metadata")- def test_custom_endpoint_falls_back_to_hardcoded_catalog(self, mock_fetch):- """Custom/proxied endpoint that fails all probes should still resolve- via DEFAULT_CONTEXT_LENGTHS instead of returning 256K.-- Regression test for #38865: a corporate Anthropic proxy (custom- base_url) caused the custom-endpoint branch to short-circuit before- the catalog lookup, capping context at 256K even for models like- claude-opus-4-8 that are in the hardcoded catalog with 1M.- """- mock_fetch.return_value = {}-- # Patch all the probe functions that the custom-endpoint branch calls- # so they all fail (return None/empty), simulating a proxy that- # doesn't expose Ollama or local-server endpoints.- with (- patch(- "agent.model_metadata._resolve_endpoint_context_length",- return_value=None,- ),- patch(- "agent.model_metadata._query_ollama_api_show",- return_value=None,- ),- patch(- "agent.model_metadata._query_local_context_length",- return_value=None,- ),- patch(- "agent.model_metadata.is_local_endpoint",- return_value=False,- ),- ):- # A known model behind a custom proxy should resolve to its- # catalog value (1M), NOT the 256K fallback.- ctx = get_model_context_length(- "claude-opus-4-8",- base_url="https://my-gateway.example.com/v1/claude",- )- assert ctx == 1000000, f"Expected 1000000, got {ctx}"-- # Another known model- ctx2 = get_model_context_length(- "claude-sonnet-4-6",- base_url="https://my-gateway.example.com/v1/claude",- )- assert ctx2 == 1000000, f"Expected 1000000, got {ctx2}"-- # An unknown model on a custom endpoint should still fall back- # to 256K (no catalog match).- ctx3 = get_model_context_length(- "totally-unknown-model",- base_url="https://my-gateway.example.com/v1/claude",- )- assert ctx3 == DEFAULT_FALLBACK_CONTEXT, (- f"Expected {DEFAULT_FALLBACK_CONTEXT}, got {ctx3}"- )-# ── Local vs non-local Ollama context resolution (#63122) ──────────@patch("agent.model_metadata.get_cached_context_length", return_value=None)@@ -1381,8 +1151,6 @@ class TestBedrockContextResolution:"""--@patch("agent.model_metadata.fetch_endpoint_model_metadata")def test_bedrock_claude_4_6_ignores_stale_200k_cache(self, mock_fetch, tmp_path):"""Old 200K Bedrock cache entries must not mask the 1M table entry."""@@ -1399,18 +1167,6 @@ class TestBedrockContextResolution:mock_fetch.assert_not_called()- @patch("agent.model_metadata.fetch_endpoint_model_metadata")- def test_non_bedrock_url_still_probes(self, mock_fetch):- """Non-Bedrock hosts still reach the custom-endpoint probe."""- mock_fetch.return_value = {"some-model": {"context_length": 50000}}- ctx = get_model_context_length(- "some-model",- base_url="https://api.example.com/v1",- )- assert ctx == 50000- assert mock_fetch.called--# =========================================================================# Bedrock context cache persistence — only a probe result may be persisted# =========================================================================@@ -1558,7 +1314,6 @@ class TestFetchModelMetadata:return cache_path-def test_network_success_writes_disk_cache(self, tmp_path, monkeypatch):self._reset_cache()cache_path = self._isolate_disk_cache(monkeypatch, tmp_path)@@ -1609,7 +1364,6 @@ class TestFetchModelMetadata:assert mock_get.call_count == 1 # cached-@patch("agent.model_metadata.requests.get")def test_canonical_slug_aliasing(self, mock_get):"""Models with canonical_slug get indexed under both IDs."""@@ -1633,9 +1387,6 @@ class TestFetchModelMetadata:assert result["anthropic/claude-3.5-sonnet"]["context_length"] == 200000---# =========================================================================# Context probe tiers# =========================================================================@@ -1648,17 +1399,11 @@ class TestContextProbeTiers:class TestGetNextProbeTier:def test_from_256k(self):- assert get_next_probe_tier(256_000) == 128_000--+ assert get_next_probe_tier(CONTEXT_PROBE_TIERS[0]) == CONTEXT_PROBE_TIERS[1]def test_from_8k_returns_none(self):- assert get_next_probe_tier(8_000) is None----+ assert get_next_probe_tier(CONTEXT_PROBE_TIERS[-1]) is None# =========================================================================@@ -1668,14 +1413,6 @@ class TestGetNextProbeTier:class TestParseContextLimitFromError:--------@pytest.mark.parametrize("msg,expected", [("max_model_len 32768", 32768),("max_model_len: 32768", 32768),@@ -1716,14 +1453,6 @@ class TestParseContextLimitFromError:# Parsed limit not below current window → no recalibration.assert get_context_length_from_provider_error(msg, 32768) is None- def test_get_context_length_from_vllm_max_model_len_error(self):- from agent.model_metadata import get_context_length_from_provider_error-- msg = (- "The engine prompt length 90000 exceeds the max_model_len 32768. "- "Please reduce prompt."- )- assert get_context_length_from_provider_error(msg, 131072) == 32768def test_output_cap_message_is_not_a_context_limit(self):"""An output-cap error must never be cached as the context window (salvage #106769):@@ -1744,10 +1473,6 @@ class TestParseContextLimitFromError:) == 32768----# =========================================================================# Persistent context length cache# =========================================================================@@ -1794,7 +1519,6 @@ class TestContextLengthCache:assert get_cached_context_length("test/model", "http://x") == 32768-def test_idempotent_save(self, tmp_path):cache_file = tmp_path / "cache.yaml"with patch("agent.model_metadata._get_context_cache_path", return_value=cache_file):@@ -1805,8 +1529,6 @@ class TestContextLengthCache:assert len(data["context_lengths"]) == 1--@patch("agent.model_metadata.fetch_model_metadata")def test_cached_value_takes_priority(self, mock_fetch, tmp_path):mock_fetch.return_value = {}@@ -1860,16 +1582,6 @@ class TestGrok43StaleCacheGuard:untouched."""- def test_stale_grok_4_3_detected_by_generic_guard(self):- from agent.model_metadata import _stale_pre_catalog_cache_entry- # 256,000 is the old grok-4 catch-all value — stale for grok-4.3 (1M).- assert _stale_pre_catalog_cache_entry("grok-4.3", 256_000)- assert _stale_pre_catalog_cache_entry("grok-4.3-latest", 256_000)- assert _stale_pre_catalog_cache_entry("xai/grok-4.3", 256_000)- # Correct/probed values are never dropped.- assert not _stale_pre_catalog_cache_entry("grok-4.3", 1_000_000)- # Non-listed slugs are untouched even at low cached values.- assert not _stale_pre_catalog_cache_entry("grok-4", 256_000)def test_stale_grok_4_3_dropped_and_reresolves_to_1m(self, tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))@@ -1899,50 +1611,6 @@ class TestGrok43StaleCacheGuard:assert ctx == 256_000, f"{slug} should stay 256000, got {ctx}"-class TestMuseSparkStaleCacheGuard:- """Muse Spark (1M window per OpenRouter live metadata) had no catalog- entry, so older builds persisted the 256K default fallback. The cache- guard must flag that stale value and keep correct/probed values."""-- def test_stale_muse_spark_detected_by_generic_guard(self):- from agent.model_metadata import _stale_pre_catalog_cache_entry- for slug in ("muse-spark-1.3", "meta/muse-spark-1.3-contributor", "muse-spark-1.2-contributor"):- assert _stale_pre_catalog_cache_entry(slug, 256_000), slug- assert not _stale_pre_catalog_cache_entry(slug, 1_048_576), slug---class TestGrok46StaleCacheGuard:- """Pre-catalog builds resolved grok-4.6 via the generic 'grok-4' catch-all- (256,000) and persisted it before the 500K catalog entry existed.- The step-1 cache guard must drop that stale value and re-resolve to 500K.- Official card: 500,000 context (docs.x.ai/developers/models/grok-4.6).- """-- def test_stale_grok_4_6_detected_by_generic_guard(self):- from agent.model_metadata import _stale_pre_catalog_cache_entry- # 256,000 is the old grok-4 catch-all value — stale for grok-4.6 (500K).- assert _stale_pre_catalog_cache_entry("grok-4.6", 256_000)- assert _stale_pre_catalog_cache_entry("xai/grok-4.6", 256_000)- assert _stale_pre_catalog_cache_entry("x-ai/grok-4.6", 256_000)- # Correct/probed values are never dropped.- assert not _stale_pre_catalog_cache_entry("grok-4.6", 500_000)- # Sibling slugs with correct catalog values are untouched.- assert not _stale_pre_catalog_cache_entry("grok-4", 256_000)- assert not _stale_pre_catalog_cache_entry("grok-4.5", 500_000)-- def test_stale_grok_4_6_dropped_and_reresolves_to_500k(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- import importlib- import agent.model_metadata as mm- importlib.reload(mm)- base = "https://api.x.ai/v1"- mm.save_context_length("grok-4.6", base, 256_000)- ctx = mm.get_model_context_length(- "grok-4.6", base_url=base, api_key="", provider="xai"- )- assert ctx == 500_000--class TestGenericPreCatalogStaleGuard:"""Generic _stale_pre_catalog_cache_entry guard: models whose catalogentry postdates a shorter catch-all (qwen3.6-plus, grok-4-fast,@@ -1960,42 +1628,14 @@ class TestGenericPreCatalogStaleGuard:# A 256K value for qwen3.6-plus is above the "qwen" catch-all —# could be a genuine probe result, so it is NOT dropped.assert not _stale_pre_catalog_cache_entry("qwen3.6-plus", 262_144)- # grok-4-fast / grok-4.20 (2M each): pre-catalog builds fell to 256K.- assert _stale_pre_catalog_cache_entry("grok-4-fast", 256_000)- assert _stale_pre_catalog_cache_entry("grok-4-fast-reasoning", 256_000)- assert _stale_pre_catalog_cache_entry("grok-4.20", 256_000)- assert not _stale_pre_catalog_cache_entry("grok-4-fast", 2_000_000)- assert not _stale_pre_catalog_cache_entry("grok-4.20", 2_000_000)# Sibling qwen slugs with legitimately small windows are untouched.assert not _stale_pre_catalog_cache_entry("qwen3-coder", 131_072)- # DeepSeek V4 / V4.1 Flash: 1M. Pre-entry builds persisted the 128K- # ``deepseek`` catch-all; a leftover must drop, a 1M value must not.- assert _stale_pre_catalog_cache_entry("deepseek-flash", 128_000)- assert _stale_pre_catalog_cache_entry("deepseek/deepseek-flash", 128_000)- assert _stale_pre_catalog_cache_entry("deepseek-v4-pro", 128_000)- assert not _stale_pre_catalog_cache_entry("deepseek-flash", 1_000_000)- assert not _stale_pre_catalog_cache_entry("deepseek", 128_000)def test_unknown_models_never_dropped(self):from agent.model_metadata import _stale_pre_catalog_cache_entryassert not _stale_pre_catalog_cache_entry("totally-unknown-model", 4096)assert not _stale_pre_catalog_cache_entry("minimax", 204_800)- def test_stale_qwen36_plus_dropped_and_reresolves(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- import importlib- import agent.model_metadata as mm- importlib.reload(mm)- base = "https://dashscope.aliyuncs.com/compatible-mode/v1"- mm.save_context_length("qwen3.6-plus", base, 131_072)- ctx = mm.get_model_context_length(- "qwen3.6-plus", base_url=base, api_key="", provider="alibaba"- )- # Stale 131,072 must be dropped; re-resolution lands on a 1M-class- # value (models.dev reports 1,000,000; hardcoded catalog 1,048,576 —- # either proves the pre-catalog leftover was invalidated).- assert ctx >= 1_000_000-class TestMoAContextLength:"""MoA virtual provider resolves context from the aggregator slot, not 256K default."""@@ -2040,8 +1680,6 @@ class TestMoAContextLength:assert moa_ctx == agg_ctx--def test_moa_custom_context_configures_compressor_threshold(self, tmp_path, monkeypatch):diff --git a/tests/agent/test_model_metadata_local_ctx.py b/tests/agent/test_model_metadata_local_ctx.pyindex 6ef9843096b..2492ca060af 100644--- a/tests/agent/test_model_metadata_local_ctx.py+++ b/tests/agent/test_model_metadata_local_ctx.py@@ -365,17 +365,6 @@ class TestContextLengthFromModelPayload:(context window) and max_tokens (max OUTPUT). The local probe must nottreat max_tokens as the context window."""- def test_prefers_max_input_tokens_over_max_tokens(self):- from agent.model_metadata import _context_length_from_model_payload-- # Real Anthropic /v1/models shape for claude-fable-5- payload = {- "type": "model",- "id": "claude-fable-5",- "max_input_tokens": 1_000_000,- "max_tokens": 128_000, # output cap, NOT context- }- assert _context_length_from_model_payload(payload) == 1_000_000def test_prefers_max_model_len_over_max_tokens(self):from agent.model_metadata import _context_length_from_model_payload@@ -893,63 +882,7 @@ class TestQueryLocalContextLengthMaxTokensNotContext:resp.json.return_value = bodyreturn resp- def test_models_list_prefers_context_size_over_max_tokens(self):- """/v1/models list: `context_size` wins over `max_tokens`."""- from agent.model_metadata import _query_local_context_length-- detail_resp = self._make_resp(404, {})- list_resp = self._make_resp(200, {- "data": [- {- "id": "deepseek-v4-flash",- "context_size": 1048576,- "max_input_tokens": 1048576,- "max_tokens": 393216,- }- ]- })-- call_count = [0]- def side_effect(url, **kwargs):- call_count[0] += 1- if call_count[0] == 1:- return detail_resp # /v1/models/deepseek-v4-flash- return list_resp # /v1/models-- client_mock = MagicMock()- client_mock.__enter__ = lambda s: client_mock- client_mock.__exit__ = MagicMock(return_value=False)- client_mock.post.return_value = self._make_resp(404, {})- client_mock.get.side_effect = side_effect- with patch("agent.model_metadata.detect_local_server_type", return_value=None), \- patch("httpx.Client", return_value=client_mock):- result = _query_local_context_length("deepseek-v4-flash", "http://127.0.0.1:8080/v1")-- assert result == 1048576-- def test_models_detail_prefers_max_input_tokens_over_max_tokens(self):- """/v1/models/{model} detail: `max_input_tokens` wins over `max_tokens`."""- from agent.model_metadata import _query_local_context_length-- detail_resp = self._make_resp(200, {- "id": "deepseek-v4-flash",- "context_size": 1048576,- "max_input_tokens": 1048576,- "max_tokens": 393216,- })-- client_mock = MagicMock()- client_mock.__enter__ = lambda s: client_mock- client_mock.__exit__ = MagicMock(return_value=False)- client_mock.post.return_value = self._make_resp(404, {})- client_mock.get.return_value = detail_resp-- with patch("agent.model_metadata.detect_local_server_type", return_value=None), \- patch("httpx.Client", return_value=client_mock):- result = _query_local_context_length("deepseek-v4-flash", "http://127.0.0.1:8080/v1")-- assert result == 1048576def test_models_list_max_tokens_only_falls_back(self):"""A model that ONLY exposes `max_tokens` (no real context key) still@@ -1113,4 +1046,5 @@ class TestDetectLocalServerTypeSkipsHostedProviders:with patch("httpx.Client", _Client), patch.object(mm, "_endpoint_blackholed", return_value=False), \patch.object(mm, "_local_probe_disk_get", return_value=None), patch.object(mm, "_local_probe_disk_put"):assert mm.detect_local_server_type(base_url) is None- assert len(calls) == expect_requests+ # Probe-count is an implementation detail; the contract is none vs some.+ assert bool(calls) == bool(expect_requests)diff --git a/tests/agent/test_model_streaming_config.py b/tests/agent/test_model_streaming_config.pyindex a29dafa5f38..aea97b41f1b 100644--- a/tests/agent/test_model_streaming_config.py+++ b/tests/agent/test_model_streaming_config.py@@ -37,14 +37,6 @@ def _build_agent(config):)-@patch("agent.process_bootstrap.OpenAI")-def test_streaming_false_seeds_disable_streaming(mock_openai):- mock_openai.return_value = MagicMock()- agent = _build_agent({"model": {**_BASE["model"], "streaming": False}})-- assert agent._disable_streaming is True--@patch("agent.process_bootstrap.OpenAI")def test_streaming_absent_keeps_streaming_enabled(mock_openai):mock_openai.return_value = MagicMock()@@ -53,14 +45,6 @@ def test_streaming_absent_keeps_streaming_enabled(mock_openai):assert agent._disable_streaming is False-@patch("agent.process_bootstrap.OpenAI")-def test_streaming_true_keeps_streaming_enabled(mock_openai):- mock_openai.return_value = MagicMock()- agent = _build_agent({"model": {**_BASE["model"], "streaming": True}})-- assert agent._disable_streaming is False--@patch("agent.process_bootstrap.OpenAI")def test_streaming_string_false_seeds_disable_streaming(mock_openai):"""String falsy values ('false', '0') must also disable streaming —@@ -71,14 +55,6 @@ def test_streaming_string_false_seeds_disable_streaming(mock_openai):assert agent._disable_streaming is True-@patch("agent.process_bootstrap.OpenAI")-def test_streaming_zero_seeds_disable_streaming(mock_openai):- mock_openai.return_value = MagicMock()- agent = _build_agent({"model": {**_BASE["model"], "streaming": 0}})-- assert agent._disable_streaming is True--@patch("agent.process_bootstrap.OpenAI")def test_streaming_invalid_value_keeps_streaming_enabled(mock_openai):"""Unrecognized values warn and keep the safe default (streaming on),@@ -89,14 +65,6 @@ def test_streaming_invalid_value_keeps_streaming_enabled(mock_openai):assert agent._disable_streaming is False-@patch("agent.process_bootstrap.OpenAI")-def test_missing_model_section_keeps_streaming_enabled(mock_openai):- mock_openai.return_value = MagicMock()- agent = _build_agent({})-- assert agent._disable_streaming is False--@patch("agent.process_bootstrap.OpenAI")def test_legacy_string_model_section_does_not_crash(mock_openai):"""The top-level ``model`` key is a legacy string; init must not crash."""@@ -106,21 +74,6 @@ def test_legacy_string_model_section_does_not_crash(mock_openai):assert agent._disable_streaming is False-@patch("agent.process_bootstrap.OpenAI")-def test_streaming_false_applies_to_every_agent_built_from_config(mock_openai):- """Delegate children are constructed through the same init, so any agent- (parent or subagent) built under this config gets the escape hatch —- covering the reported failure surface."""- mock_openai.return_value = MagicMock()- cfg = {"model": {**_BASE["model"], "streaming": False}}-- first = _build_agent(cfg)- second = _build_agent(cfg)-- assert first._disable_streaming is True- assert second._disable_streaming is True--@patch("agent.process_bootstrap.OpenAI")def test_streaming_false_read_from_real_config_file(mock_openai):"""End-to-end: a real config.yaml in HERMES_HOME (sandboxed per-test bydiff --git a/tests/agent/test_models_dev.py b/tests/agent/test_models_dev.pyindex 4a20cffe76c..6028737c45e 100644--- a/tests/agent/test_models_dev.py+++ b/tests/agent/test_models_dev.py@@ -13,12 +13,10 @@ from agent.models_dev import (_explicit_model_override,_override_context_window,_override_for,- _NotModified,_validate_registry,fetch_models_dev,get_model_capabilities,get_model_info,- get_provider_info,lookup_models_dev_context,)@@ -95,24 +93,12 @@ SAMPLE_REGISTRY = {class TestProviderMapping:- def test_all_mapped_providers_are_strings(self):- for hermes_id, mdev_id in PROVIDER_TO_MODELS_DEV.items():- assert isinstance(hermes_id, str)- assert isinstance(mdev_id, str)-- def test_known_providers_mapped(self):- assert PROVIDER_TO_MODELS_DEV["anthropic"] == "anthropic"- assert PROVIDER_TO_MODELS_DEV["copilot"] == "github-copilot"- assert PROVIDER_TO_MODELS_DEV["stepfun"] == "stepfun"- assert PROVIDER_TO_MODELS_DEV["kilocode"] == "kilo"- assert PROVIDER_TO_MODELS_DEV["ai-gateway"] == "vercel"+def test_xai_oauth_uses_xai_catalog(self):assert PROVIDER_TO_MODELS_DEV["xai"] == "xai"assert PROVIDER_TO_MODELS_DEV["xai-oauth"] == "xai"- def test_unmapped_provider_not_in_dict(self):- assert "nous" not in PROVIDER_TO_MODELS_DEV@@ -441,28 +427,6 @@ class TestETagConditionalGet:assert result == SAMPLE_REGISTRYassert md._models_dev_cache_time > 0- @patch("agent.models_dev.requests.get")- def test_new_etag_persisted_after_successful_fetch(self, mock_get):- """A successful fetch with an ETag in the response persists it."""- import agent.models_dev as md-- response = MagicMock()- response.status_code = 200- response.json.return_value = SAMPLE_REGISTRY- response.headers = {"ETag": '"new-etag"'}- response.raise_for_status = MagicMock()- mock_get.return_value = response-- with patch.object(md, "_disk_cache_age_seconds", return_value=None), \- patch.object(md, "_load_disk_cache", return_value={}), \- patch.object(md, "_save_disk_cache") as mock_save, \- patch.object(md, "_load_etag", return_value=""), \- patch.object(md, "_save_etag") as mock_save_etag:- fetch_models_dev()-- # ETag rides along with the cache body into _save_disk_cache.- mock_save.assert_called_once_with(SAMPLE_REGISTRY, '"new-etag"')- mock_save_etag.assert_not_called()@patch("agent.models_dev.requests.get")def test_no_etag_header_sent_without_cached_etag(self, mock_get):@@ -658,28 +622,6 @@ class TestMirrorUrlOverride:call_args = mock_get.call_argsassert "mirror.example.com" in call_args.args[0]- @patch("agent.models_dev.requests.get")- def test_default_url_used_when_not_configured(self, mock_get):- """Without config override, the default models.dev URL is used."""- import agent.models_dev as md-- response = MagicMock()- response.status_code = 200- response.json.return_value = SAMPLE_REGISTRY- response.headers = {}- response.raise_for_status = MagicMock()- mock_get.return_value = response-- with patch.object(md, "_disk_cache_age_seconds", return_value=None), \- patch.object(md, "_load_disk_cache", return_value={}), \- patch.object(md, "_save_disk_cache"), \- patch.object(md, "_load_etag", return_value=""), \- patch.object(md, "_save_etag"), \- patch("hermes_cli.config.load_config_readonly", return_value={}):- fetch_models_dev()-- call_args = mock_get.call_args- assert "models.dev" in call_args.args[0]@patch("agent.models_dev.requests.get")def test_empty_url_falls_back_to_default(self, mock_get):@@ -740,16 +682,6 @@ class TestNoNetworkOnHotPaths:lookup_models_dev_context("anthropic", "claude-opus-4-6")mock_fetch.assert_called_once_with(allow_network=False)- @patch("agent.models_dev.requests.get")- def test_get_model_capabilities_explicit_network(self, mock_get):- """get_model_capabilities can opt into network."""- with patch("agent.models_dev.fetch_models_dev") as mock_fetch:- mock_fetch.return_value = CAPS_REGISTRY- get_model_capabilities("anthropic", "claude-sonnet-4", allow_network=True)- # allow_network=True uses the zero-arg call shape so the dozens of- # test sites that monkeypatch fetch_models_dev with zero-arg- # lambdas keep working.- mock_fetch.assert_called_once_with()# ---------------------------------------------------------------------------@@ -825,32 +757,7 @@ class TestGetModelCapabilities:assert caps is not Noneassert caps.supports_vision is False- def test_astra_builtin_metadata_fills_catalog_lag_without_listing_it(self):- """An explicitly discovered Astra remains fully described before models.dev catches up."""- with patch("agent.models_dev.fetch_models_dev", return_value={}):- caps = get_model_capabilities("openai", "gpt-6-astra")-- assert caps is not None- assert caps.supports_vision is True # the one thing _UNKNOWN_MODEL_BASE could not supply-- api_caps = get_model_capabilities("openai-api", "gpt-6-astra")- assert api_caps == caps-- def test_deepseek_flash_builtin_vision_fills_catalog_lag(self):- """Native Flash stays multimodal when models.dev is empty; Pro does not.-- Vendor docs: deepseek-flash accepts images, deepseek-v4-pro does not.- A global model.supports_vision pin would lie about Pro.- """- with patch("agent.models_dev.fetch_models_dev", return_value={}):- flash = get_model_capabilities("deepseek", "deepseek-flash")- alias = get_model_capabilities("deepseek", "deepseek-v4-flash")- pro = get_model_capabilities("deepseek", "deepseek-v4-pro")- assert flash is not None and flash.supports_vision is True- assert flash.context_window == 1_000_000- assert alias is not None and alias.supports_vision is True- assert pro is Nonedef test_metadata_only_override_on_custom_provider_leaves_capabilities_unknown(self):"""A custom provider's ``model_overrides`` entry that only corrects ``context_window`` must not@@ -897,7 +804,7 @@ class TestCatalogProviderAlias:ctx = lookup_models_dev_context("925llm", "deepseek-chat")info = get_model_info("925llm", "deepseek-chat")- assert builtin is not None and builtin.supports_vision is True and builtin.max_output_tokens == 384_000+ assert builtin is not None and builtin.supports_vision is Trueassert prefixed == builtinassert catalog is not None and catalog.supports_vision is False and catalog.max_output_tokens == 8000assert ctx == 128000@@ -1356,7 +1263,6 @@ class TestModelOverrides:"""import importlib- import agent.models_dev as mdimport hermes_cli.config as hchome = tmp_path / "hermes"diff --git a/tests/agent/test_models_dev_meta_mapping.py b/tests/agent/test_models_dev_meta_mapping.pydeleted file mode 100644index 328c5adb3ed..00000000000--- a/tests/agent/test_models_dev_meta_mapping.py+++ /dev/null@@ -1,14 +0,0 @@-"""Muse Spark hosts map to the right models.dev provider id (context/pricing)."""--from agent.models_dev import PROVIDER_TO_MODELS_DEV---def test_meta_ai_maps_to_meta():- assert PROVIDER_TO_MODELS_DEV.get("meta-ai") == "meta"- assert PROVIDER_TO_MODELS_DEV.get("meta") == "meta"---def test_opencode_free_is_no_longer_mapped():- # The keyless OpenCode free tier was removed (OpenCode 403s anonymous access outside its- # own client), so `opencode-free` must not claim a models.dev catalog anymore.- assert "opencode-free" not in PROVIDER_TO_MODELS_DEVdiff --git a/tests/agent/test_moonshot_schema.py b/tests/agent/test_moonshot_schema.pyindex 5fc50dd905b..023797052f1 100644--- a/tests/agent/test_moonshot_schema.py+++ b/tests/agent/test_moonshot_schema.py@@ -191,11 +191,6 @@ class TestTopLevelGuarantees:assert sanitize_moonshot_tool_parameters("garbage") == emptyassert sanitize_moonshot_tool_parameters([]) == empty- def test_non_object_top_level_coerced(self):- params = {"type": "string"}- out = sanitize_moonshot_tool_parameters(params)- assert out["type"] == "object"- assert "properties" in outdef test_does_not_mutate_input(self):params = {@@ -325,21 +320,6 @@ class TestEnumNullStripping:"""Rule 3: Moonshot rejects null/empty-string inside enum arrays."""- def test_enum_empty_string_stripped(self):- """enum containing empty string '' must have it removed for Moonshot."""- params = {- "type": "object",- "properties": {- "db_type": {- "type": "string",- "enum": ["mysql", "postgresql", ""],- },- },- }- out = sanitize_moonshot_tool_parameters(params)- db_type = out["properties"]["db_type"]- assert "" not in db_type["enum"]- assert db_type["enum"] == ["mysql", "postgresql"]def test_dataslayer_db_type_after_mcp_normalize(self):diff --git a/tests/agent/test_multimodal_interim.py b/tests/agent/test_multimodal_interim.pyindex add0102a4d9..ba8b660223d 100644--- a/tests/agent/test_multimodal_interim.py+++ b/tests/agent/test_multimodal_interim.py@@ -28,7 +28,6 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom unittest.mock import MagicMock-import pytest# ---------------------------------------------------------------------------@@ -116,17 +115,6 @@ class TestInterimVisibleTextMultimodal:visible = AIAgent._interim_assistant_visible_text(agent, tool_msg)assert isinstance(visible, str)- def test_tool_message_yields_no_interim_text(self):- """Tool messages carry no user-facing interim text (role guard)."""- from run_agent import AIAgent-- agent = _make_agent()- tool_msg = _vision_tool_result("some description")- visible = AIAgent._interim_assistant_visible_text(agent, tool_msg)- # No codex_message_items -> no commentary -> flattened content is still- # text, but it's a tool result, not assistant interim. The dedup guard- # (role == "assistant") excludes it from ever being emitted.- assert isinstance(visible, str)def test_assistant_list_content_flattened(self):"""An assistant message with list content yields flattened visible text."""@@ -150,40 +138,4 @@ class TestInterimVisibleTextMultimodal:# ----------------------------------------------------------------------------class TestDuplicatePreviousInterimDedup:- def test_previous_tool_list_content_safe_and_not_duplicate(self):- """Replicates conversation_loop.py:4871-4885.-- ``previous_msg`` is a tool message with a *list* content (the exact- crash shape from #66267). The dedup must compute- ``previous_interim_visible`` without raising and must NOT mark the- current assistant message as a duplicate of a tool message.- """- from run_agent import AIAgent-- agent = _make_agent()- assistant_msg = {- "role": "assistant",- "content": "Let me check the repo first.",- "finish_reason": "incomplete",- }- previous_msg = _vision_tool_result("some tool output")-- current_interim_visible = AIAgent._interim_assistant_visible_text(agent, assistant_msg)- previous_interim_visible = (- AIAgent._interim_assistant_visible_text(agent, previous_msg)- if isinstance(previous_msg, dict)- else ""- )- duplicate_previous_interim = (- bool(current_interim_visible)- and isinstance(previous_msg, dict)- and previous_msg.get("role") == "assistant"- and previous_msg.get("finish_reason") == "incomplete"- and previous_interim_visible == current_interim_visible- )-- # Must not raise, and a tool message can never be a duplicate source.- assert isinstance(previous_interim_visible, str)- assert duplicate_previous_interim is Falsediff --git a/tests/agent/test_multimodal_tool_content_recovery.py b/tests/agent/test_multimodal_tool_content_recovery.pyindex 3bda896542d..2a9bfa00878 100644--- a/tests/agent/test_multimodal_tool_content_recovery.py+++ b/tests/agent/test_multimodal_tool_content_recovery.py@@ -52,10 +52,6 @@ def _make_agent(provider: str = "xiaomi", model: str = "mimo-v2.5"):class TestStripImagePartsHelper:- def test_no_messages_returns_false(self):- agent = _make_agent()- assert agent._try_strip_image_parts_from_tool_messages([]) is False- assert agent._try_strip_image_parts_from_tool_messages(None) is Falsedef test_tool_message_with_string_content_unchanged(self):@@ -153,19 +149,6 @@ class TestToolResultContentShortCircuit:- def test_missing_cache_attribute_falls_through(self, monkeypatch):- """Agents built via ``object.__new__`` without calling ``__init__``- must not crash — the cache attribute may be absent. Xiaomi still- gets a text summary because the provider profile says so."""- agent = _make_agent(provider="xiaomi", model="mimo-v2.5")- # Deliberately do not assign _no_list_tool_content_models.- monkeypatch.setattr(agent, "_model_supports_vision", lambda: True)- out = agent._tool_result_content_for_active_model(- "computer_use", self._multimodal_result()- )- # Xiaomi proactively downgrades regardless of cache state.- assert isinstance(out, str)- assert "data:image" not in out# ─── Classifier ──────────────────────────────────────────────────────────────diff --git a/tests/agent/test_native_compaction.py b/tests/agent/test_native_compaction.pyindex 1328ce4578e..a6fc0197115 100644--- a/tests/agent/test_native_compaction.py+++ b/tests/agent/test_native_compaction.py@@ -257,20 +257,6 @@ class TestRejectionMatcher:)-class TestConfigCoercion:- def test_false_like_strings_stay_disabled(self, monkeypatch):- from utils import is_truthy_value-- for raw in ("false", "off", "no", "0", "", "FALSE", " Off "):- assert not is_truthy_value(raw, False), raw-- def test_true_like_strings_enable(self):- from utils import is_truthy_value-- for raw in ("true", "1", "yes", "on", "TRUE"):- assert is_truthy_value(raw, False), raw--class TestWirePlumbing:"""context_management flows through build_kwargs and both preflights."""@@ -425,39 +411,13 @@ class TestResponseCapture:class TestAgentInitConfig:- def test_defaults_off_and_automatic_threshold(self, monkeypatch):- from run_agent import AIAgent-- agent = AIAgent(- api_key="test-key",- base_url="https://api.openai.com/v1",- api_mode="codex_responses",- model="gpt-5.6",- provider="openai-api",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- enabled_toolsets=[],- )- assert agent.codex_responses_native_compaction is False- assert agent.codex_responses_compact_threshold is None- def test_public_config_default_selects_automatic_threshold(self):- from hermes_cli.config import DEFAULT_CONFIG-- assert (- DEFAULT_CONFIG["compression"]["codex_responses_compact_threshold"] is None- )@pytest.mark.parametrize(("threshold_yaml", "configured", "resolved"),[(None, None, 756_808),- ("null", None, 756_808),("200000", 200_000, 200_000),- ("true", None, 756_808),- ("-5", None, 756_808),- ("1.5", None, 756_808),('"bad"', None, 756_808),],)@@ -494,40 +454,6 @@ class TestAgentInitConfig:{"type": "compaction", "compact_threshold": resolved}]- def test_kwargs_have_no_context_management_by_default(self):- from run_agent import AIAgent-- agent = AIAgent(- api_key="test-key",- base_url="https://api.openai.com/v1",- api_mode="codex_responses",- model="gpt-5.6",- provider="openai-api",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- enabled_toolsets=[],- )- kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}])- assert "context_management" not in kwargs-- def test_kwargs_include_field_when_enabled_on_eligible_route(self):- from run_agent import AIAgent-- agent = AIAgent(- api_key="test-key",- base_url="https://api.openai.com/v1",- api_mode="codex_responses",- model="gpt-5.6",- provider="openai-api",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- enabled_toolsets=[],- )- agent.codex_responses_native_compaction = True- kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}])- assert isinstance(kwargs.get("context_management"), list)def test_kwargs_omit_field_for_ineligible_model_even_when_enabled(self):from run_agent import AIAgentdiff --git a/tests/agent/test_native_compaction_nontext_retention.py b/tests/agent/test_native_compaction_nontext_retention.pyindex b4720256d34..7fbf681b4cf 100644--- a/tests/agent/test_native_compaction_nontext_retention.py+++ b/tests/agent/test_native_compaction_nontext_retention.py@@ -1,7 +1,7 @@"""Regression coverage for image-only user content across native compaction."""from agent.codex_responses_adapter import _chat_messages_to_responses_input-from agent.native_compaction import _extract_item_text, prune_pre_checkpoint_items+from agent.native_compaction import prune_pre_checkpoint_items_IMAGE_URL = "data:image/png;base64,AAAA"@@ -10,11 +10,6 @@ _RESPONSES_IMAGE_PART = {"type": "input_image", "image_url": _IMAGE_URL}_CHECKPOINT = {"type": "compaction", "encrypted_content": "blob_cp"}-def test_extract_item_text_remains_text_only_for_image_content():- image_only = {"content": [_RESPONSES_IMAGE_PART]}-- assert _extract_item_text(image_only) is None- assert _extract_item_text({"content": []}) is Nonedef test_image_only_user_message_survives_pre_checkpoint_pruning_verbatim():diff --git a/tests/agent/test_native_preflight_estimate.py b/tests/agent/test_native_preflight_estimate.pyindex ac542c57494..b2f0b19c0b9 100644--- a/tests/agent/test_native_preflight_estimate.py+++ b/tests/agent/test_native_preflight_estimate.py@@ -66,9 +66,6 @@ def test_returns_none_when_native_compaction_is_disabled():assert estimate_native_responses_preflight_tokens(agent, _history_with_checkpoint()) is None-def test_returns_none_when_model_is_outside_gpt56_family():- agent = _codex_agent(model="gpt-5.2")- assert estimate_native_responses_preflight_tokens(agent, _history_with_checkpoint()) is Nonedef test_pruned_estimate_is_far_below_durable_transcript():diff --git a/tests/agent/test_non_stream_stale_timeout.py b/tests/agent/test_non_stream_stale_timeout.pyindex 047cc377422..b7730fc1bbe 100644--- a/tests/agent/test_non_stream_stale_timeout.py+++ b/tests/agent/test_non_stream_stale_timeout.py@@ -70,17 +70,6 @@ def test_estimator_empty_inputs():# ── default base + tier scaling ────────────────────────────────────────────-def test_default_base_is_90s(monkeypatch, tmp_path):- """Default base stale timeout dropped from 300s to 90s (May 2026)."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- (tmp_path / ".env").write_text("", encoding="utf-8")- monkeypatch.delenv("HERMES_API_CALL_STALE_TIMEOUT", raising=False)- _write_config(tmp_path, "")-- agent = _make_agent(tmp_path)- base, implicit = agent._resolved_api_call_stale_timeout_base()- assert base == 90.0- assert implicit is True@@ -118,5 +107,6 @@ providers:def test_openai_codex_stale_floor_tiers():from agent.chat_completion_helpers import openai_codex_stale_timeout_floor- assert openai_codex_stale_timeout_floor(55_000) == 900.0- assert openai_codex_stale_timeout_floor(120_000) == 1200.0+ # Contract, not literals: a bigger request never gets a shorter floor.+ small, large = openai_codex_stale_timeout_floor(55_000), openai_codex_stale_timeout_floor(120_000)+ assert 0 < small <= largediff --git a/tests/agent/test_notice_spine.py b/tests/agent/test_notice_spine.pyindex 2587cc73318..0e0cab2edd4 100644--- a/tests/agent/test_notice_spine.py+++ b/tests/agent/test_notice_spine.py@@ -9,10 +9,8 @@ Covers:"""from __future__ import annotations-import inspectfrom unittest.mock import patch-import pytestfrom agent.credits_tracker import AgentNoticefrom run_agent import AIAgent@@ -33,21 +31,6 @@ def _bare_agent() -> AIAgent:return agent-class TestEmitNotice:- def test_emit_notice_calls_callback_with_exact_notice(self):- agent = _bare_agent()- received = []- notice = AgentNotice(- text="credits 90% used",- level="warn",- kind="sticky",- ttl_ms=None,- key="credits.warn90",- id="n1",- )- agent.notice_callback = received.append- agent._emit_notice(notice)- assert received == [notice]@@ -58,10 +41,6 @@ class TestEmitNotice:# ── B. Constructor / init_agent signature threading ─────────────────────────-class TestSignatureThreading:- def test_agent_init_exposes_notice_callback(self):- sig = inspect.signature(AIAgent.__init__)- assert "notice_callback" in sig.parameters@@ -101,28 +80,6 @@ class TestAgentCbsNoticeBinding:},)- def test_notice_callback_payload_is_full_snake_case_dict(self):- """All six snake_case fields must be present in the payload — no extras,- no camelCase variants."""- from tui_gateway import server-- captured = []- with patch("tui_gateway.server._emit", side_effect=lambda *a: captured.append(a)):- cbs = server._agent_cbs("sid123")- cbs["notice_callback"](- AgentNotice(- text="credits 90% used",- level="warn",- kind="sticky",- ttl_ms=None,- key="credits.warn90",- id="n1",- )- )-- assert len(captured) == 1- _event_type, _sid, payload = captured[0]- assert set(payload.keys()) == {"text", "level", "kind", "ttl_ms", "key", "id"}diff --git a/tests/agent/test_nous_429_fallback_reentry.py b/tests/agent/test_nous_429_fallback_reentry.pydeleted file mode 100644index c0cfad8ec5f..00000000000--- a/tests/agent/test_nous_429_fallback_reentry.py+++ /dev/null@@ -1,40 +0,0 @@-"""Regression guard: a genuine Nous 429 must re-enter the retry loop so the-top-of-loop Nous rate-limit guard can activate the fallback chain.--Bug (found in the #44061 audit): the genuine-rate-limit branch in-``agent/conversation_loop.py`` set ``retry_count = max_retries`` then-``continue``-d, intending the top-of-loop guard to "handle fallback or bail-cleanly". But the loop condition is ``while retry_count < max_retries`` —-setting retry_count equal to max_retries makes the condition False-immediately, so the guard NEVER runs. No fallback activation, no clean-rate-limit message: the turn dies with the generic retry-exhaustion error.--The fix sets ``retry_count = max(0, max_retries - 1)`` so the loop body runs-exactly once more: the guard sees the breaker state recorded by-``record_nous_rate_limit()`` moments earlier and either activates a fallback-provider (resetting retry_count) or returns the explicit rate-limit failure.-"""-from __future__ import annotations--import inspect-import re---def _loop_reenters(retry_count: int, max_retries: int) -> bool:- """Mirror of the ``while retry_count < max_retries`` loop condition."""- return retry_count < max_retries---class TestGenuineNous429ReentersLoop:- """The assignment used by the genuine-429 branch must leave the loop- condition True so the top-of-loop guard gets a chance to run."""-- def test_fixed_assignment_reenters_for_typical_max_retries(self):- for max_retries in (1, 2, 3, 5, 10):- retry_count = max(0, max_retries - 1)- assert _loop_reenters(retry_count, max_retries), (- f"max_retries={max_retries}: guard would never run"- )---diff --git a/tests/agent/test_nous_credits_snapshot.py b/tests/agent/test_nous_credits_snapshot.pyindex d0681e43202..49679c6d7d9 100644--- a/tests/agent/test_nous_credits_snapshot.py+++ b/tests/agent/test_nous_credits_snapshot.py@@ -39,23 +39,15 @@ def test_healthy():assert snap.available is Trueassert snap.plan == "Pro"assert snap.provider == "nous"- assert snap.title == "Nous credits"blob = "\n".join(_all_lines(snap))assert "$18.00" in blobassert "$12.34" in blobassert "$30.34" in blob- assert "Renews: 2026-07-01" in blob- assert "/billing" in blob+ assert "2026-07-01" in blob# money-rule: magnitudes-only, never a percentageassert "%" not in blob------def test_logged_out():info = _account(logged_in=False,@@ -65,13 +57,3 @@ def test_logged_out():),)assert build_nous_credits_snapshot(info) is None---def test_none():- assert build_nous_credits_snapshot(None) is None------diff --git a/tests/agent/test_nous_fallback_unavailable.py b/tests/agent/test_nous_fallback_unavailable.pyindex 62087c59d4c..1ef8cff6257 100644--- a/tests/agent/test_nous_fallback_unavailable.py+++ b/tests/agent/test_nous_fallback_unavailable.py@@ -61,25 +61,6 @@ class TestNousFallbackLocalAvailability:assert activated is Trueassert agent.model == "gpt-5.5"- def test_nous_unavailable_not_retried_in_same_session(self):- """After Nous is skipped once, subsequent activations continue further."""- agent = _make_agent(- fallback_model=[- {"provider": "nous", "model": "anthropic/claude-sonnet-4.6"},- {"provider": "openai-codex", "model": "gpt-5.5"},- ]- )- with patch(- "hermes_cli.auth.get_provider_auth_state",- return_value={},- ):- agent._try_activate_fallback(None)- key = (- "nous",- "anthropic/claude-sonnet-4.6",- "",- )- assert key in getattr(agent, "_unavailable_fallback_keys", set())def test_present_nous_token_allows_activation(self):"""Nous is considered when token material exists."""diff --git a/tests/agent/test_nous_key_pre_expiry_adoption.py b/tests/agent/test_nous_key_pre_expiry_adoption.pyindex 82be617ee7f..326caf574a6 100644--- a/tests/agent/test_nous_key_pre_expiry_adoption.py+++ b/tests/agent/test_nous_key_pre_expiry_adoption.py@@ -7,7 +7,7 @@ started the proactive keepalive, and nothing adopted a fresh key before a requesimport base64import jsonimport time-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom agent.client_lifecycle import ClientLifecycleMixin@@ -84,6 +84,10 @@ def test_keepalive_thread_starts_when_an_agent_routes_to_nous(monkeypatch, tmp_pmonkeypatch.setenv("HERMES_HOME", str(tmp_path / "hh"))started = []monkeypatch.setattr("hermes_cli.nous_auth_keepalive.start_nous_auth_keepalive", lambda: started.append(1))+ # Tool discovery and the SDK client are irrelevant to the keepalive wiring and dominate runtime.+ monkeypatch.setattr("model_tools.get_tool_definitions", lambda *a, **k: [])+ monkeypatch.setattr("model_tools.check_toolset_requirements", lambda *a, **k: {})+ monkeypatch.setattr("agent.process_bootstrap.OpenAI", MagicMock())AIAgent(api_key="k", base_url="https://inference-api.nousresearch.com/v1", provider="nous",model="anthropic/claude-fable-5.1", quiet_mode=True, skip_context_files=True, skip_memory=True)assert started == [1]diff --git a/tests/agent/test_nous_oauth_401_guidance.py b/tests/agent/test_nous_oauth_401_guidance.pydeleted file mode 100644index 0dba4c1868a..00000000000--- a/tests/agent/test_nous_oauth_401_guidance.py+++ /dev/null@@ -1,58 +0,0 @@-"""Tests for the Nous OAuth 401 actionable-guidance branch in-``agent.turn_recovery._print_nonretryable_auth_guidance`` (called from the-``nonretryable_client_error_result`` terminal branch).--Source-inspection style (matches ``test_gemini_fast_fallback.py``): we assert-that the guidance strings exist in the function body so that the user-facing-hint cannot be silently removed by a future refactor.--Regression context: ashh hit a Nous 401 (OAuth token expired / portal said-account out of credits) plus a model slug ``deepseek/deepseek-v4-flash:free``-that's OpenRouter syntax, not a Nous catalog name. The previous guidance-branch only covered ``openai-codex`` and ``xai-oauth``; ``nous`` fell through-to a generic "Your API key was rejected... run hermes setup" message, which is-the wrong advice for a pure-OAuth provider.-"""-from __future__ import annotations--import inspect--from agent import turn_recovery---def test_nous_provider_is_in_oauth_401_set():- """The provider-set gate that selects OAuth-specific guidance must- include ``nous`` alongside ``openai-codex`` and ``xai-oauth``.- """- source = inspect.getsource(turn_recovery._print_nonretryable_auth_guidance)-- # Be flexible about set element ordering — assert all three are listed- # near each other in the gating expression.- assert "\"openai-codex\"" in source- assert "\"xai-oauth\"" in source- assert "\"nous\"" in source-- # And the gate string itself must mention all three so future refactors- # that split nous off into its own gate still get caught.- needle = "provider in {\"openai-codex\", \"xai-oauth\", \"nous\"}"- assert needle in source, (- "Expected nous to be co-gated with the other OAuth providers in the "- "actionable-401-guidance branch of _print_nonretryable_auth_guidance."- )---def test_nous_401_guidance_strings_present():- """User-facing remediation strings for Nous OAuth 401s must exist."""- source = inspect.getsource(turn_recovery._print_nonretryable_auth_guidance)-- # Must tell the user it's an OAuth token problem, NOT an API key problem- # (Nous Portal has no API key path — auth_type=oauth_device_code only).- assert "Nous Portal OAuth token was rejected" in source-- # Must give a concrete re-auth command, not a generic "hermes setup".- assert "hermes portal" in source-- # Must point at the portal so users can check account/credit status.- assert "portal.nousresearch.com" in source--diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.pyindex 38014c27375..89a93d0c963 100644--- a/tests/agent/test_nous_rate_guard.py+++ b/tests/agent/test_nous_rate_guard.py@@ -108,20 +108,8 @@ class TestClearNousRateLimit:assert nous_rate_limit_remaining() is Noneassert not os.path.exists(_state_path())- def test_clear_when_no_file(self, rate_guard_env):- from agent.nous_rate_guard import clear_nous_rate_limit- # Should not raise- clear_nous_rate_limit()---class TestFormatRemaining:- """Test human-readable duration formatting."""-- def test_seconds(self):- from agent.nous_rate_guard import format_remaining- assert format_remaining(30) == "30s"@@ -170,16 +158,6 @@ class TestAuxiliaryClientIntegration:result = aux._try_nous()assert result == (None, None)- def test_try_nous_works_when_not_rate_limited(self, rate_guard_env, monkeypatch):- import agent.auxiliary_client as aux-- # No rate limit recorded — _try_nous should proceed normally- # (will return None because no real creds, but won't be blocked- # by the rate guard)- monkeypatch.setattr(aux, "_read_nous_auth", lambda: None)- monkeypatch.setattr(aux, "_resolve_nous_runtime_api", lambda **kw: None)- result = aux._try_nous()- assert result == (None, None)class TestIsGenuineNousRateLimit:@@ -316,16 +294,6 @@ class TestWelcomeRouteCopy:assert "Nous Portal" not in expectedassert buffered == [f"⏳ {expected} Trying fallback..."]- def test_a_non_welcome_route_keeps_todays_sentence(self, monkeypatch):- verdict, buffered, statuses = self._drive_guard(- "https://inference-api.nousresearch.com/v1", monkeypatch- )-- expected = "Your Nous account has hit its rate limit; it resets in 10m."- assert verdict.action == "return"- assert statuses == [f"⏳ {expected}"]- assert verdict.result["final_response"].startswith(f"⏳ {expected}\n\n")- assert buffered == [f"⏳ {expected} Trying fallback..."]class TestRateGuardStateEncoding:diff --git a/tests/agent/test_nous_welcome_client_contract.py b/tests/agent/test_nous_welcome_client_contract.pyindex ebb7183c161..f9e146fff8a 100644--- a/tests/agent/test_nous_welcome_client_contract.py+++ b/tests/agent/test_nous_welcome_client_contract.py@@ -137,9 +137,6 @@ class TestRefusalCopy:terminal = anon_auth.welcome_refusal_copy(refusal, model="gpt-5", in_chat=False)assert "`hermes auth upgrade`" in terminal and "/login" not in terminal- def test_capacity_copy_carries_the_retry(self):- refusal = anon_auth.parse_welcome_refusal({"reason": "at_capacity", "retry_after": 30})- assert "try again in about a minute" in anon_auth.welcome_refusal_copy(refusal)@pytest.mark.parametrize("copy_fn, args", [(anon_auth.welcome_refusal_copy, ({"reason": r},)) for r in sorted(anon_auth.WELCOME_REFUSAL_REASONS)@@ -161,5 +158,5 @@ class TestTurnRecoveryGuidance:classified = SimpleNamespace(error_context={"welcome_refusal": {"reason": "model_not_free", "retry_after": 0, "alternates": []}})assert "nous/welcome" in _welcome_tier_guidance(classified, model="gpt-5", in_chat=True)classified = SimpleNamespace(error_context={"welcome_route": "tier_disabled"})- assert "switched off" in _welcome_tier_guidance(classified, model="", in_chat=True)+ assert _welcome_tier_guidance(classified, model="", in_chat=True)assert _welcome_tier_guidance(SimpleNamespace(error_context={}), model="", in_chat=True) == ""diff --git a/tests/agent/test_ollama_num_ctx.py b/tests/agent/test_ollama_num_ctx.pyindex 8d98f24b55a..b3eb9d15a02 100644--- a/tests/agent/test_ollama_num_ctx.py+++ b/tests/agent/test_ollama_num_ctx.py@@ -82,23 +82,9 @@ class TestQueryOllamaNumCtx:# Verify the post was called with stripped name (no "local:" prefix)call_args = mock_client.post.call_args- assert call_args[1]["json"]["name"] == "qwen2.5:7b" or call_args[0][1] is not None+ assert call_args.kwargs["json"]["name"] == "qwen2.5:7b"assert result == 32768- def test_handles_qwen2_architecture_key(self):- """Different model architectures use different key prefixes in model_info."""- show_data = {- "model_info": {"qwen2.context_length": 65536},- "parameters": "",- }- mock_ctx, _ = _mock_httpx_client(show_data)-- with patch("agent.model_metadata.detect_local_server_type", return_value="ollama"):- import httpx- with patch.object(httpx, "Client", return_value=mock_ctx):- result = query_ollama_num_ctx("qwen2.5:32b", "http://localhost:11434")-- assert result == 65536@@ -218,8 +204,7 @@ class TestFloorRefusalNamesTheLocalServerHonestly:with pytest.raises(ValueError) as exc:_build_agent({"agent": {}, "model": {}}, probed_ctx=32768, base_url="http://127.0.0.1:8422/v1")msg = str(exc.value)- assert "llama.cpp: -c 64000" in msg and "model.ollama_num_ctx" in msg- assert "Choose a model" not in msg+ assert "model.ollama_num_ctx" in msgdef test_hosted_refusal_keeps_context_length_advice(self):with pytest.raises(ValueError, match="model.context_length") as exc:diff --git a/tests/agent/test_onboarding.py b/tests/agent/test_onboarding.pyindex 514ada7f1ec..1193bd7d2cc 100644--- a/tests/agent/test_onboarding.py+++ b/tests/agent/test_onboarding.py@@ -6,16 +6,10 @@ import yamlfrom agent.onboarding import (BUSY_INPUT_FLAG,- OPENCLAW_RESIDUE_FLAG,TOOL_PROGRESS_FLAG,- busy_input_hint_cli,- busy_input_hint_gateway,detect_openclaw_residue,is_seen,mark_seen,- openclaw_residue_hint_cli,- tool_progress_hint_cli,- tool_progress_hint_gateway,)@@ -68,31 +62,6 @@ class TestMarkSeen:-class TestHintMessages:------ def test_busy_input_hint_cli_steer(self):- msg = busy_input_hint_cli("steer")- assert "/busy interrupt" in msg- assert "/busy queue" in msg- assert "steer" in msg.lower()--- def test_hints_are_not_empty(self):- for hint in (- busy_input_hint_gateway("queue"),- busy_input_hint_gateway("interrupt"),- busy_input_hint_gateway("steer"),- busy_input_hint_cli("queue"),- busy_input_hint_cli("interrupt"),- busy_input_hint_cli("steer"),- tool_progress_hint_gateway(),- tool_progress_hint_cli(),- ):- assert hint.strip()class TestRoundTrip:@@ -136,40 +105,11 @@ class TestDetectOpenclawResidue:-class TestOpenclawResidueHint:-- def test_hint_warns_cleanup_breaks_openclaw(self):- # Archiving the directory breaks OpenClaw for users still running it —- # the banner must flag that side effect.- msg = openclaw_residue_hint_cli().lower()- assert "openclaw will stop working" in msg or "stop working" in msg- def test_hint_not_empty(self):- assert openclaw_residue_hint_cli().strip()---class TestOpenclawResidueSeenFlag:- def test_flag_independent_of_other_flags(self, tmp_path):- cfg_path = tmp_path / "config.yaml"- mark_seen(cfg_path, BUSY_INPUT_FLAG)- loaded = yaml.safe_load(cfg_path.read_text())- assert is_seen(loaded, OPENCLAW_RESIDUE_FLAG) is False-- def test_flag_round_trips(self, tmp_path):- cfg_path = tmp_path / "config.yaml"- assert mark_seen(cfg_path, OPENCLAW_RESIDUE_FLAG) is True- loaded = yaml.safe_load(cfg_path.read_text())- assert is_seen(loaded, OPENCLAW_RESIDUE_FLAG) is Trueclass TestProfileBuildMode:- def test_default_is_ask(self):- from agent.onboarding import profile_build_mode-- assert profile_build_mode({}) == "ask"- assert profile_build_mode({"onboarding": {}}) == "ask"- assert profile_build_mode({"onboarding": {"profile_build": "ask"}}) == "ask"@@ -180,48 +120,7 @@ class TestProfileBuildMode:assert profile_build_mode({"onboarding": "nope"}) == "ask"-class TestProfileBuildDirective:- def test_directive_is_opt_in_and_consent_gated(self):- from agent.onboarding import profile_build_directive-- d = profile_build_directive()- # Must OFFER, not assume.- assert "OFFER" in d- # Must require consent before external lookups.- assert "consent" in d.lower()- # Must forbid silently reading connected accounts.- assert "silently" in d.lower()- # Must persist via the user-profile memory store.- assert 'target="user"' in d- # Must allow declining.- assert "decline" in d.lower()-- def test_directive_mentions_first_message(self):- from agent.onboarding import profile_build_directive-- assert "first message ever" in profile_build_directive()---class TestProfileBuildSeenFlag:- def test_flag_round_trips(self, tmp_path):- from agent.onboarding import PROFILE_BUILD_FLAG- cfg_path = tmp_path / "config.yaml"- assert mark_seen(cfg_path, PROFILE_BUILD_FLAG) is True- loaded = yaml.safe_load(cfg_path.read_text())- assert is_seen(loaded, PROFILE_BUILD_FLAG) is True-- def test_flag_independent_of_busy_input(self, tmp_path):- from agent.onboarding import PROFILE_BUILD_FLAG-- cfg_path = tmp_path / "config.yaml"- mark_seen(cfg_path, BUSY_INPUT_FLAG)- loaded = yaml.safe_load(cfg_path.read_text())- assert is_seen(loaded, PROFILE_BUILD_FLAG) is False-class TestProfileBuildConfigDefault:- def test_default_config_carries_ask(self):- from hermes_cli.config import DEFAULT_CONFIG- assert DEFAULT_CONFIG["onboarding"]["profile_build"] == "ask"diff --git a/tests/agent/test_oneshot.py b/tests/agent/test_oneshot.pyindex e3142c35217..6ffc1aa960d 100644--- a/tests/agent/test_oneshot.py+++ b/tests/agent/test_oneshot.py@@ -2,13 +2,10 @@from unittest.mock import MagicMock, patch-import pytestfrom agent.oneshot import (- PROMPT_TEMPLATES,render_template,run_oneshot,- _strip_code_fence,_truncate,)@@ -21,8 +18,7 @@ class TestRenderTemplate:"commit_message",{"diff": "diff --git a/x b/x\n+new", "recent_commits": "feat: a\nfix: b"},)- # Instructions describe the contract (conventional commits), not a snapshot.- assert "Conventional Commits" in instructions+ assert instructionsassert "diff --git a/x b/x" in userassert "feat: a" in user@@ -34,7 +30,6 @@ class TestRenderTemplate:_, plain = render_template("commit_message", {"diff": "d"})_, regen = render_template("commit_message", {"diff": "d", "avoid": "feat: prior"})assert "feat: prior" in regen- assert "do not repeat" in regenassert "feat: prior" not in plain@@ -71,13 +66,9 @@ class TestRunOneshot:class TestHelpers:- def test_truncate_under_limit_unchanged(self):- assert _truncate("short", 100) == "short"def test_truncate_over_limit_marks_truncation(self):out = _truncate("x" * 200, 50)assert out.endswith("…(truncated)")assert len(out) < 200- def test_strip_code_fence_without_fence_is_noop(self):- assert _strip_code_fence("plain text") == "plain text"diff --git a/tests/agent/test_openrouter_response_cache.py b/tests/agent/test_openrouter_response_cache.pyindex 3544fd07161..4915456b1f8 100644--- a/tests/agent/test_openrouter_response_cache.py+++ b/tests/agent/test_openrouter_response_cache.py@@ -14,20 +14,6 @@ class TestBuildOrHeaders:"""Test the build_or_headers() helper in agent/auxiliary_client.py."""---- def test_ttl_default(self):- """Default TTL (300) is included when cache is enabled."""- from agent.auxiliary_client import build_or_headers-- headers = build_or_headers(or_config={"response_cache": True, "response_cache_ttl": 300})- assert headers["X-OpenRouter-Cache-TTL"] == "300"-----def test_ttl_negative(self):"""Negative TTL is ignored."""from agent.auxiliary_client import build_or_headers@@ -36,7 +22,6 @@ class TestBuildOrHeaders:assert "X-OpenRouter-Cache-TTL" not in headers-def test_returns_fresh_dict(self):"""Each call returns a new dict so mutations don't leak."""from agent.auxiliary_client import build_or_headers@@ -67,10 +52,6 @@ class TestEnvVarOverrides:"""Test env var precedence over config.yaml for response caching."""----@pytest.mark.parametrize("ttl", ["0", "86401", "abc", "-1", "12.5"])def test_invalid_env_ttl_dropped(self, monkeypatch, ttl):"""Invalid TTL env values are ignored; cache still enabled without TTL."""@@ -101,17 +82,6 @@ class TestEnvVarOverrides:assert headers["X-OpenRouter-Cache"] == "true"assert headers["X-OpenRouter-Cache-TTL"] == "600"-class TestDefaultConfig:- """Verify the openrouter config section is in DEFAULT_CONFIG."""-- def test_openrouter_section_exists(self):- from hermes_cli.config import DEFAULT_CONFIG-- assert "openrouter" in DEFAULT_CONFIG- or_cfg = DEFAULT_CONFIG["openrouter"]- assert or_cfg["response_cache"] is True- assert or_cfg["response_cache_ttl"] == 300-# ---------------------------------------------------------------------------# _check_openrouter_cache_status@@ -130,7 +100,6 @@ class TestCheckOpenrouterCacheStatus:return agent-def test_no_header_is_noop(self):agent = self._make_agent()resp = SimpleNamespace(headers={})@@ -138,7 +107,6 @@ class TestCheckOpenrouterCacheStatus:assert getattr(agent, "_or_cache_hits", 0) == 0-def test_case_insensitive(self):agent = self._make_agent()resp = SimpleNamespace(headers={"x-openrouter-cache-status": "hit"})diff --git a/tests/agent/test_openrouter_silent_default_purge.py b/tests/agent/test_openrouter_silent_default_purge.pyindex a365473cffb..52887df40e6 100644--- a/tests/agent/test_openrouter_silent_default_purge.py+++ b/tests/agent/test_openrouter_silent_default_purge.py@@ -11,9 +11,7 @@ and env var when a credential is newly ingested."""import logging-import uuid-import pytestclass TestAuxiliaryOpenrouterDefaultIsFree:@@ -25,11 +23,6 @@ class TestAuxiliaryOpenrouterDefaultIsFree:"SKU — a paid built-in default is silent real spend (#81952)")- def test_builtin_default_matches_free_only_warning_recommendation(self):- """The default is the same SKU the free_only warning tells users to set."""- from agent import auxiliary_client as ac-- assert ac._OPENROUTER_MODEL == "nvidia/nemotron-3-ultra-550b-a55b:free"def test_user_configured_model_still_honored(self, monkeypatch):"""auxiliary.openrouter_model from config wins over the built-in default."""@@ -68,8 +61,6 @@ class TestEnvIngestionWarning:if r.levelno == logging.WARNING and "Ingested OPENROUTER_API_KEY" in r.getMessage()]assert warnings, "expected a WARNING for env->pool openrouter ingestion"- assert "OpenRouter spend" in warnings[0]- assert "hermes auth remove openrouter" in warnings[0]def test_warning_once_per_process(self, tmp_path, monkeypatch, caplog):self._fresh_home(tmp_path, monkeypatch)diff --git a/tests/agent/test_org_skill_namespace.py b/tests/agent/test_org_skill_namespace.pyindex ecdacfeb46b..397a347a692 100644--- a/tests/agent/test_org_skill_namespace.py+++ b/tests/agent/test_org_skill_namespace.py@@ -11,7 +11,6 @@ Covers the design agreed 2026-07-23 (bare-name first-class org skills):import json-import pytestfrom agent import skill_utils as skufrom agent.prompt_builder import _build_snapshot_entry@@ -181,12 +180,6 @@ class TestOrgSkillsAreEditableInPlace:assert result["success"] is True, result.get("error")assert "improved" in (d / "SKILL.md").read_text(encoding="utf-8")- def test_edit_tells_the_user_how_to_share_it_back(self, tmp_path, monkeypatch):- smt, _skills, _d = self._org_skill(tmp_path, monkeypatch)- result = smt._patch_skill("shared-x", "body", "improved")- # Without auto-propose the edit stays local, and the tool result must- # say so AND name the command — otherwise the improvement is stranded.- assert "propose" in (result.get("org_sharing") or "")def test_delete_is_still_refused(self, tmp_path, monkeypatch):smt, _skills, d = self._org_skill(tmp_path, monkeypatch)@@ -216,31 +209,7 @@ class TestOrgPullIsWiredIn:SITES exist, so the feature can't silently become dead code again."""- def test_session_startup_calls_maybe_pull_org_skills(self):- import pathlib- cli_src = (- pathlib.Path(__file__).resolve().parents[2] / "hermes_cli" / "cli_tui_runtime_mixin.py"- ).read_text(encoding="utf-8")- assert "maybe_pull_org_skills" in cli_src, (- "CLI session startup (hermes_cli/cli_tui_runtime_mixin.py) must call maybe_pull_org_skills() — "- "without a call site the org mirror is never populated and org "- "skills never load (the function being importable is not enough)."- )- # It must sit alongside the personal pull, not replace it.- assert "maybe_pull_skills" in cli_src-- def test_sync_pull_command_refreshes_org_mirror(self):- import pathlib-- main_src = (- pathlib.Path(__file__).resolve().parents[2]- / "hermes_cli"- / "main_platform_setup.py"- ).read_text(encoding="utf-8")- assert "maybe_pull_org_skills" in main_src, (- "`hermes sync pull` must also refresh the org mirror."- )def test_sync_status_exposes_org_state(self):from tools import skills_sync_client as ssc@@ -251,63 +220,8 @@ class TestOrgPullIsWiredIn:for key in ("org_available", "org_id", "org_role", "org_skills"):assert key in status, f"sync status must expose {key!r}"- def test_no_internal_jargon_in_user_facing_strings(self):- """User-visible help/errors must not leak internal design coordinates."""- import pathlib- import re-- root = pathlib.Path(__file__).resolve().parents[2]- targets = [- root / "hermes_cli" / "subcommands" / "sync.py",- root / "hermes_cli" / "subcommands" / "skills.py",- ]- banned = re.compile(- r"\(M[12]\)|\bHSP\b|HSP/1|§[0-9]|DEV-PHASE|hsp-1-contract"- )- for path in targets:- for i, line in enumerate(path.read_text(encoding="utf-8").split("\n"), 1):- if "help=" in line or "description=" in line:- assert not banned.search(line), (- f"{path.name}:{i} leaks internal jargon to users: {line.strip()}"- )---class TestSkillSyncIsOneCommand:- """Every Skill Sync verb lives under `hermes sync` for launch.-- The surface is deliberately encapsulated: one command to learn, one to- document, and top-level `sync` stays free of skill-management verbs that- belong elsewhere. `propose` in particular used to sit under `hermes- skills`, which split one feature across two commands.- """-- def _src(self, *parts):- import pathlib- return (- pathlib.Path(__file__).resolve().parents[2].joinpath(*parts)- ).read_text(encoding="utf-8")-- def test_propose_is_a_sync_subcommand(self):- sync_src = self._src("hermes_cli", "subcommands", "sync.py")- assert '"propose"' in sync_src, (- "`propose` must be a `hermes sync` subcommand."- )- def test_propose_is_not_under_skills(self):- skills_src = self._src("hermes_cli", "subcommands", "skills.py")- assert '"propose"' not in skills_src, (- "`propose` must NOT remain under `hermes skills` — Skill Sync is "- "one command for launch."- )-- def test_sync_usage_lists_propose(self):- main_src = self._src("hermes_cli", "main_platform_setup.py")- usage_start = main_src.index("usage: hermes sync ")- usage_block = main_src[usage_start : usage_start + 1400]- assert "propose" in usage_block, (- "`hermes sync` usage must list the propose verb."- )class TestLocalEditsSurviveOrgUpdates:diff --git a/tests/agent/test_outbound_stale_vision.py b/tests/agent/test_outbound_stale_vision.pyindex e87f4a0585e..30b9aad5aeb 100644--- a/tests/agent/test_outbound_stale_vision.py+++ b/tests/agent/test_outbound_stale_vision.py@@ -89,11 +89,6 @@ def _outbound_image_blocks(messages: list[dict]) -> int:class TestOutboundStaleVisionEviction:- def test_sanitize_alone_keeps_every_screenshot(self):- """The previous send chokepoint does not close #89296 by itself."""- history = _history_with_screenshots(5)- sanitized = sanitize_api_messages(history)- assert _image_bearing_tool_ids(sanitized) == [f"call_{i}" for i in range(5)]def test_nothing_is_evicted_below_the_provider_limit(self):"""The common case must be append-only: no rewrite, so the cached prefix survives."""diff --git a/tests/agent/test_output_cap_parsing.py b/tests/agent/test_output_cap_parsing.pyindex 8578f69595c..efcff90a0b6 100644--- a/tests/agent/test_output_cap_parsing.py+++ b/tests/agent/test_output_cap_parsing.py@@ -16,9 +16,6 @@ class TestParseOpenRouterOutputCap:assert parse_available_output_tokens_from_error(msg) == 10000---class TestParseCharBasedOutputCap:"""LM Studio / llama.cpp report context in tokens but prompt in characters.@@ -49,7 +46,6 @@ class TestParseCharBasedOutputCap:assert available + (chars + 2) // 3 <= ctx-class TestParseDashScopeOutputCap:"""DashScope / Alibaba Cloud (Qwen) reject an over-cap output request witha bounded range whose upper bound is the real max-output cap (#55546)."""@@ -66,9 +62,6 @@ class TestParseDashScopeOutputCap:"Range of max_tokens should be [1, 65536]")assert parse_available_output_tokens_from_error(msg) == 65536- def test_dashscope_range_arbitrary_bound(self):- msg = "Range of max_tokens should be [1, 8192]"- assert parse_available_output_tokens_from_error(msg) == 8192def test_dashscope_range_with_spaces(self):msg = "range of max_tokens should be [ 1 , 32768 ]"@@ -177,11 +170,6 @@ class TestParseVllmTokenBasedOutputCap:self._VLLM_MSG_REAL_INPUT) == 31072- def test_vllm_retry_fits_inside_window(self):- # The retried cap plus the reported input must fit in the window.- available = parse_available_output_tokens_from_error(self._VLLM_MSG)- assert available is not None- assert available + 65537 <= 131072def test_vllm_retry_converges(self):"""The retry sequence must reach a working cap in a few attempts.@@ -209,7 +197,6 @@ class TestParseVllmTokenBasedOutputCap:assert real_input + cap <= window, f"did not converge: cap={cap}"-class TestParseAdvertisedCeilingWordings:"""Azure and SGLang name the ceiling without any phrase the parser knew (#78405, #83521).Unrecognized, the 400 carried the bare ``max_tokens`` substring (or nothing at all) intodiff --git a/tests/agent/test_overflow_overhead_aware_tokens.py b/tests/agent/test_overflow_overhead_aware_tokens.pyindex 436a7cfbcde..0bd36902ef2 100644--- a/tests/agent/test_overflow_overhead_aware_tokens.py+++ b/tests/agent/test_overflow_overhead_aware_tokens.py@@ -1,26 +1,12 @@-"""Regression tests: overflow recovery handlers must pass overhead-aware token estimates.--PR fix (LCM issue 441): 413, context-overflow, and long-context-tier recovery handlers-were passing a messages-only token estimate to _compress_context instead of the-overhead-aware estimate_request_tokens_rough(api_messages, tools=agent.tools or None),-which includes tool schemas and system prompt overhead.--These tests assert that each recovery handler:-1. Calls estimate_request_tokens_rough with a non-None `tools` argument.-2. Passes the resulting value as approx_tokens to _compress_context.--The sentinel pattern (return_value=987654) makes the assertion unambiguous: if-approx_tokens==987654 the overhead-aware path was taken; any other value means the-handler used a different (likely messages-only) estimate.-"""+"""Anthropic long-context-tier (429) recovery: the retry diagnostics buffered+during recovery must flush correctly (muted vs. unmuted) on terminal failure."""import pytestfrom types import SimpleNamespace-from unittest.mock import MagicMock, patch, call+from unittest.mock import MagicMock, patchfrom run_agent import AIAgent-import run_agent# ---------------------------------------------------------------------------@@ -93,323 +79,25 @@ def _prefill():]-# ----------------------------------------------------------------------------# Sentinel: any value that could not coincidentally appear from a messages-only-# estimate during these tests.-# ---------------------------------------------------------------------------_SENTINEL_TOKENS = 987_654-# ----------------------------------------------------------------------------# 1. 413 / payload-too-large handler-# ------------------------------------------------------------------------------class TestHTTP413OverheadAwareTokens:- """The 413 recovery handler must call estimate_request_tokens_rough with- tools=agent.tools (non-None) and pass the result as approx_tokens."""-- def test_413_passes_overhead_aware_tokens_to_compress(self, agent):- """approx_tokens passed to _compress_context equals the overhead-aware estimate."""- err = Exception("Request entity too large")- err.status_code = 413- ok_resp = _mock_response(content="Success", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- return_value=_SENTINEL_TOKENS,- ) as mock_estimate,- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- result = agent.run_conversation("hello", conversation_history=_prefill())-- # _compress_context must have been called at least once for compression- mock_compress.assert_called()-- # Find the call that came from the 413 handler (approx_tokens=sentinel)- compress_kwargs_list = [c.kwargs for c in mock_compress.call_args_list]- sentinel_call = next(- (kw for kw in compress_kwargs_list if kw.get("approx_tokens") == _SENTINEL_TOKENS),- None,- )- assert sentinel_call is not None, (- f"No _compress_context call received approx_tokens={_SENTINEL_TOKENS}. "- f"Calls received approx_tokens values: "- f"{[kw.get('approx_tokens') for kw in compress_kwargs_list]}"- )-- def test_413_estimate_called_with_non_none_tools(self, agent):- """estimate_request_tokens_rough must receive tools=<non-None> in the 413 handler."""- err = Exception("Request entity too large")- err.status_code = 413- ok_resp = _mock_response(content="Success", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- estimate_calls = []-- def _capture_estimate(messages, tools=None):- estimate_calls.append({"messages": messages, "tools": tools})- return _SENTINEL_TOKENS-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- side_effect=_capture_estimate,- ),- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- agent.run_conversation("hello", conversation_history=_prefill())-- # At least one estimate call from the 413 handler must have non-None tools- handler_calls_with_tools = [c for c in estimate_calls if c["tools"] is not None]- assert handler_calls_with_tools, (- "estimate_request_tokens_rough was never called with non-None tools "- "during 413 recovery. All calls: "- + str([c["tools"] for c in estimate_calls])- )---# ----------------------------------------------------------------------------# 2. Context-overflow / input-too-large handler-# ------------------------------------------------------------------------------class TestContextOverflowOverheadAwareTokens:- """The context-overflow (input overflow) recovery handler must call- estimate_request_tokens_rough with tools=agent.tools and pass the result- as approx_tokens to _compress_context."""-- @staticmethod- def _make_context_overflow_error():- """Build a 400 error that the classifier routes to context_overflow."""- err = Exception(- "Error code: 400 - {'error': {'message': "- "\"This endpoint's maximum context length is 128000 tokens. "- "However, you requested about 200000 tokens. "- "Please reduce the length of the messages.\"}}"- )- err.status_code = 400- return err-- def test_context_overflow_passes_overhead_aware_tokens_to_compress(self, agent):- """approx_tokens passed to _compress_context equals the overhead-aware estimate."""- err = self._make_context_overflow_error()- ok_resp = _mock_response(content="Recovered", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- return_value=_SENTINEL_TOKENS,- ) as mock_estimate,- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- result = agent.run_conversation("hello", conversation_history=_prefill())-- mock_compress.assert_called()-- compress_kwargs_list = [c.kwargs for c in mock_compress.call_args_list]- sentinel_call = next(- (kw for kw in compress_kwargs_list if kw.get("approx_tokens") == _SENTINEL_TOKENS),- None,- )- assert sentinel_call is not None, (- f"No _compress_context call received approx_tokens={_SENTINEL_TOKENS}. "- f"Calls received approx_tokens values: "- f"{[kw.get('approx_tokens') for kw in compress_kwargs_list]}"- )-- def test_context_overflow_estimate_called_with_non_none_tools(self, agent):- """estimate_request_tokens_rough must receive tools=<non-None> in the context-overflow handler."""- err = self._make_context_overflow_error()- ok_resp = _mock_response(content="Recovered", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- estimate_calls = []-- def _capture_estimate(messages, tools=None):- estimate_calls.append({"messages": messages, "tools": tools})- return _SENTINEL_TOKENS-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- side_effect=_capture_estimate,- ),- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- agent.run_conversation("hello", conversation_history=_prefill())-- handler_calls_with_tools = [c for c in estimate_calls if c["tools"] is not None]- assert handler_calls_with_tools, (- "estimate_request_tokens_rough was never called with non-None tools "- "during context-overflow recovery. All calls: "- + str([c["tools"] for c in estimate_calls])- )-- def test_prompt_too_long_variant_passes_overhead_aware_tokens(self, agent):- """Anthropic 'prompt is too long' error also routes to context_overflow handler."""- err = Exception(- "Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', "- "'message': 'prompt is too long: 233153 tokens > 200000 maximum'}}"- )- err.status_code = 400- ok_resp = _mock_response(content="Recovered", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- return_value=_SENTINEL_TOKENS,- ),- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- result = agent.run_conversation("hello", conversation_history=_prefill())-- mock_compress.assert_called()- compress_kwargs_list = [c.kwargs for c in mock_compress.call_args_list]- sentinel_call = next(- (kw for kw in compress_kwargs_list if kw.get("approx_tokens") == _SENTINEL_TOKENS),- None,- )- assert sentinel_call is not None, (- f"'prompt is too long' path did not pass overhead-aware approx_tokens. "- f"Got: {[kw.get('approx_tokens') for kw in compress_kwargs_list]}"- )---# ----------------------------------------------------------------------------# 3. Anthropic long-context tier (429) handler-# ------------------------------------------------------------------------------class TestLongContextTierOverheadAwareTokens:- """The Anthropic long-context-tier 429 handler must call- estimate_request_tokens_rough with tools=agent.tools and pass the result- as approx_tokens to _compress_context."""-- @staticmethod- def _make_long_context_tier_error():- """Build a 429 'extra usage required for long context requests' error."""- err = Exception(- "Error code: 429 - {'error': {'type': 'rate_limit_error', "- "'message': 'Extra usage is required for long context requests. "- "Please enable extra usage in your account settings.'}}"- )- err.status_code = 429- return err-- def test_long_context_tier_passes_overhead_aware_tokens_to_compress(self, agent):- """approx_tokens passed to _compress_context equals the overhead-aware estimate."""- err = self._make_long_context_tier_error()- ok_resp = _mock_response(content="Recovered after context tier", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- return_value=_SENTINEL_TOKENS,- ),- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- result = agent.run_conversation("hello", conversation_history=_prefill())-- mock_compress.assert_called()- compress_kwargs_list = [c.kwargs for c in mock_compress.call_args_list]- sentinel_call = next(- (kw for kw in compress_kwargs_list if kw.get("approx_tokens") == _SENTINEL_TOKENS),- None,- )- assert sentinel_call is not None, (- f"Long-context-tier handler did not pass overhead-aware approx_tokens. "- f"Got: {[kw.get('approx_tokens') for kw in compress_kwargs_list]}"- )-- def test_long_context_tier_estimate_called_with_non_none_tools(self, agent):- """estimate_request_tokens_rough must receive tools=<non-None> in the long-context handler."""- err = self._make_long_context_tier_error()- ok_resp = _mock_response(content="Recovered", finish_reason="stop")- agent.client.chat.completions.create.side_effect = [err, ok_resp]-- estimate_calls = []-- def _capture_estimate(messages, tools=None):- estimate_calls.append({"messages": messages, "tools": tools})- return _SENTINEL_TOKENS-- with (- patch(- "agent.model_metadata.estimate_request_tokens_rough",- side_effect=_capture_estimate,- ),- patch.object(agent, "_compress_context") as mock_compress,- patch.object(agent, "_persist_session"),- patch.object(agent, "_save_trajectory"),- patch.object(agent, "_cleanup_task_resources"),- ):- mock_compress.return_value = (- [{"role": "user", "content": "compressed"}],- "compressed prompt",- )- agent.run_conversation("hello", conversation_history=_prefill())-- handler_calls_with_tools = [c for c in estimate_calls if c["tools"] is not None]- assert handler_calls_with_tools, (- "estimate_request_tokens_rough was never called with non-None tools "- "during long-context-tier recovery. All calls: "- + str([c["tools"] for c in estimate_calls])- )+def _make_long_context_tier_error():+ """Build a 429 'extra usage required for long context requests' error."""+ err = Exception(+ "Error code: 429 - {'error': {'type': 'rate_limit_error', "+ "'message': 'Extra usage is required for long context requests. "+ "Please enable extra usage in your account settings.'}}"+ )+ err.status_code = 429+ return err@pytest.mark.parametrize("muted", [False, True])def test_long_context_retry_carrier_survives_failure_flush(agent, muted, monkeypatch):from gateway.warning_notifications import DiagnosticTextagent._notification_config = {"display": {"suppress_warning_notifications": muted}}- err = TestLongContextTierOverheadAwareTokens._make_long_context_tier_error()+ err = _make_long_context_tier_error()agent.client.chat.completions.create.side_effect = [err, _mock_response(content="Recovered")]captured = []original = agent._buffer_retry_messagediff --git a/tests/agent/test_partial_stream_finish_reason.py b/tests/agent/test_partial_stream_finish_reason.pyindex 95a2f1cc8c7..05f9cc16676 100644--- a/tests/agent/test_partial_stream_finish_reason.py+++ b/tests/agent/test_partial_stream_finish_reason.py@@ -21,7 +21,6 @@ from unittest.mock import MagicMock, patchimport pytestfrom hermes_constants import PARTIAL_STREAM_STUB_ID, FINISH_REASON_LENGTH-from agent.conversation_loop import _get_continuation_prompt# ── Helpers (mirrors test_streaming.py) ────────────────────────────────────@@ -238,8 +237,6 @@ class TestCleanStreamEndMidToolCall:assert getattr(response, "_dropped_tool_names", None) == ["execute_code"]--# ── Clean stream-end before any argument byte arrives (#80498) ─────────────class TestCleanStreamEndBeforeAnyToolArgs:@@ -360,28 +357,6 @@ class TestMixedToolCallsOneDroppedOneComplete:# ── Length-continuation prompt branching ──────────────────────────────────-class TestLengthContinuationPromptBranching:- """When finish_reason=length, the continuation prompt that reaches the- model has to tell the truth: real truncation vs. network interruption- vs. dropped tool call (#31998). Three distinct prompts now exist."""-- def _simulate_branch(self, response_id: str, dropped_tools=None) -> str:- """Return the continuation prompt text the loop would inject for- a `finish_reason=length` response with the given id."""- is_partial = response_id == PARTIAL_STREAM_STUB_ID- return _get_continuation_prompt(is_partial, dropped_tools)-- def test_partial_stream_stub_uses_network_prompt(self):- prompt = self._simulate_branch(PARTIAL_STREAM_STUB_ID)- assert "network error mid-stream" in prompt- assert "output length limit" not in prompt--- def test_no_id_falls_through_to_length_prompt(self):- prompt = self._simulate_branch("")- assert "output length limit" in prompt--# ── Integration: live conversation loop ───────────────────────────────────@@ -585,7 +560,6 @@ class TestContentFilterStallActivatesFallback:assert result["completed"] is True-class TestEmptyPartialStreamStubNotPersisted:"""Regression for the session-poisoning bug hit with moonshotai/kimi-k3via OpenRouter (2026-07-20): a stream dropped mid-``write_file`` tool@@ -663,7 +637,6 @@ class TestEmptyPartialStreamStubNotPersisted:assert result["completed"] is True-class TestBuildAssistantMessageEmptyContentPad:"""Layer 2 was consolidated into the class owner: the builder storestextless turns AS-IS (no write-time pad — a pad here broke codex@@ -714,15 +687,6 @@ class TestBuildAssistantMessageEmptyContentPad:assert msg["tool_calls"]assert isinstance(msg["timestamp"], float)- def test_non_empty_content_unchanged(self):- from agent.chat_completion_helpers import build_assistant_message- from tests.agent.test_run_agent import _mock_assistant_msg-- agent = self._agent_for_builder()- msg = build_assistant_message(agent, _mock_assistant_msg(content="hi"), "stop")- assert msg["content"] == "hi"- assert isinstance(msg["timestamp"], float)-class TestSendTimeEmptyAssistantPad:"""Durable repair for ALREADY-poisoned persisted sessions: a partialdiff --git a/tests/agent/test_per_model_threshold_init_ordering.py b/tests/agent/test_per_model_threshold_init_ordering.pyindex 347234debeb..47a476ebc5d 100644--- a/tests/agent/test_per_model_threshold_init_ordering.py+++ b/tests/agent/test_per_model_threshold_init_ordering.py@@ -87,12 +87,6 @@ def test_plugin_engine_gets_model_thresholds_before_initial_update_model():-def test_model_thresholds_key_in_default_config():- """compression.model_thresholds is a public DEFAULT_CONFIG key."""- from hermes_cli.config import DEFAULT_CONFIG-- assert "model_thresholds" in DEFAULT_CONFIG["compression"]- assert DEFAULT_CONFIG["compression"]["model_thresholds"] == {}class TestFloorInteractionOnModelSwitch:diff --git a/tests/agent/test_percentage_clamp.py b/tests/agent/test_percentage_clamp.pyindex 8daa68deaa6..053f3dd6d96 100644--- a/tests/agent/test_percentage_clamp.py+++ b/tests/agent/test_percentage_clamp.py@@ -7,54 +7,18 @@ compression fires), users see >100% in /stats, gateway status, andmemory tool output."""-class TestMemoryToolPercentClamp:- """tools/memory_tool.py — _success_response and _render_block pct"""- def test_over_limit_clamped_at_100(self):- """Percentage should be capped at 100 even if current > limit."""- # Simulate the calculation directly- current = 5500- limit = 5000- pct = min(100, int((current / limit) * 100)) if limit > 0 else 0- assert pct == 100-class TestCLIStatsPercentClamp:- """cli.py — /stats command percentage"""- def test_over_context_clamped_at_100(self):- """Tokens exceeding context_length should show max 100%."""- last_prompt = 210_000- ctx_len = 200_000- pct = min(100, (last_prompt / ctx_len * 100)) if ctx_len else 0- assert pct == 100-class TestGatewayStatsPercentClamp:- """gateway/run.py — _format_usage_stats percentage"""-- def test_over_context_clamped_at_100(self):- last_prompt_tokens = 210_000- context_length = 200_000- pct = min(100, last_prompt_tokens / context_length * 100) if context_length else 0- assert pct == 100--class TestSourceLinesAreClamped:- """Verify the actual source files have min(100, ...) applied."""-- @staticmethod- def _read_file(rel_path: str) -> str:- import os- base = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))- with open(os.path.join(base, rel_path)) as f:- return f.read()-def test_gateway_run_clamped(self):# The /usage stats handler was extracted from gateway/run.py into# gateway/slash_commands.py and then gateway/slash_commands_status.py.@@ -65,9 +29,5 @@ class TestSourceLinesAreClamped:assert _pct(210_000, 200_000) == 100assert _pct(30_000, 200_000) == 15assert _pct(5, 0) == 0- src = self._read_file("gateway/slash_commands_status.py")- assert "_pct(ctx.last_prompt_tokens, ctx.context_length)" in src, (- "gateway/slash_commands_status.py stats pct is not clamped via _pct(...)"- )diff --git a/tests/agent/test_pet_generate.py b/tests/agent/test_pet_generate.pydeleted file mode 100644index 34cbe20ea21..00000000000--- a/tests/agent/test_pet_generate.py+++ /dev/null@@ -1,469 +0,0 @@-"""Tests for pet generation: deterministic atlas ops, store register, orchestration.--No network/API calls — image generation is mocked with synthetic strips so the-whole pipeline (segmentation → compose → validate → register → adopt) is-exercised hermetically.-"""--from __future__ import annotations--import os-from pathlib import Path--import pytest--pytestmark = pytest.mark.skipif(- os.environ.get("HERMES_RUN_SLOW_PET_TESTS") != "1",- reason=(- "pet generation image-processing suite is opt-in; run with "- "HERMES_RUN_SLOW_PET_TESTS=1 scripts/run_tests.sh tests/agent/test_pet_generate.py"- ),-)--from agent.pet.generate import atlas--PIL = pytest.importorskip("PIL")-from PIL import Image, ImageDraw # noqa: E402---def _strip(n_blobs: int, *, transparent: bool = True, bg=(0, 255, 0, 255), size=(208, 208)) -> Image.Image:- """A horizontal strip with *n_blobs* clearly-separated colored ellipses."""- w = size[0] * n_blobs- h = size[1]- base = (0, 0, 0, 0) if transparent else bg- img = Image.new("RGBA", (w, h), base)- draw = ImageDraw.Draw(img)- for i in range(n_blobs):- cx = i * size[0] + size[0] // 2- cy = h // 2- r = size[0] // 3- color = (40 + i * 30 % 200, 80, 200 - i * 20 % 180, 255)- draw.ellipse((cx - r, cy - r, cx + r, cy + r), fill=color)- return img---# ───────────────────────── frame extraction ─────────────────────────---def test_extract_strip_frames_transparent_returns_centered_cells():- frames = atlas.extract_strip_frames(_strip(6), 6)- assert len(frames) == 6- for frame in frames:- assert frame.size == (atlas.CELL_WIDTH, atlas.CELL_HEIGHT)- # Background corners must be transparent.- assert frame.getpixel((0, 0))[3] == 0- # Something is drawn.- assert frame.getchannel("A").getextrema()[1] > 0-----def test_remove_background_defringes_antialiased_edge():- # The contaminated antialiased ring where sprite meets backdrop survives the- # key (it's a blend, too far from pure magenta). Defringe shaves that 1px ring:- # the keyed silhouette comes back eroded ~1px on every side, core intact.- img = Image.new("RGBA", (200, 200), (255, 0, 255, 255))- draw = ImageDraw.Draw(img)- draw.rectangle((50, 50, 149, 149), fill=(40, 200, 60, 255)) # 100x100 green- keyed = atlas.remove_background(img)- bbox = keyed.getbbox()- assert bbox is not None- w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]- assert 96 <= w <= 99 and 96 <= h <= 99 # ~1px shaved per side- assert keyed.getpixel((100, 100))[3] > 0 # core intact-----------------------# ───────────────────────── atlas compose / validate ─────────────────────────---def _frames_for_all_states() -> dict[str, list]:- out: dict[str, list] = {}- for state, _row, count in atlas.ROW_SPECS:- out[state] = atlas.extract_strip_frames(_strip(count), count)- return out-----------def test_validate_atlas_rejects_postage_stamp_sprite():- sheet = Image.new("RGBA", (atlas.ATLAS_WIDTH, atlas.ATLAS_HEIGHT), (0, 0, 0, 0))- frame = Image.new("RGBA", (atlas.CELL_WIDTH, atlas.CELL_HEIGHT), (0, 0, 0, 0))- ImageDraw.Draw(frame).rectangle((86, 174, 106, 201), fill=(220, 240, 255, 255))-- for _state, row, count in atlas.ROW_SPECS:- for col in range(count):- sheet.alpha_composite(frame, (col * atlas.CELL_WIDTH, row * atlas.CELL_HEIGHT))-- result = atlas.validate_atlas(sheet)-- assert not result["ok"]- assert any("too small" in e for e in result["errors"])---------def test_normalize_cells_uses_consistent_pose_scale_for_motion_rows():- # A jump row needs a taller union crop than idle, but the pet itself should- # not shrink just because the motion envelope is taller.- idle = Image.new("RGBA", (160, 180), (0, 0, 0, 0))- jump_low = Image.new("RGBA", (160, 180), (0, 0, 0, 0))- jump_high = Image.new("RGBA", (160, 180), (0, 0, 0, 0))- ImageDraw.Draw(idle).rectangle((50, 80, 110, 160), fill=(80, 120, 220, 255))- ImageDraw.Draw(jump_low).rectangle((50, 80, 110, 160), fill=(220, 120, 80, 255))- ImageDraw.Draw(jump_high).rectangle((50, 60, 110, 140), fill=(220, 120, 80, 255))-- normalized = atlas.normalize_cells({"idle": [idle], "jumping": [jump_low, jump_high]})- idle_box = normalized["idle"][0].getbbox()- jump_box = normalized["jumping"][0].getbbox()-- assert idle_box is not None- assert jump_box is not None- idle_h = idle_box[3] - idle_box[1]- jump_h = jump_box[3] - jump_box[1]- assert abs(idle_h - jump_h) <= 8---# ───────────────────────── store register / adopt ─────────────────────────---def test_slugify_and_unique_slug():- from agent.pet import store-- assert store.slugify("My Cool Pet!") == "my-cool-pet"- assert store.slugify(" ") == "pet"- first = store.unique_slug("Robo")- (store.pets_dir() / first).mkdir(parents=True)- assert store.unique_slug("Robo") == "robo-2"---def test_register_local_pet_appears_and_is_adoptable():- from agent.pet import store-- sheet = atlas.compose_atlas(_frames_for_all_states())- pet = store.register_local_pet(sheet, slug="Sparky", display_name="Sparky", description="zappy")- assert pet.slug == "sparky"- assert pet.exists- assert any(p.slug == "sparky" for p in store.installed_pets())-- # install_pet returns the on-disk pet without ever hitting the manifest.- adopted = store.install_pet("sparky")- assert adopted.slug == "sparky"- assert adopted.display_name == "Sparky"---def test_register_local_pet_is_generated_and_exports_zip():- import io- import zipfile-- from agent.pet import store-- sheet = atlas.compose_atlas(_frames_for_all_states())- store.register_local_pet(sheet, slug="zippy", display_name="Zippy")- assert store.load_pet("zippy").generated is True # createdBy=generator-- filename, data = store.export_pet("zippy")- assert filename == "zippy.zip"- names = zipfile.ZipFile(io.BytesIO(data)).namelist()- assert "zippy/pet.json" in names- assert any(n.startswith("zippy/spritesheet") for n in names)-------# ───────────────────────── orchestration (mocked imagegen) ─────────────────────────-----def test_generate_base_drafts_hardens_opaque_background(monkeypatch, tmp_path):- """A provider that ignores background=transparent still yields a cutout."""- from agent.pet.generate import imagegen, orchestrate-- def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):- # Solid-green backdrop with a blob — i.e. the provider painted a backdrop.- p = tmp_path / f"{prefix}_opaque.png"- _strip(1, transparent=False, bg=(0, 255, 0, 255)).save(p)- return [p]-- monkeypatch.setattr(imagegen, "resolve_provider", lambda **_: object())- monkeypatch.setattr(imagegen, "generate", fake_generate)-- drafts = orchestrate.generate_base_drafts("a fox", n=1)- assert len(drafts) == 1-- with Image.open(drafts[0]) as out:- rgba = out.convert("RGBA")- # The keyed backdrop is now transparent (corner pixel fully see-through).- assert rgba.getpixel((0, 0))[3] == 0- # The pet blob in the center is still opaque.- assert rgba.getpixel((rgba.width // 2, rgba.height // 2))[3] > 0---def test_harden_transparency_removes_non_png_original(tmp_path):- """A non-PNG base draft is replaced by a hardened PNG, and the original- draft file is not left behind in the image cache."""- from agent.pet.generate import orchestrate-- src = tmp_path / "pet_base_sample.webp"- _strip(1).save(src, format="WEBP")-- out = orchestrate._harden_transparency(src)-- assert out.suffix == ".png"- assert out.exists()- assert not src.exists()---def test_harden_transparency_keeps_png_input_in_place(tmp_path):- """A PNG base draft is hardened in place, so the returned path is the input- path and there is no separate original to remove."""- from agent.pet.generate import orchestrate-- src = tmp_path / "pet_base_sample.png"- _strip(1).save(src, format="PNG")-- out = orchestrate._harden_transparency(src)-- assert out == src- assert out.exists()---def test_harden_transparency_keeps_mixed_case_png_in_place(tmp_path):- """A PNG path with a mixed-case suffix is hardened in place.-- path.with_suffix('.png') yields a different Path string than 'pet.PNG', but- on case-insensitive filesystems (macOS APFS, Windows) both resolve to the- same file. Unlinking the input after save would delete the hardened output.- """- from agent.pet.generate import orchestrate-- src = tmp_path / "pet_base_sample.PNG"- _strip(1).save(src, format="PNG")-- out = orchestrate._harden_transparency(src)-- assert out == src- assert out.suffix == ".PNG"- assert out.exists()- assert src.exists()---def test_hatch_pet_end_to_end(monkeypatch, tmp_path):- from agent.pet import store- from agent.pet.generate import atlas as atlas_mod- from agent.pet.generate import imagegen, orchestrate-- base = tmp_path / "base.png"- _strip(1).save(base)-- def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):- # Return a synthetic row strip; frame count is inferable from the spec.- state = prefix.replace("pet_row_", "")- count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)- p = tmp_path / f"{prefix}.png"- _strip(count).save(p)- return [p]-- monkeypatch.setattr(imagegen, "resolve_provider", lambda **_: object())- monkeypatch.setattr(imagegen, "generate", fake_generate)-- events: list[tuple[str, str]] = []- result = orchestrate.hatch_pet(- base_image=base,- slug="mocky",- display_name="Mocky",- description="a test pet",- concept="a fox",- on_progress=lambda ev, detail: events.append((ev, detail)),- )-- assert result.slug == "mocky"- assert result.validation["ok"]- assert set(result.states) == {s for s, _, _ in atlas_mod.ROW_SPECS}- assert ("compose", "") in events- # The pet is on disk and adoptable.- assert store.load_pet("mocky").exists---def test_hatch_pet_removes_row_strips_after_extraction(monkeypatch, tmp_path):- """Row strips are intermediates. Once their frames are decoded, the strip- files are removed so the image cache does not grow on every hatch (nothing- prunes cache/images outside the gateway housekeeping loop)."""- from agent.pet.generate import atlas as atlas_mod- from agent.pet.generate import imagegen, orchestrate-- base = tmp_path / "base.png"- _strip(1).save(base)-- produced: list = []-- def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):- state = prefix.replace("pet_row_", "")- count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)- p = tmp_path / f"{prefix}.png"- _strip(count).save(p)- produced.append(p)- return [p]-- monkeypatch.setattr(imagegen, "resolve_provider", lambda **_: object())- monkeypatch.setattr(imagegen, "generate", fake_generate)-- orchestrate.hatch_pet(base_image=base, slug="cleanup", concept="a fox")-- assert produced, "expected row strips to be generated"- leftover = [p for p in produced if p.exists()]- assert leftover == [], f"row strips left in cache: {leftover}"---def test_hatch_pet_removes_row_strips_after_failed_attempt(monkeypatch, tmp_path):- from agent.pet.generate import atlas as atlas_mod- from agent.pet.generate import imagegen, orchestrate-- base = tmp_path / "base.png"- _strip(1).save(base)-- attempts: dict[str, int] = {}-- def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):- attempts[prefix] = attempts.get(prefix, 0) + 1- state = prefix.replace("pet_row_", "")- count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)- path = tmp_path / f"{prefix}_{attempts[prefix]}.png"- _strip(count).save(path)- return [path]-- extract_strip_frames = atlas_mod.extract_strip_frames- failed_once = False-- def flaky_extract(strip, count, *args, **kwargs):- nonlocal failed_once- if Path(strip).name.startswith("pet_row_idle_") and not failed_once:- failed_once = True- raise ValueError("retry idle row")- return extract_strip_frames(strip, count, *args, **kwargs)-- monkeypatch.setattr(imagegen, "resolve_provider", lambda **_: object())- monkeypatch.setattr(imagegen, "generate", fake_generate)- monkeypatch.setattr(atlas_mod, "extract_strip_frames", flaky_extract)-- orchestrate.hatch_pet(base_image=base, slug="retry-cleanup", concept="a fox")-- assert failed_once- assert attempts["pet_row_idle"] == 2- assert not list(tmp_path.glob("pet_row_*"))---def test_hatch_pet_idle_fallback_when_row_fails(monkeypatch, tmp_path):- from agent.pet.generate import atlas as atlas_mod- from agent.pet.generate import imagegen, orchestrate- from agent.pet.generate.imagegen import GenerationError-- base = tmp_path / "base.png"- _strip(1).save(base)-- def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):- if prefix == "pet_row_idle":- raise GenerationError("boom")- state = prefix.replace("pet_row_", "")- count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)- p = tmp_path / f"{prefix}.png"- _strip(count).save(p)- return [p]-- monkeypatch.setattr(imagegen, "resolve_provider", lambda **_: object())- monkeypatch.setattr(imagegen, "generate", fake_generate)-- result = orchestrate.hatch_pet(base_image=base, slug="fallbacky", concept="a fox")- assert "idle" in result.states # filled by the base-image fallback-------class _FakeImgProvider:- def __init__(self, name, available=True):- self.name = name- self._available = available-- def is_available(self):- return self._available-----def test_list_sprite_providers_marks_default(monkeypatch):- """Lists only available ref-capable backends, flagging the default pick."""- from agent.pet.generate import imagegen-- registry = {"openai": _FakeImgProvider("openai"), "nous": _FakeImgProvider("nous")}- monkeypatch.setattr(imagegen, "_discover", lambda: None)- monkeypatch.setattr("agent.image_gen_registry.get_active_provider", lambda: registry["openai"])- monkeypatch.setattr("agent.image_gen_registry.get_provider", lambda name: registry.get(name))-- listed = imagegen.list_sprite_providers()- names = {p["name"] for p in listed}- assert names == {"openai", "nous"}- # Every entry carries a display label (no quality note — all backends are equal).- assert all(p["label"] for p in listed)- assert all("note" not in p for p in listed)- assert [p["name"] for p in listed if p["default"]] == ["openai"]- # Listed in preference order: Nous Portal before OpenAI.- assert [p["name"] for p in listed] == ["nous", "openai"]---def test_generate_retries_without_transparent_background(monkeypatch, tmp_path):- """A model that rejects background=transparent still produces images."""- from agent.pet.generate import imagegen-- saved = tmp_path / "img.png"- _strip(1).save(saved)- calls: list[dict] = []-- class FakeProvider:- def generate(self, prompt, **kwargs):- calls.append(kwargs)- if kwargs.get("background") == "transparent":- return {"success": False, "error": "Transparent background is not supported for this model."}- return {"success": True, "image": str(saved)}-- sprite = imagegen.SpriteProvider(name="openai", provider=FakeProvider(), supports_references=False)-- out = imagegen.generate("a fox", n=2, provider=sprite)- assert len(out) == 2- # First variant probes transparent (rejected) then retries opaque; the second- # variant skips the transparent probe entirely.- backgrounds = [c.get("background") for c in calls]- assert backgrounds == ["transparent", None, None]diff --git a/tests/agent/test_phantom_tool_references.py b/tests/agent/test_phantom_tool_references.pyindex 3128e20dc7f..b194e57f154 100644--- a/tests/agent/test_phantom_tool_references.py+++ b/tests/agent/test_phantom_tool_references.py@@ -14,29 +14,6 @@ Covers:from pathlib import Path-class TestHermesAgentHelpGuidance:- def test_skill_variant_used_when_skill_view_present(self):- from agent.prompt_builder import HERMES_AGENT_HELP_GUIDANCE- assert "skill_view(name='hermes-agent')" in HERMES_AGENT_HELP_GUIDANCE-- def test_no_skills_variant_has_no_skill_view_reference(self):- from agent.prompt_builder import HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS- assert "skill_view" not in HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS- assert "hermes-agent.nousresearch.com/docs" in HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS---class TestExecutionGuidanceText:- def test_no_web_tool_named_without_web_tools(self):- # #39797: naming web_search here overrode SOUL.md and dangled when the web toolset was off.- from agent.prompt_builder import OPENAI_MODEL_EXECUTION_GUIDANCE, execution_guidance_text- text = execution_guidance_text()- assert text == OPENAI_MODEL_EXECUTION_GUIDANCE- assert "web_search" not in text and "web_extract" not in text- # The surrounding structure survives.- assert "<mandatory_tool_use>" in text- assert "<missing_context>" in text--class TestCodingBriefTodoGating:def _brief(self, valid_tool_names):from agent.coding_context import CODING_PROFILE, RuntimeMode@@ -51,17 +28,15 @@ class TestCodingBriefTodoGating:def test_todo_kept_when_tool_available(self):brief = self._brief({"todo_list", "terminal", "read_file"})- assert "Track multi-step work with `todo_list`" in brief+ assert "todo_list" in briefdef test_todo_dropped_when_tool_missing(self):brief = self._brief({"terminal", "read_file"})- assert "`todo`" not in brief- # The path:line half of the merged bullet survives.- assert "path:line" in brief+ assert "todo_list" not in briefdef test_unknown_toolset_keeps_full_brief(self):brief = self._brief(None)- assert "Track multi-step work with `todo_list`" in brief+ assert "todo_list" in briefclass TestEssentialSkillsUndisableable:@@ -97,7 +72,6 @@ class TestEssentialSkillsUndisableable:from tools.skill_manager_guards import _pinned_guardmsg = _pinned_guard("hermes-agent")assert msg is not None- assert "essential" in msg.lower()class TestEssentialOnlySync:diff --git a/tests/agent/test_plan_prompt.py b/tests/agent/test_plan_prompt.pyindex 87abbe0f269..82777b82a30 100644--- a/tests/agent/test_plan_prompt.py+++ b/tests/agent/test_plan_prompt.py@@ -16,35 +16,10 @@ class TestBuildPlanPrompt:prompt = build_plan_prompt(task)assert task in prompt- def test_empty_task_infers_from_conversation(self):- prompt = build_plan_prompt("")- assert "infer the task from the current conversation context" in prompt- # Whitespace-only behaves the same.- assert "infer the task" in build_plan_prompt(" ")-- def test_plan_mode_ground_rules_always_present(self):- for arg in ("", "build a REST API"):- prompt = build_plan_prompt(arg)- assert "PLAN MODE" in prompt- assert "Do not implement code" in prompt- assert "Do not run mutating terminal commands" in prompt- assert "read-only" in prompt-- def test_save_location_contract(self):- prompt = build_plan_prompt("anything")- assert ".hermes/plans/" in prompt- assert "YYYY-MM-DD_HHMMSS-<slug>.md" in prompt-- def test_authoring_craft_travels_with_every_prompt(self):- prompt = build_plan_prompt("x")- assert "bite-sized" in prompt- assert "exact file paths" in prompt.lower()- assert "TDD" in prompt- assert "YAGNI" in prompt-- def test_no_execution_handoff_in_same_turn(self):- prompt = build_plan_prompt("x")- assert "do not start executing in this turn" in prompt++++class TestPlanRegistryWiring:@@ -55,30 +30,6 @@ class TestPlanRegistryWiring:assert cmd is not Noneassert cmd.name == "plan"- def test_plan_is_not_cli_only(self):- # /plan must reach messaging gateways — the whole point of the- # builtin conversion is menu visibility on Telegram/Discord.- from hermes_cli.commands import resolve_command-- assert not resolve_command("plan").cli_only-- def test_plan_reaches_gateway_dispatch(self):- from hermes_cli.commands import GATEWAY_KNOWN_COMMANDS-- assert "plan" in GATEWAY_KNOWN_COMMANDS-- def test_plan_in_telegram_bot_commands(self):- from hermes_cli.commands_platforms import telegram_bot_commands- names = {n for n, _ in telegram_bot_commands()}- assert "plan" in names- def test_no_bundled_plan_skill_remains(self):- # The bundled skill was removed with the builtin conversion; a- # leftover copy would collide with the core command at scan time- # (scan_skill_commands skips core-colliding skill slugs with a- # warning, so the skill would be silently unreachable).- from pathlib import Path- repo_root = Path(__file__).resolve().parents[2]- assert not (repo_root / "skills" / "software-development" / "plan").exists()diff --git a/tests/agent/test_platform_hint_desktop.py b/tests/agent/test_platform_hint_desktop.pyindex 8587b5fb48b..925923f46d5 100644--- a/tests/agent/test_platform_hint_desktop.py+++ b/tests/agent/test_platform_hint_desktop.py@@ -17,7 +17,7 @@ from unittest.mock import patchimport pytest-from agent.prompt_builder import PLATFORM_HINTS, build_environment_hints+from agent.prompt_builder import PLATFORM_HINTSfrom agent.system_prompt import (_tui_embedded_pane_clarifier,build_system_prompt_parts,@@ -55,53 +55,13 @@ def _make_agent(platform="", **overrides):return SimpleNamespace(**base)-class TestDesktopHintEntry:- def test_desktop_key_exists(self):- """The map must carry a "desktop" entry — without it the platform- hint lookup falls through to an empty string and the agent gets no- surface framing at all on the desktop chat surface."""- assert "desktop" in PLATFORM_HINTS- def test_desktop_hint_advertises_markdown(self):- """The desktop renderer supports full GFM (verified via the- Streamdown pipeline in apps/desktop). The hint must steer the- agent toward markdown, not away from it like the cli/tui hints do."""- hint = PLATFORM_HINTS["desktop"]- assert "markdown" in hint.lower()-class TestDesktopHintBlockRemoved:- """The standalone desktop-hint block that used to live in- ``build_environment_hints()`` (lines ~1130-1144) was a band-aid for the- missing ``PLATFORM_HINTS["desktop"]`` entry. Once that entry exists, the- block is dead code that competes with the platform hint's claim of- what surface the agent is on. It must be gone."""-- def test_build_environment_hints_has_no_runtime_surface_line(self, monkeypatch):- monkeypatch.setenv("HERMES_DESKTOP", "1")- monkeypatch.delenv("HERMES_DESKTOP_TERMINAL", raising=False)- from agent.prompt_builder import _BACKEND_PROBE_CACHE- _BACKEND_PROBE_CACHE.clear()- hints = build_environment_hints()- assert "Runtime surface:" not in hints- assert "desktop GUI app" not in hints-- def test_build_environment_hints_has_no_embedded_pane_clarifier(self, monkeypatch):- """The ⌥-drag / ⌘+L embedded-pane clarifier moves to the platform-hint- resolution site (system_prompt.py), not build_environment_hints()."""- monkeypatch.setenv("HERMES_DESKTOP", "1")- monkeypatch.setenv("HERMES_DESKTOP_TERMINAL", "1")- from agent.prompt_builder import _BACKEND_PROBE_CACHE- _BACKEND_PROBE_CACHE.clear()- hints = build_environment_hints()- assert "embedded terminal pane" not in hints- assert "Shift-drag" not in hints--class TestPlatformHintResolutionInStablePrompt:"""End-to-end through ``build_system_prompt_parts`` — the platform tag onthe agent drives BOTH which PLATFORM_HINTS entry gets appended AND@@ -138,16 +98,10 @@ class TestEmbeddedTuiPaneClarifier:stay byte-stable)."""- def test_embedded_pane_clarifier_appended_when_env_set(self, monkeypatch):- monkeypatch.setenv("HERMES_DESKTOP_TERMINAL", "1")- out = _tui_embedded_pane_clarifier(PLATFORM_HINTS["tui"])- assert out.startswith(PLATFORM_HINTS["tui"])- assert "embedded terminal pane" in out- assert "Shift-drag" in out or "Option-drag" in out or "⌥" in out- @pytest.mark.parametrize("val", ["0", "false", "no", "", "0", "False"])+ @pytest.mark.parametrize("val", ["0", "false", ""])def test_falsy_env_does_not_trigger_clarifier(self, monkeypatch, val):monkeypatch.setenv("HERMES_DESKTOP_TERMINAL", val)out = _tui_embedded_pane_clarifier(PLATFORM_HINTS["tui"])@@ -156,23 +110,3 @@ class TestEmbeddedTuiPaneClarifier:)-class TestContradictionGone:- """The original contradiction: a single assembled system prompt- contained both ``You are running in the Hermes terminal UI (TUI).`` and- ``Runtime surface: you're running inside the Hermes desktop GUI app.``.- After the fix, no single session's prompt can carry both."""-- def test_desktop_chat_session_has_no_tui_framing(self, monkeypatch):- monkeypatch.setenv("HERMES_DESKTOP", "1")- monkeypatch.delenv("HERMES_DESKTOP_TERMINAL", raising=False)- assert "tui" in PLATFORM_HINTS- assert "desktop" in PLATFORM_HINTS- desktop_hint = PLATFORM_HINTS["desktop"]- tui_hint = PLATFORM_HINTS["tui"]- assert "terminal UI" not in desktop_hint- assert "terminal UI" in tui_hint-- def test_tui_hint_does_not_carry_desktop_marker(self):- tui_hint = PLATFORM_HINTS["tui"]- assert "desktop GUI app" not in tui_hint- assert "Runtime surface:" not in tui_hintdiff --git a/tests/agent/test_plugin_context_engine_init.py b/tests/agent/test_plugin_context_engine_init.pyindex 1c5dc291ca1..9116446620d 100644--- a/tests/agent/test_plugin_context_engine_init.py+++ b/tests/agent/test_plugin_context_engine_init.py@@ -4,7 +4,7 @@ Regression test for #9071 — plugin engines were never initialized withcontext_length, causing the CLI status bar to show 'ctx --'."""-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom agent.context_engine import ContextEngine@@ -107,40 +107,6 @@ def test_active_context_engine_tools_survive_explicit_platform_toolsets():}-def test_plugin_engine_update_model_args():- """Verify update_model() receives model, context_length, base_url, api_key, provider."""- engine = _StubEngine()- engine.update_model = MagicMock()-- cfg = {"context": {"engine": "stub"}, "agent": {}}-- with (- patch("hermes_cli.config.load_config", return_value=cfg), patch("hermes_cli.config.load_config_readonly", return_value=cfg),- patch("plugins.context_engine.load_context_engine", return_value=engine),- patch("agent.model_metadata.get_model_context_length", return_value=131_072),- patch("model_tools.get_tool_definitions", return_value=[]),- patch("model_tools.check_toolset_requirements", return_value={}),- patch("agent.process_bootstrap.OpenAI"),- ):- from run_agent import AIAgent-- agent = AIAgent(- model="openrouter/auto",- api_key="test-key-1234567890",- base_url="https://openrouter.ai/api/v1",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )-- engine.update_model.assert_called_once()- kw = engine.update_model.call_args.kwargs- assert kw["context_length"] == 131_072- assert "model" in kw- assert "provider" in kw- assert "api_mode" in kw--def _codex_agent_kwargs():return dict(model="gpt-5.5",@@ -207,6 +173,4 @@ def test_codex_gpt55_autoraise_still_applies_to_builtin_compressor():assert agent._compression_threshold_autoraised == {"model": "gpt-5.5", "from": 0.50, "to": 0.85}assert agent.context_compressor.threshold_percent == 0.85# Gateway parity: the notice is stashed for replay on turn 1.- assert agent._compression_warning and "85%" in agent._compression_warning--+ assert agent._compression_warningdiff --git a/tests/agent/test_plugin_context_references.py b/tests/agent/test_plugin_context_references.pyindex f0bbfd33a97..21ee7983422 100644--- a/tests/agent/test_plugin_context_references.py+++ b/tests/agent/test_plugin_context_references.py@@ -2,7 +2,6 @@from __future__ import annotations-import asynciofrom pathlib import Pathimport pytest@@ -11,7 +10,6 @@ from agent.context_references import (BUILTIN_PREFIXES,ContextCompletionItem,ContextReferenceProvider,- _PLUGIN_REFERENCE_PATTERN,_context_reference_providers,get_context_reference_providers,parse_context_references,@@ -119,11 +117,6 @@ def test_parse_plugin_reference_ignored_when_not_registered():assert [r.kind for r in refs] == []-def test_plugin_pattern_regex():- m = _PLUGIN_REFERENCE_PATTERN.search("@issue:ENG-123")- assert m is not None- assert m.group("kind") == "issue"- assert m.group("value") == "ENG-123"# -- expand tests ----------------------------------------------------------@@ -173,13 +166,6 @@ async def test_expand_plugin_error(tmp_path: Path):# -- autocomplete tests -----------------------------------------------------async def test_autocomplete():- p = _DummyProvider()- register_context_reference_provider(p)- items = await p.autocomplete("foo", limit=5)- assert len(items) == 1- assert items[0].text == "foo-result"# -- ContextCompletionItem tests -------------------------------------------@@ -191,7 +177,3 @@ def test_completion_item_defaults():assert item.meta == ""-def test_completion_item_custom():- item = ContextCompletionItem(text="1", display="ENG-1", meta="Bug")- assert item.display == "ENG-1"- assert item.meta == "Bug"diff --git a/tests/agent/test_plugin_llm.py b/tests/agent/test_plugin_llm.pyindex 38016944eda..76a722bf252 100644--- a/tests/agent/test_plugin_llm.py+++ b/tests/agent/test_plugin_llm.py@@ -12,12 +12,10 @@ import asyncioimport base64from types import SimpleNamespacefrom typing import Any-from unittest.mock import MagicMockimport pytestfrom agent.plugin_llm import (- PluginLlm,PluginLlmCompleteResult,PluginLlmImageInput,PluginLlmStructuredResult,@@ -388,22 +386,6 @@ class TestPluginLlmFacade:class TestAsyncSurface:- def test_acomplete_uses_async_caller(self):- async def fake_async(**_kwargs):- return "openai", "gpt-4o", _fake_response("async hello")-- llm = make_plugin_llm_for_test(- plugin_id="my-plugin",- policy=_TrustPolicy(plugin_id="my-plugin"),- async_caller=fake_async,- )-- async def _run() -> PluginLlmCompleteResult:- return await llm.acomplete([{"role": "user", "content": "hi"}])-- result = asyncio.run(_run())- assert result.text == "async hello"- assert result.provider == "openai"def test_acomplete_structured_parses_json(self):async def fake_async(**_kwargs):@@ -490,17 +472,6 @@ plugins:class TestPluginContextIntegration:- def test_ctx_llm_is_lazy_singleton(self):- from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager-- manifest = PluginManifest(name="test-plugin", source="test", key="test-plugin")- manager = PluginManager()- ctx = PluginContext(manifest, manager)- first = ctx.llm- second = ctx.llm- assert first is second- assert isinstance(first, PluginLlm)- assert first._plugin_id == "test-plugin" # type: ignore[attr-defined]def test_ctx_llm_uses_manifest_key_for_policy(self):from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager@@ -626,30 +597,3 @@ class TestHookMode:hook_record = captured[1]assert hook_record["hook_returned"] == "rewrote it"- def test_complete_works_from_post_tool_call_hook_when_async_caller_set(self):- """Hooks fired synchronously should still work with sync- ctx.llm.complete even if other callsites use async."""- from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager-- manifest = PluginManifest(name="hook-async", source="test", key="hook-async")- manager = PluginManager()- ctx = PluginContext(manifest, manager)-- def fake_caller(**_):- return "openrouter", "model-x", _fake_response("ok")-- ctx._llm = make_plugin_llm_for_test( # type: ignore[attr-defined]- plugin_id="hook-async",- policy=_TrustPolicy(plugin_id="hook-async"),- sync_caller=fake_caller,- )-- called: list = []-- def hook(**kwargs):- r = ctx.llm.complete(messages=[{"role": "user", "content": "x"}])- called.append(r.text)-- ctx.register_hook("post_tool_call", hook)- manager.invoke_hook("post_tool_call", tool_name="x", args={}, result="y")- assert called == ["ok"]diff --git a/tests/agent/test_plugin_llm_task_routing.py b/tests/agent/test_plugin_llm_task_routing.pyindex 7dde600d0e0..fb37fd91ce0 100644--- a/tests/agent/test_plugin_llm_task_routing.py+++ b/tests/agent/test_plugin_llm_task_routing.py@@ -304,45 +304,6 @@ class TestRouting:assert captured["task"] == "classifier"assert result.audit["task"] == "classifier"- def test_async_variants_log_exact_route(self, monkeypatch, caplog):- _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])- _set_builtins(monkeypatch, [])- llm = make_plugin_llm_for_test(- plugin_id="my-plugin",- policy=_policy(),- async_caller=_async_capturing_caller({}),- )-- with caplog.at_level(logging.INFO, logger="agent.plugin_llm"):- asyncio.run(- llm.acomplete(- [{"role": "user", "content": "hi"}],- task="classifier",- purpose="plain",- )- )- asyncio.run(- llm.acomplete_structured(- instructions="classify",- input=[PluginLlmTextInput(text="payload")],- task="classifier",- purpose="structured",- )- )-- messages = [record.getMessage() for record in caplog.records]- assert any(- "plugin_llm.acomplete plugin=my-plugin provider=aux-provider "- "model=aux-model task=classifier purpose=plain tokens=8" in message- for message in messages- )- assert any(- "plugin_llm.acomplete_structured plugin=my-plugin provider=aux-provider "- "model=aux-model task=classifier purpose=structured "- "content_type=text tokens=8" in message- for message in messages- )-def test_successful_fallback_route_beats_requested_route_for_attribution():provider, model = _resolve_attribution(@@ -359,7 +320,7 @@ class TestForwardsToCallLlm:where the previously-hardcoded ``task=None`` is replaced by the routedkey. The injected-caller tests above bypass this line."""- def test_sync_task_uses_auxiliary_attribution_and_log(self, monkeypatch, caplog):+ def test_sync_task_uses_auxiliary_attribution(self, monkeypatch):_set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])_set_builtins(monkeypatch, [])seen: Dict[str, Any] = {}@@ -371,14 +332,9 @@ class TestForwardsToCallLlm:monkeypatch.setattr("agent.auxiliary_client.call_llm", fake_call_llm)llm = make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy())- with caplog.at_level(logging.INFO, logger="agent.plugin_llm"):- result = llm.complete([{"role": "user", "content": "hi"}], task="classifier")+ result = llm.complete([{"role": "user", "content": "hi"}], task="classifier")assert seen["task"] == "classifier"assert (result.provider, result.model) == ("aux-provider", "aux-model")- assert any(- "provider=aux-provider model=aux-model task=classifier" in record.getMessage()- for record in caplog.records- )def test_sync_default_forwards_task_none(self, monkeypatch):_set_registry(monkeypatch, [])diff --git a/tests/agent/test_plugin_stream_hooks.py b/tests/agent/test_plugin_stream_hooks.pyindex 81b45fd6a24..f44a8a9cec5 100644--- a/tests/agent/test_plugin_stream_hooks.py+++ b/tests/agent/test_plugin_stream_hooks.py@@ -38,17 +38,6 @@ def _callbacks(callbacks_by_hook):return lambda name: tuple(callbacks_by_hook.get(name, ()))-def test_stream_observer_hooks_are_valid_plugin_hooks():- from hermes_cli.plugins import VALID_HOOKS-- assert {- "on_stream_start",- "on_stream_delta",- "on_stream_end",- "on_interim_message",- }.issubset(VALID_HOOKS)--def test_stream_delta_plugin_hook_is_queued_off_token_path(monkeypatch):from agent.plugin_stream_hooks import shutdown_plugin_stream_hook_dispatcher@@ -193,29 +182,6 @@ def test_reasoning_stream_delta_plugin_hook_is_opt_in(monkeypatch):assert calls[0][1]["delta"] == "visible reasoning"-def test_reasoning_stream_opt_in_is_read_once_per_stream(monkeypatch):- from agent.plugin_stream_hooks import shutdown_plugin_stream_hook_dispatcher-- shutdown_plugin_stream_hook_dispatcher()- monkeypatch.setattr("hermes_cli.plugins.iter_hook_callbacks", _callbacks({"on_stream_delta": [lambda **kw: None]}))- reads = []-- def _enabled():- reads.append(1)- return False-- monkeypatch.setattr("agent.plugin_stream_hooks.stream_reasoning_deltas_enabled", _enabled)- agent = _agent()- for token in ("a", "b", "c"):- agent._fire_reasoning_delta(token)- assert len(reads) == 1-- agent._reset_stream_delivery_tracking()- agent._fire_reasoning_delta("d")- assert len(reads) == 2- shutdown_plugin_stream_hook_dispatcher()--def test_interim_message_plugin_hook_is_queued(monkeypatch):from agent.plugin_stream_hooks import shutdown_plugin_stream_hook_dispatcherdiff --git a/tests/agent/test_portal_tags.py b/tests/agent/test_portal_tags.pyindex 2051771cf67..898df968d13 100644--- a/tests/agent/test_portal_tags.py+++ b/tests/agent/test_portal_tags.py@@ -14,7 +14,6 @@ def test_nous_portal_tags_contains_product_and_client():tags = nous_portal_tags()assert "product=hermes-agent" in tagsassert hermes_client_tag() in tags- assert len(tags) == 2@@ -45,7 +44,7 @@ def test_ambient_context_set_none_clears():token = set_conversation_context(empty)try:assert get_conversation_context() is None- assert len(nous_portal_tags()) == 2+ assert not any(t.startswith("conversation=") for t in nous_portal_tags())finally:reset_conversation_context(token)diff --git a/tests/agent/test_post_compression_trim.py b/tests/agent/test_post_compression_trim.pyindex 4cb1aadc39b..1e98ca476ed 100644--- a/tests/agent/test_post_compression_trim.py+++ b/tests/agent/test_post_compression_trim.py@@ -39,20 +39,6 @@ def _messages(n: int, size: int = 1500) -> list:return msgs-def test_successful_compression_trims_memory_once(monkeypatch):- calls = []- monkeypatch.setattr(- mem_trim, "trim_memory", lambda *a, **kw: calls.append(kw) or False- )-- cc = _compressor()- out = cc.compress(_messages(14), current_tokens=100_000)-- assert len(out) < 15, "sanity: compaction should have made progress"- assert len(calls) == 1, "trim_memory must run exactly once per compaction"- assert calls[0].get("reason") == "post-compression"--def test_trim_failure_does_not_break_compression(monkeypatch):def boom(*a, **kw):raise RuntimeError("allocator says no")diff --git a/tests/agent/test_post_tool_compression_attempt_cap.py b/tests/agent/test_post_tool_compression_attempt_cap.pyindex 63d4558a35e..9fc09477f53 100644--- a/tests/agent/test_post_tool_compression_attempt_cap.py+++ b/tests/agent/test_post_tool_compression_attempt_cap.py@@ -167,12 +167,13 @@ class TestPostToolCompressionAttemptCap:(7 compactions here); the shared per-turn counter caps it at theresolved default of 3."""- assert agent.max_compression_attempts == 3 # config default+ cap = agent.max_compression_attempts+ assert 0 < cap < 7result, compress_calls = _run_tool_loop(agent, n_tool_iterations=7)assert result["completed"] is True- assert len(compress_calls) == 3, (- f"post-tool compression must stop at the per-turn cap (3), "+ assert len(compress_calls) == cap, (+ f"post-tool compression must stop at the per-turn cap ({cap}), "f"got {len(compress_calls)} compactions")@@ -193,7 +194,7 @@ class TestPostToolCompressionAttemptCap:result, compress_calls = _run_tool_loop(agent, n_tool_iterations=7)assert result["completed"] is True- assert len(compress_calls) == 3, (+ assert len(compress_calls) == agent.max_compression_attempts, ("pre-API and post-tool compactions must share one per-turn "f"attempt budget, got {len(compress_calls)} total compactions")@@ -204,5 +205,5 @@ class TestPostToolCompressionAttemptCap:agent.client.chat.completions.create.side_effect = None_result, second = _run_tool_loop(agent, n_tool_iterations=5)- assert len(first) == 3- assert len(second) == 3+ assert len(first) == agent.max_compression_attempts+ assert len(second) == agent.max_compression_attemptsdiff --git a/tests/agent/test_pre_compress_checkpoint_contract.py b/tests/agent/test_pre_compress_checkpoint_contract.pyindex 7fa9e756bfc..7544e8b9e83 100644--- a/tests/agent/test_pre_compress_checkpoint_contract.py+++ b/tests/agent/test_pre_compress_checkpoint_contract.py@@ -77,9 +77,6 @@ class _FailingLegacyProvider(_BaseStubProvider):raise RuntimeError("legacy best-effort failure")-def test_provider_base_class_defaults_to_implicit_historical_api_version_one():- assert MemoryProvider.pre_compress_checkpoint_api_version == 1- assert PRE_COMPRESS_CHECKPOINT_API_VERSION == 2def test_v1_providers_receive_raw_messages_and_v2_receive_evidence():@@ -541,26 +538,6 @@ def test_turn_finalizer_never_micro_compacts_while_checkpoint_gate_armed(assert _run(checkpoint_required=False) == 1-def test_agent_init_suppresses_micro_compaction_under_checkpoint_gate():- """checkpoint_required forces micro-compaction off at init.-- Both keys can be enabled together in config; the gate must win so every- lossy rewrite passes through the checkpoint-aware batch compressor.- """- import inspect-- from agent import agent_init-- source = inspect.getsource(agent_init)- # The suppression must happen before the compressor attribute assignment.- suppress_idx = source.find("if cs.checkpoint_required and cs.micro_compact:")- # The compressor attribute assignment is table-driven; pin the table entry.- assign_idx = source.find('("_micro_compact_enabled", cs.micro_compact)')- assert suppress_idx != -1, (- "init_agent must suppress micro-compaction when checkpoint_required"- )- assert assign_idx != -1- assert suppress_idx < assign_idxdef _warn_text(caplog) -> str:diff --git a/tests/agent/test_preflight_compression_gate.py b/tests/agent/test_preflight_compression_gate.pyindex f31965328bc..a2a1f7e264f 100644--- a/tests/agent/test_preflight_compression_gate.py+++ b/tests/agent/test_preflight_compression_gate.py@@ -36,21 +36,6 @@ def test_few_messages_huge_content_triggers_gate():) is True-----def test_content_above_threshold_triggers():- """A single message comfortably above the threshold trips branch (b)."""- # ~threshold*4 chars => ~threshold tokens; +1000 tokens of margin so the- # test doesn't depend on per-message dict-wrapping overhead in the- # shared estimator's (chars+3)//4 rounding.- messages = [_msg("x" * ((THRESHOLD_TOKENS + 1000) * 4))]- assert _should_run_preflight_estimate(- messages, PROTECT_FIRST_N, PROTECT_LAST_N, THRESHOLD_TOKENS- ) is True--def test_content_below_threshold_does_not_trigger():"""A single message comfortably below the threshold (and few messages)must not trigger — the estimator stays under and the count gate is not@@ -59,9 +44,3 @@ def test_content_below_threshold_does_not_trigger():assert _should_run_preflight_estimate(messages, PROTECT_FIRST_N, PROTECT_LAST_N, THRESHOLD_TOKENS) is False------diff --git a/tests/agent/test_preflight_lock_defer.py b/tests/agent/test_preflight_lock_defer.pyindex 006ba811459..b524bd508ee 100644--- a/tests/agent/test_preflight_lock_defer.py+++ b/tests/agent/test_preflight_lock_defer.py@@ -71,23 +71,3 @@ def test_preflight_lock_skip_does_not_set_blocked_flag():# Exactly one pass: the defer stops the loop without arming the blocker.assert calls == [1]assert ctx.preflight_compression_blocked is False-------def test_preflight_magicmock_flag_value_is_not_a_defer():- """Type-pin: truthy junk (MagicMock auto-attribute shape) must not be- treated as lock contention — the blocker arms as for a plain no-op."""- agent = _make_agent()-- def _junk_flag_compress(messages, _system_message, **_kwargs):- agent._compression_skipped_due_to_lock = MagicMock()- return messages, "SYSTEM"-- agent._compress_context = _junk_flag_compress-- ctx = _build(agent, conversation_history=list(_HISTORY))-- assert ctx.preflight_compression_blocked is Truediff --git a/tests/agent/test_primary_runtime_restore.py b/tests/agent/test_primary_runtime_restore.pyindex cf3d46ceab6..02fc9c5ac17 100644--- a/tests/agent/test_primary_runtime_restore.py+++ b/tests/agent/test_primary_runtime_restore.py@@ -78,60 +78,6 @@ def _mock_resolve(base_url="https://openrouter.ai/api/v1", api_key="fallback-key# _primary_runtime snapshot# =============================================================================-class TestPrimaryRuntimeSnapshot:- def test_snapshot_created_at_init(self):- agent = _make_agent()- assert hasattr(agent, "_primary_runtime")- rt = agent._primary_runtime- assert rt["model"] == agent.model- assert rt["provider"] == "custom"- assert rt["base_url"] == "https://my-llm.example.com/v1"- assert rt["api_mode"] == agent.api_mode- assert "client_kwargs" in rt- assert "compressor_context_length" in rt-- def test_snapshot_includes_request_overrides(self):- overrides = {"extra_body": {"reasoning": {"effort": "medium"}}}- agent = _make_agent(request_overrides=overrides)- rt = agent._primary_runtime- assert rt["request_overrides"] == overrides- assert rt["request_overrides"] is not agent.request_overrides-- def test_snapshot_includes_compressor_state(self):- agent = _make_agent()- rt = agent._primary_runtime- cc = agent.context_compressor- assert rt["compressor_model"] == cc.model- assert rt["compressor_provider"] == cc.provider- assert rt["compressor_context_length"] == cc.context_length- assert rt["compressor_threshold_tokens"] == cc.threshold_tokens-- def test_snapshot_includes_anthropic_state_when_applicable(self):- """Anthropic-mode agents should snapshot Anthropic-specific state."""- with (- patch("model_tools.get_tool_definitions", return_value=_make_tool_defs("web_search")),- patch("model_tools.check_toolset_requirements", return_value={}),- patch("agent.process_bootstrap.OpenAI"),- patch("agent.anthropic_adapter.build_anthropic_client", return_value=MagicMock()),- ):- agent = AIAgent(- api_key="sk-ant-test-12345678",- base_url="https://api.anthropic.com",- provider="anthropic",- api_mode="anthropic_messages",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )- rt = agent._primary_runtime- assert "anthropic_api_key" in rt- assert "anthropic_base_url" in rt- assert "is_anthropic_oauth" in rt-- def test_snapshot_omits_anthropic_for_openai_mode(self):- agent = _make_agent(provider="custom")- rt = agent._primary_runtime- assert "anthropic_api_key" not in rt# =============================================================================@@ -144,55 +90,7 @@ class TestRestorePrimaryRuntime:assert agent._fallback_activated is Falseassert agent._restore_primary_runtime() is False- def test_restores_model_and_provider(self):- agent = _make_agent(- fallback_model={"provider": "openrouter", "model": "anthropic/claude-sonnet-4"},- )- original_model = agent.model- original_provider = agent.provider-- # Simulate fallback activation- mock_client = _mock_resolve()- with patch("agent.auxiliary_client.resolve_provider_client", return_value=(mock_client, None)):- agent._try_activate_fallback()-- assert agent._fallback_activated is True- assert agent.model == "anthropic/claude-sonnet-4"- assert agent.provider == "openrouter"-- # Restore should bring back the primary- with patch("agent.process_bootstrap.OpenAI", return_value=MagicMock()):- result = agent._restore_primary_runtime()- assert result is True- assert agent._fallback_activated is False- assert agent.model == original_model- assert agent.provider == original_provider-- def test_emits_user_visible_primary_restore_notice(self):- agent = _make_agent(- fallback_model={"provider": "openrouter", "model": "anthropic/claude-sonnet-4"},- )- agent.model = "primary-model"- agent._primary_runtime["model"] = "primary-model"- original_model = agent.model- original_provider = agent.provider- mock_client = _mock_resolve()- with patch(- "agent.auxiliary_client.resolve_provider_client",- return_value=(mock_client, None),- ):- assert agent._try_activate_fallback() is True-- emitted = []- agent._emit_status = emitted.append- with patch("agent.process_bootstrap.OpenAI", return_value=MagicMock()):- assert agent._restore_primary_runtime() is True-- assert emitted == [- f"✅ Primary model restored: {original_model} via {original_provider}; "- "fallback anthropic/claude-sonnet-4 via openrouter is no longer active."- ]def test_does_not_label_temporary_model_restore_as_fallback_recovery(self):"""`/model --once` reuses restore with no provider fallback lifecycle."""@@ -235,10 +133,10 @@ class TestRestorePrimaryRuntime:assert agent._restore_primary_runtime() is Falseassert agent._restore_primary_runtime() is True- assert emitted == [- "✅ Primary model restored: primary-model via custom; "- "fallback anthropic/claude-sonnet-4 via openrouter is no longer active."- ]+ # Exactly one restore notice, emitted only by the successful retry.+ assert len(emitted) == 1+ assert "primary-model" in emitted[0]+ assert "anthropic/claude-sonnet-4" in emitted[0]def test_resets_fallback_index(self):"""After restore, the full fallback chain should be available again."""@@ -567,17 +465,6 @@ def _make_transport_error(error_type="ReadTimeout"):class TestTryRecoverPrimaryTransport:- def test_recovers_on_read_timeout(self):- agent = _make_agent(provider="custom")- error = _make_transport_error("ReadTimeout")-- with patch("agent.process_bootstrap.OpenAI", return_value=MagicMock()), \- patch("time.sleep"):- result = agent._try_recover_primary_transport(- error, retry_count=3, max_retries=3,- )-- assert result is Truedef test_recovery_restores_request_overrides(self):original_overrides = {"extra_body": {"reasoning": {"effort": "medium"}}}@@ -646,29 +533,7 @@ class TestTryRecoverPrimaryTransport:- def test_wait_time_scales_with_retry_count(self):- agent = _make_agent(provider="custom")- error = _make_transport_error("ReadTimeout")-- with patch("agent.process_bootstrap.OpenAI", return_value=MagicMock()), \- patch("time.sleep") as mock_sleep:- agent._try_recover_primary_transport(- error, retry_count=3, max_retries=3,- )- # wait_time = min(3 + retry_count, 8) = min(6, 8) = 6- mock_sleep.assert_called_once_with(6)-- def test_wait_time_capped_at_8(self):- agent = _make_agent(provider="custom")- error = _make_transport_error("ReadTimeout")- with patch("agent.process_bootstrap.OpenAI", return_value=MagicMock()), \- patch("time.sleep") as mock_sleep:- agent._try_recover_primary_transport(- error, retry_count=10, max_retries=3,- )- # wait_time = min(3 + 10, 8) = 8- mock_sleep.assert_called_once_with(8)def test_survives_rebuild_failure(self):@@ -692,16 +557,6 @@ class TestTryRecoverPrimaryTransport:class TestRestoreInRunConversation:"""Verify the hook in run_conversation() calls _restore_primary_runtime."""- def test_restore_called_at_turn_start(self):- agent = _make_agent()- agent._fallback_activated = True-- with patch.object(agent, "_restore_primary_runtime", return_value=True) as mock_restore, \- patch.object(agent, "run_conversation", wraps=None) as _:- # We can't easily run the full conversation, but we can verify- # the method exists and is callable- agent._restore_primary_runtime()- mock_restore.assert_called_once()def test_full_cycle_fallback_then_restore(self):"""Simulate: turn 1 activates fallback, turn 2 restores primary."""@@ -821,13 +676,6 @@ class TestSwitchModelRequestOverridesSnapshot:api_key=kwargs.get("api_key", "sk-test-1234567890"),)- def test_switch_snapshot_carries_request_overrides(self):- overrides = {"extra_body": {"reasoning": {"effort": "high"}}}- agent = _make_agent(request_overrides=overrides)- self._switch(agent)- rt = agent._primary_runtime- assert rt.get("request_overrides") == overrides- assert rt["request_overrides"] is not agent.request_overridesdef test_switch_then_recover_restores_current_overrides(self):"""After /model switch, a transport recovery must reinstate thediff --git a/tests/agent/test_proactive_prune_config.py b/tests/agent/test_proactive_prune_config.pyindex 320ac1b35a6..215adebe313 100644--- a/tests/agent/test_proactive_prune_config.py+++ b/tests/agent/test_proactive_prune_config.py@@ -59,12 +59,6 @@ def _make_agent(monkeypatch, tmp_path: Path, **prune_keys):class TestProactivePruneConfig:- def test_default_is_disabled_when_unset(self, monkeypatch, tmp_path):- agent = _make_agent(monkeypatch, tmp_path)- cc = agent.context_compressor- assert cc.proactive_prune_tokens == 0- assert cc.proactive_prune_min_result_chars == 8000- assert cc.proactive_prune_min_reclaim_tokens == 4096def test_custom_values_are_honored(self, monkeypatch, tmp_path):agent = _make_agent(diff --git a/tests/agent/test_proactive_prune_rearm_threshold.py b/tests/agent/test_proactive_prune_rearm_threshold.pyindex 9d49eb5626f..6c0bfb1ce6f 100644--- a/tests/agent/test_proactive_prune_rearm_threshold.py+++ b/tests/agent/test_proactive_prune_rearm_threshold.py@@ -185,43 +185,5 @@ def test_under_threshold_no_op_is_not_warned(caplog) -> None:assert not _over_threshold_warnings(caplog)-def test_lockout_warns_again_after_rearm_reset(caplog) -> None:- """A full compaction (or session rebind / model recalibration) zeroes the- rearm mark. An identical lockout afterwards must warn again — the dedup key- must not outlive the reclamation that should have cleared it."""- c = _compressor(proactive_prune_min_reclaim_tokens=10_000_000)- msgs = _history()- billed = c.threshold_tokens + 5_000-- with caplog.at_level(logging.WARNING, logger="agent.context_compressor"):- c.prune_tool_results_only(msgs, current_tokens=billed)- assert len(_over_threshold_warnings(caplog)) == 1- # Same state, same key (reason, rearm=0): deduped.- with caplog.at_level(logging.WARNING, logger="agent.context_compressor"):- c.prune_tool_results_only(msgs, current_tokens=billed)- assert len(_over_threshold_warnings(caplog)) == 1-- # A public rearm boundary (same helper as compress(), on_session_end,- # bind_session_state and update_model): pins the wiring, not just the body.- c.on_session_reset()- assert c._proactive_prune_rearm_tokens == 0-- with caplog.at_level(logging.WARNING, logger="agent.context_compressor"):- c.prune_tool_results_only(msgs, current_tokens=billed)- assert len(_over_threshold_warnings(caplog)) == 2, (- "lockout after a rearm reset was deduped against the stale key"- )-def test_dropping_under_threshold_clears_dedup_key(caplog) -> None:- """Back under threshold (e.g. compaction elsewhere shrank the request), the- key is released so the next over-threshold lockout is reported."""- c = _compressor(proactive_prune_min_reclaim_tokens=10_000_000)- msgs = _history()- billed = c.threshold_tokens + 5_000-- with caplog.at_level(logging.WARNING, logger="agent.context_compressor"):- c.prune_tool_results_only(msgs, current_tokens=billed)- c.prune_tool_results_only(msgs, current_tokens=c.threshold_tokens - 1)- c.prune_tool_results_only(msgs, current_tokens=billed)- assert len(_over_threshold_warnings(caplog)) == 2diff --git a/tests/agent/test_proactive_prune_restart_safety.py b/tests/agent/test_proactive_prune_restart_safety.pyindex 83adb437e5b..0ae91779ff1 100644--- a/tests/agent/test_proactive_prune_restart_safety.py+++ b/tests/agent/test_proactive_prune_restart_safety.py@@ -246,28 +246,3 @@ def test_patch_session_model_config_merge_and_delete(tmp_path: Path) -> None:db.patch_session_model_config(session_id, {})-def test_incapable_store_short_circuits_before_prune_scan(tmp_path: Path) -> None:- """A bound store without archive_and_compact must not pay the prune scan."""- db = SessionDB(db_path=tmp_path / "state.db")- session_id = "INCAPABLE_STORE_FAST_NOOP"- db.create_session(session_id, source="telegram")- db.append_messages_batch(session_id, _history())- agent = _build_agent(db, session_id)- _configure_pruning(agent)- compressor = agent.context_compressor-- class _NoArchiveStore:- pass-- compressor.bind_session_state(_NoArchiveStore(), session_id)- messages = db.get_messages_as_conversation(session_id)- with patch.object(- type(compressor), "_prune_old_tool_results",- side_effect=AssertionError("scan must not run for incapable stores"),- ):- result, count = compressor.prune_tool_results_only(- messages, current_tokens=120_000,- )-- assert result is messages- assert count == 0diff --git a/tests/agent/test_proactive_tool_result_pruning.py b/tests/agent/test_proactive_tool_result_pruning.pyindex 2a963f7f015..bbb5434f733 100644--- a/tests/agent/test_proactive_tool_result_pruning.py+++ b/tests/agent/test_proactive_tool_result_pruning.py@@ -87,16 +87,6 @@ def test_prunes_below_compression_threshold():assert m["content"] != _PRUNED_TOOL_PLACEHOLDER # informative, not a blank placeholder----------def test_idempotent():c = _compressor(proactive_prune_tokens=48_000, proactive_prune_min_result_chars=8_000)msgs = _build(8, big_indices={0, 1, 2})@@ -179,25 +169,14 @@ def test_successful_full_compression_resets_proactive_runway():assert result is not fresh----# ---------------------------------------------------------------------------# Salvage follow-ups: no-op caller contract, prompt-cache hysteresis gate,# no-orphan pairing invariant, and the default-off behavior pin.# ----------------------------------------------------------------------------------def test_min_reclaim_gate_default_and_clamp():- """Default 4096; negative/None coerce to disabled (0)."""- assert _compressor().proactive_prune_min_reclaim_tokens == 4096+def test_min_reclaim_gate_clamp():+ """Negative/None coerce to disabled (0)."""assert _compressor(proactive_prune_min_reclaim_tokens=0).proactive_prune_min_reclaim_tokens == 0assert _compressor(proactive_prune_min_reclaim_tokens=-5).proactive_prune_min_reclaim_tokens == 0assert _compressor(proactive_prune_min_reclaim_tokens=None).proactive_prune_min_reclaim_tokens == 0@@ -239,8 +218,3 @@ def test_unset_config_zero_behavior_change():assert pruned == 0assert result is msgsassert msgs == snapshot # input never mutated- # And the compression-path caller still prunes at the 200-char default floor- # (min_prune_chars default unchanged).- import inspect- sig = inspect.signature(c._prune_old_tool_results)- assert sig.parameters["min_prune_chars"].default == 200diff --git a/tests/agent/test_probe_cache_followups.py b/tests/agent/test_probe_cache_followups.pyindex 32ac7ceee18..7cb390fd99c 100644--- a/tests/agent/test_probe_cache_followups.py+++ b/tests/agent/test_probe_cache_followups.py@@ -57,23 +57,6 @@ class TestOllamaApiShowCaching:assert client.post.call_count == 2 # None was NOT cached- def test_ttl_expiry_reprobes(self):- """After the 30s TTL lapses, the next call must hit the network again."""- from agent import model_metadata- from agent.model_metadata import _query_ollama_api_show- import time as _time-- client = _client_mock(_mock_show_response(131072))- with patch("httpx.Client", return_value=client):- _query_ollama_api_show("llama3", "http://127.0.0.1:11434")- # Age the entry past the TTL.- ((key, (val, _ts)),) = list(model_metadata._LOCAL_CTX_PROBE_CACHE.items())- model_metadata._LOCAL_CTX_PROBE_CACHE[key] = (- val, _time.monotonic() - model_metadata._LOCAL_CTX_PROBE_TTL_SECONDS - 1,- )- _query_ollama_api_show("llama3", "http://127.0.0.1:11434")-- assert client.post.call_count == 2 # expired entry re-probed@@ -99,17 +82,6 @@ class TestDetectLocalServerTypeCache:client.get.side_effect = _getreturn client- def test_second_call_served_from_cache(self):- from agent.model_metadata import detect_local_server_type-- client = self._get_client()- with patch("httpx.Client", return_value=client):- first = detect_local_server_type("http://127.0.0.1:11434")- calls_after_first = client.get.call_count- second = detect_local_server_type("http://127.0.0.1:11434")-- assert first == second == "ollama"- assert client.get.call_count == calls_after_first # no new HTTP trafficdef test_ttl_expiry_allows_server_swap_redetection(self):"""Stopping Ollama and starting LM Studio on the same port must be@@ -299,27 +271,18 @@ class TestDetectServerTypeNegativeCaching:def test_negative_verdict_is_cached_in_memory(self):from agent.model_metadata import detect_local_server_type- from agent import model_metadataclient = self._client_all_401()with patch("httpx.Client", return_value=client):assert detect_local_server_type("http://remote:8080/v1") is None+ after_first = client.get.call_countassert detect_local_server_type("http://remote:8080/v1") is None# Second call served from the in-memory negative entry: the- # waterfall ran exactly once (5 GETs), not twice.- assert client.get.call_count == 5- assert "http://remote:8080" in model_metadata._endpoint_probe_path_cache-- def test_negative_verdict_not_written_to_disk(self):- from agent.model_metadata import detect_local_server_type- from agent import model_metadata+ # waterfall ran exactly once, not twice.+ assert after_first > 0+ assert client.get.call_count == after_first- with patch("httpx.Client", return_value=self._client_all_401()), patch.object(- model_metadata, "_local_probe_disk_put"- ) as disk_put:- assert detect_local_server_type("http://remote2:8080/v1") is None- disk_put.assert_not_called()def test_negative_verdict_expires_quickly(self):"""The short failure TTL keeps a transient failure recoverable."""@@ -330,6 +293,7 @@ class TestDetectServerTypeNegativeCaching:client = self._client_all_401()with patch("httpx.Client", return_value=client):assert detect_local_server_type("http://remote3:8080/v1") is None+ after_first = client.get.call_count# Age the entry past the failure TTL.model_metadata._endpoint_probe_path_cache["http://remote3:8080"] = (None,@@ -339,6 +303,6 @@ class TestDetectServerTypeNegativeCaching:)assert detect_local_server_type("http://remote3:8080/v1") is None- assert client.get.call_count == 10 # waterfall re-ran after expiry+ assert client.get.call_count == 2 * after_first # waterfall re-ran after expirydiff --git a/tests/agent/test_prompt_builder.py b/tests/agent/test_prompt_builder.pyindex 8e2e5b45758..fabf06bc42b 100644--- a/tests/agent/test_prompt_builder.py+++ b/tests/agent/test_prompt_builder.py@@ -1,7 +1,5 @@"""Tests for agent/prompt_builder.py — context scanning, truncation, skills index."""-import builtins-import importlibimport loggingimport osimport sys@@ -22,20 +20,8 @@ from agent.prompt_builder import (build_skills_system_prompt,build_context_files_prompt,CONTEXT_FILE_MAX_CHARS,- _dynamic_context_file_max_chars,_get_context_file_max_chars,- _CONTEXT_FILE_DYNAMIC_CEILING,- DEFAULT_AGENT_IDENTITY,drain_truncation_warnings,- TOOL_USE_ENFORCEMENT_GUIDANCE,- TOOL_USE_ENFORCEMENT_MODELS,- OPENAI_MODEL_EXECUTION_GUIDANCE,- PARALLEL_TOOL_CALL_GUIDANCE,- GOOGLE_MODEL_OPERATIONAL_GUIDANCE,- MEMORY_GUIDANCE,- SESSION_SEARCH_GUIDANCE,- PLATFORM_HINTS,- WSL_ENVIRONMENT_HINT,)@@ -61,30 +47,6 @@ def _drain_truncation_warnings():# =========================================================================-class TestGuidanceConstants:- def test_memory_guidance_keeps_form_rule_and_routing(self):- """Dieted (#95681): WHAT belongs in memory is the memory tool- schema's job (taught on every call). This block keeps only the- declarative-form rule and the staleness/skills routing."""- from agent.prompt_builder import MEMORY_GUIDANCE-- assert "declarative facts" in MEMORY_GUIDANCE- assert "imperative phrasing" in MEMORY_GUIDANCE- assert "stale within a week" in MEMORY_GUIDANCE- # Skills are the default home for task-learned knowledge (incl. the- # user's preferences/corrections for that work); memory is the narrow- # every-session exception. The routing rule must LEAD, not trail.- assert MEMORY_GUIDANCE.index("Skills come first") < MEMORY_GUIDANCE.index("Memory is the narrow exception")- assert "preferences and corrections" in MEMORY_GUIDANCE- assert "Save proactively" not in MEMORY_GUIDANCE- assert "workflows belong" in MEMORY_GUIDANCE- # The category/SKIP curricula must NOT be re-taught here.- assert "PR numbers" not in MEMORY_GUIDANCE- assert "tool quirks" not in MEMORY_GUIDANCE-- def test_session_search_guidance_is_simple_cross_session_recall(self):- assert "relevant cross-session context exists" in SESSION_SEARCH_GUIDANCE- assert "recent turns of the current session" not in SESSION_SEARCH_GUIDANCE# =========================================================================@@ -168,19 +130,6 @@ class TestTruncateContent:- def test_truncation_warning_points_to_config_key(self, monkeypatch):- def fake_load_config():- return {"context_file_max_chars": 120}-- monkeypatch.setattr("hermes_cli.config.load_config", fake_load_config)- monkeypatch.setattr("hermes_cli.config.load_config_readonly", fake_load_config)-- _truncate_content("x" * 180, "warning.md")-- warnings = drain_truncation_warnings()- assert len(warnings) == 1- assert "context_file_max_chars" in warnings[0]- assert "CONTEXT_FILE_MAX_CHARS" not in warnings[0]def test_warnings_isolated_across_contexts(self, monkeypatch):"""Truncation warnings accumulate per-context — a concurrent build in@@ -223,12 +172,6 @@ class TestDynamicContextFileCap:monkeypatch.setattr("hermes_cli.config.load_config_readonly", lambda: {})- def test_dynamic_scales_above_floor_for_large_window(self):- # 200K-token window → ~48K (200000 * 4 * 0.06), well above the floor- # and above Codex's 32 KiB project_doc default.- cap = _dynamic_context_file_max_chars(200_000)- assert cap == 48_000- assert cap > CONTEXT_FILE_MAX_CHARS@@ -303,23 +246,6 @@ class TestParseSkillFile:-class TestPromptBuilderImports:- def test_module_import_does_not_eagerly_import_skills_tool(self, monkeypatch):- original_import = builtins.__import__-- def guarded_import(name, globals=None, locals=None, fromlist=(), level=0):- if name == "tools.skills_tool" or (- name == "tools" and fromlist and "skills_tool" in fromlist- ):- raise ModuleNotFoundError("simulated optional tool import failure")- return original_import(name, globals, locals, fromlist, level)-- monkeypatch.delitem(sys.modules, "agent.prompt_builder", raising=False)- monkeypatch.setattr(builtins, "__import__", guarded_import)-- module = importlib.import_module("agent.prompt_builder")-- assert hasattr(module, "build_skills_system_prompt")# =========================================================================@@ -486,16 +412,6 @@ class TestBuildContextFilesPrompt:result = build_context_files_prompt(cwd=str(sub), skip_soul=True)assert result.count("Same rules everywhere.") == 1- def test_agents_md_single_file_output_unchanged(self, tmp_path):- # Zero-regression guarantee: with one AGENTS.md at cwd (git repo or- # not), the section is byte-identical to historical single-file form.- from agent.prompt_builder import _load_agents_md-- (tmp_path / ".git").mkdir()- sub = tmp_path / "sub"- sub.mkdir()- (sub / "AGENTS.md").write_text("Only file.")- assert _load_agents_md(sub) == "## AGENTS.md\n\nOnly file."def test_agents_md_no_git_root_stays_cwd_only(self, tmp_path):# Without a git root, parents are never consulted (no picking up an@@ -613,7 +529,6 @@ class TestFindHermesMd:def test_unreadable_parent_is_treated_as_no_git_root(self, tmp_path, monkeypatch):"""A parent the process cannot stat (#8751) must not raise out of prompt construction."""- import os as _osproject = tmp_path / "locked" / "proj"project.mkdir(parents=True)real_exists = Path.exists@@ -679,19 +594,6 @@ class TestFindGitRoot:sub.mkdir(parents=True)assert _find_git_root(sub) == tmp_path- def test_returns_none_without_git(self, tmp_path):- # Create an isolated dir tree with no .git anywhere in it.- # tmp_path itself might be under a git repo, so we test with- # a directory that has its own .git higher up to verify the- # function only returns an actual .git directory it finds.- isolated = tmp_path / "no_git_here"- isolated.mkdir()- # We can't fully guarantee no .git exists above tmp_path,- # so just verify the function returns a Path or None.- result = _find_git_root(isolated)- # If result is not None, it must actually contain .git- if result is not None:- assert (result / ".git").exists()class TestCursorrulesCandidates:@@ -729,70 +631,6 @@ class TestStripYamlFrontmatter:# =========================================================================-class TestPromptBuilderConstants:--- def test_cli_and_tui_hints_flag_local_only_cron(self):- """#51568 — cron jobs from CLI/TUI sessions don't deliver back into- the session, so the agent must be told up front not to promise it."""- for key in ("cli", "tui"):- hint = PLATFORM_HINTS[key]- assert "LOCAL-ONLY" in hint- assert "deliver" in hint---- def test_api_server_hint_scopes_media_tag_guidance(self):- """api_server MEDIA: interception is partial (#68402, corrected):- _resolve_media_to_data_urls (gateway/platforms/api_server.py) inlines- small image MEDIA: tags as base64 data URLs on the chat, completions,- and responses endpoints — but non-image files are never resolved- (_MEDIA_IMG_EXT is image-only) and the /v1/runs handler never calls- the resolver at all. The hint must teach BOTH halves: images work via- MEDIA:, everything else needs a plain path in the response text."""- hint = PLATFORM_HINTS["api_server"]- # Images ARE intercepted: inlined as data URLs.- assert "MEDIA:" in hint- assert "inlined" in hint.lower()- assert "data" in hint.lower() # data URLs- # The gaps: non-image files and the runs endpoint.- assert "non-image" in hint.lower()- assert "runs" in hint.lower()- # Fallback guidance: plain file path in the response text.- assert "plain" in hint.lower()-- def test_markdown_converting_platform_hints_do_not_forbid_markdown(self):- """#12224 — WhatsApp (Baileys) and Signal adapters actively convert- markdown to native formatting (gateway/platforms/whatsapp_common.py- format_message + signal_format.markdown_to_signal: bold, italic,- strikethrough, headers, bullets). Their hints previously told the- agent "do not use markdown", which made it strip bullets/bold the- adapter would have rendered. The hint must affirm markdown, not- forbid it."""- for key in ("whatsapp", "signal"):- hint = PLATFORM_HINTS[key]- assert "do not use markdown" not in hint.lower()- assert "markdown" in hint.lower()-- def test_cli_hint_does_not_suggest_media_tags(self):- # Regression: MEDIA:/path tags are intercepted only by messaging- # gateway platforms. On the CLI they render as literal text and- # confuse users. The CLI hint must steer the agent away from them.- cli_hint = PLATFORM_HINTS["cli"]- assert "MEDIA:" in cli_hint, (- "CLI hint should mention MEDIA: in order to tell the agent "- "NOT to use it (negative guidance)."- )- # Must contain explicit "don't" language near the MEDIA reference.- assert any(- marker in cli_hint.lower()- for marker in ("do not emit media", "not intercepted", "do not", "don't")- ), "CLI hint should explicitly discourage MEDIA: tags."- # Messaging hints should still advertise MEDIA: positively (sanity- # check that this test is calibrated correctly).- # Dieted (#95681): messaging hints now share the _MEDIA_NATIVE- # spine ("write MEDIA:/absolute/path..."), not per-hint prose.- assert "MEDIA:/absolute/path" in PLATFORM_HINTS["telegram"]@@ -857,44 +695,6 @@ class TestEnvironmentHints:assert f"Current working directory: {tmp_path}" in _pb.build_environment_hints()- def test_probe_remote_backend_imports_real_factory(self, monkeypatch):- """Regression for #53667: the probe imported a nonexistent- ``get_environment`` from ``tools.environments`` and always died with- ``ImportError: cannot import name 'get_environment'`` (cosmetic — it- only dropped the live backend description to a static fallback). The- real factory is ``_create_environment`` in ``tools.terminal_tool``;- the probe must import and call THAT, returning a parsed line instead- of None."""- import agent.prompt_builder as _pb-- monkeypatch.setenv("TERMINAL_ENV", "docker")- _pb._BACKEND_PROBE_CACHE.clear()-- class _FakeEnv:- def execute(self, cmd, timeout=None):- return {- "returncode": 0,- "output": (- "os=Linux\nkernel=6.8.0\nhome=/root\n"- "cwd=/workspace\nuser=root\n"- ),- }-- created = {}-- def _fake_create_environment(*, env_type, **kwargs):- created["env_type"] = env_type- return _FakeEnv()-- # Patch the REAL factory in tools.terminal_tool_backends — the probe imports it- # locally, so the import itself must succeed (the bug was here).- import tools.terminal_tool_backends as _tt- monkeypatch.setattr(_tt, "_create_environment", _fake_create_environment)-- line = _pb._probe_remote_backend("docker")- assert created.get("env_type") == "docker"- assert line is not None- assert "Linux 6.8.0" in linedef test_remote_backend_probe_carries_no_user_home_cwd(self, monkeypatch):"""#117262: the sandbox's user, $HOME and cwd are user-identifying metadata that@@ -1066,14 +866,6 @@ class TestEnvironmentHints:- def test_remote_backend_list_covers_known_sandboxes(self):- """Regression guard: if someone adds a remote backend, they must list it here."""- import agent.prompt_builder as _pb- for backend in ("docker", "singularity", "modal", "daytona", "ssh", "vercel_sandbox"):- assert backend in _pb._REMOTE_TERMINAL_BACKENDS, (- f"{backend!r} must be in _REMOTE_TERMINAL_BACKENDS so its host "- f"info is suppressed in the system prompt"- )# =========================================================================@@ -1148,108 +940,18 @@ class TestBuildSkillsSystemPromptConditional:# =========================================================================-class TestToolUseEnforcementGuidance:- def test_guidance_mentions_tool_calls(self):- assert "tool call" in TOOL_USE_ENFORCEMENT_GUIDANCE.lower()--- def test_guidance_requires_action(self):- assert "MUST" in TOOL_USE_ENFORCEMENT_GUIDANCE--------class TestOpenAIModelExecutionGuidance:- """Tests for GPT/Codex-specific execution discipline guidance."""- def test_guidance_covers_verification(self):- text = OPENAI_MODEL_EXECUTION_GUIDANCE.lower()- assert "verification" in text or "verify" in text- assert "correctness" in text- def test_guidance_is_string(self):- assert isinstance(OPENAI_MODEL_EXECUTION_GUIDANCE, str)- assert len(OPENAI_MODEL_EXECUTION_GUIDANCE) > 100-- def test_guidance_covers_external_write_readback(self):- text = OPENAI_MODEL_EXECUTION_GUIDANCE.lower()- assert "read" in text and "back" in text- assert "successful tool call is not a successful task" in text-- def test_guidance_covers_count_reconciliation(self):- text = OPENAI_MODEL_EXECUTION_GUIDANCE.lower()- assert "has_more" in text- assert "hard assertions" in text-- def test_guidance_covers_literal_preservation(self):- text = OPENAI_MODEL_EXECUTION_GUIDANCE.lower()- assert "normalize" in text- assert "malformed" in text-- def test_guidance_covers_retry_differently(self):- text = OPENAI_MODEL_EXECUTION_GUIDANCE.lower()- assert "suspiciously narrow" in text- assert "retry" in text-- def test_guidance_gates_completion_on_verification(self):- text = OPENAI_MODEL_EXECUTION_GUIDANCE.lower()- assert "plausible subset" in text---class TestExecutionGuidanceModels:- """Behavior contracts for the default auto-match model list."""-- def test_includes_historical_families(self):- from agent.prompt_builder import EXECUTION_GUIDANCE_MODELS- for fam in ("gpt", "codex", "grok"):- assert fam in EXECUTION_GUIDANCE_MODELS-- def test_includes_composio_eval_families(self):- from agent.prompt_builder import EXECUTION_GUIDANCE_MODELS- for fam in ("deepseek", "kimi", "qwen", "glm", "minimax", "mimo", "mistral"):- assert fam in EXECUTION_GUIDANCE_MODELS-- def test_muse_spark_gets_both_guidance_blocks(self):- # Muse Spark closes the turn after a chat-only response on defaults- # (#96550) — it needs tool-use enforcement AND execution guidance.- from agent.prompt_builder import EXECUTION_GUIDANCE_MODELS- assert any(p in "meta/muse-spark-1.3-contributor" for p in TOOL_USE_ENFORCEMENT_MODELS)- assert any(p in "meta/muse-spark-1.3-contributor" for p in EXECUTION_GUIDANCE_MODELS)-- def test_excludes_google_and_claude(self):- # Gemini/Gemma get GOOGLE_MODEL_OPERATIONAL_GUIDANCE instead;- # Claude doesn't exhibit the targeted failure modes.- from agent.prompt_builder import EXECUTION_GUIDANCE_MODELS- for fam in ("gemini", "gemma", "claude"):- assert fam not in EXECUTION_GUIDANCE_MODELS---class TestParallelToolCallGuidance:- """Behavior contracts for the universal parallel-tool-call guidance block.-- Asserts the invariants the block must satisfy (steer batching, scope to- independent calls, stay short for the cached prompt) rather than freezing- its exact wording.- """- def test_is_nonempty_string(self):- assert isinstance(PARALLEL_TOOL_CALL_GUIDANCE, str)- assert PARALLEL_TOOL_CALL_GUIDANCE.strip()- def test_has_a_heading(self):- # Heading delimits it as its own section in the assembled prompt.- assert PARALLEL_TOOL_CALL_GUIDANCE.lstrip().startswith("#")diff --git a/tests/agent/test_prompt_cache_scope.py b/tests/agent/test_prompt_cache_scope.pyindex c261a487ad4..ed7c1f6146b 100644--- a/tests/agent/test_prompt_cache_scope.py+++ b/tests/agent/test_prompt_cache_scope.py@@ -46,9 +46,6 @@ class TestResolvePromptCacheScope:def test_no_db_falls_back_to_physical_id(self):assert resolve_prompt_cache_scope(_agent("root-sess")) == "root-sess"- def test_unrotated_session_is_its_own_scope(self, db):- db.create_session("root-sess", source="webui")- assert resolve_prompt_cache_scope(_agent("root-sess", db)) == "root-sess"def test_rotation_child_inherits_root_scope(self, db):"""THE fix: scope survives a compression rotation boundary."""@@ -224,13 +221,6 @@ class TestRotationContinuityEndToEnd:assert key_before == key_after- def test_unrelated_sessions_keep_distinct_keys(self, db):- db.create_session("conv-a", source="webui")- db.create_session("conv-b", source="webui")-- assert self._key_for(_agent("conv-a", db)) != self._key_for(- _agent("conv-b", db)- )def test_sibling_forks_keep_distinct_keys(self, db):db.create_session("parent-sess", source="webui")@@ -360,32 +350,6 @@ class TestTransportWiring:assert k1["prompt_cache_key"] == k2["prompt_cache_key"]-class TestAuxiliaryRuntimeThreading:- def test_set_runtime_main_carries_cache_scope(self):- import agent.auxiliary_client as aux-- token = aux.set_runtime_main(- "openrouter",- "gpt-5.5",- session_id="rotated-1",- cache_scope="root-sess",- )- try:- assert aux._runtime_main_value("cache_scope") == "root-sess"- assert aux._runtime_main_value("session_id") == "rotated-1"- finally:- aux.reset_runtime_main(token)-- def test_cache_scope_defaults_empty(self):- import agent.auxiliary_client as aux-- token = aux.set_runtime_main("openrouter", "gpt-5.5", session_id="s-1")- try:- assert aux._runtime_main_value("cache_scope") == ""- finally:- aux.reset_runtime_main(token)--class TestPerResponseRunNonceIsolation:"""Issue #96570 — hosts that mint one physical session per RESPONSE.diff --git a/tests/agent/test_prompt_cache_ttl_propagation.py b/tests/agent/test_prompt_cache_ttl_propagation.pyindex 4a8fd7ce20a..66a871e85ae 100644--- a/tests/agent/test_prompt_cache_ttl_propagation.py+++ b/tests/agent/test_prompt_cache_ttl_propagation.py@@ -11,8 +11,6 @@ contract (every fallback activation must restart the outer iteration so thepre-API preflight re-runs against the fallback's context window)."""-import ast-import inspectdef _collect_cache_controls(obj):@@ -173,149 +171,6 @@ class TestMoACacheControlThreadsTtl:assert all("ttl" not in m for m in markers)-class TestFailoverRestartsPreflight:- """#84733: a fallback provider switch must re-run the pre-API preflight.-- ``_try_activate_fallback`` already shrinks the compressor's context- window to the fallback's; the pre-API preflight runs at the top of the- OUTER iteration loop, before the retry loop. So the restart discipline- is loop-aware:-- - Sites INSIDE the retry loop (``while retry_count < max_retries``)- must ``break`` out of it with ``restart_with_rebuilt_messages`` set,- so the handler after the retry loop refunds the budget and- ``continue``s the outer iteration (which re-runs the preflight).- A plain ``continue`` there would only re-fire the retry loop and- skip the preflight — the original bug.- - Sites DIRECTLY in the outer loop must ``continue`` — the next outer- iteration re-runs the preflight already. A ``break`` there would- exit the conversation loop and end the turn without ever calling- the just-activated fallback.-- Source-level guard: parsing the function is cheap, and the assertion- encodes the bug class — a new failover site added with the wrong- restart statement for its loop fails here on purpose.- """-- def test_every_fallback_activation_restarts_preflight(self):- """The retry-loop body now lives in verdict helpers (``turn_api_call``,- ``turn_api_error``, ``turn_response_check``): a fallback activation there must- end in ``return _verdict("break")`` — the loop's ``break`` — so the- ``restart_with_rebuilt_messages`` handler after the retry loop refunds the- budget and re-runs the preflight. Every ``_try_activate_fallback`` reference- must be a direct ``if agent._try_activate_fallback():`` site so this guard can- bind its restart discipline (#84733)."""- from agent import turn_api_call, turn_api_error, turn_response_check-- def _verdict_kind(stmt):- if (- isinstance(stmt, ast.Return)- and isinstance(stmt.value, ast.Call)- and isinstance(stmt.value.func, ast.Name)- and stmt.value.func.id == "_verdict"- and stmt.value.args- and isinstance(stmt.value.args[0], ast.Constant)- ):- return stmt.value.args[0].value- return None-- seen = 0- for mod in (turn_api_call, turn_api_error, turn_response_check):- tree = ast.parse(inspect.getsource(mod))- fallback_ifs = [- node- for node in ast.walk(tree)- if isinstance(node, ast.If)- and isinstance(node.test, ast.Call)- and isinstance(node.test.func, ast.Attribute)- and node.test.func.attr == "_try_activate_fallback"- ]- all_refs = [- node- for node in ast.walk(tree)- if isinstance(node, ast.Attribute)- and node.attr == "_try_activate_fallback"- ]- assert len(all_refs) == len(fallback_ifs), (- f"{mod.__name__}: every _try_activate_fallback reference must be a "- "direct `if agent._try_activate_fallback(...):` site (#84733)"- )- for node in fallback_ifs:- kinds = [_verdict_kind(stmt) for stmt in node.body]- assert "break" in kinds, (- f"{mod.__name__}: retry-loop fallback activation must return "- "_verdict(\"break\") so the restart-with-rebuilt-messages handler "- "re-runs the pre-API preflight against the fallback's context "- "window (#84733)"- )- assert "continue" not in kinds, (- f"{mod.__name__}: a `continue` verdict would only re-fire the retry "- "loop and skip the preflight (#84733)"- )- seen += len(fallback_ifs)- assert seen >= 5, "expected the retry-loop _try_activate_fallback sites"-- # The restart consumer must re-issue the OUTER iteration (`continue` verdict).- from agent import turn_iteration_prep-- tree = ast.parse(inspect.getsource(turn_iteration_prep.apply_retry_restarts))- handlers = [- node- for node in ast.walk(tree)- if isinstance(node, ast.If)- and isinstance(node.test, ast.Attribute)- and node.test.attr == "restart_with_rebuilt_messages"- ]- assert handlers and all(- any(_verdict_kind(stmt) == "continue" for stmt in node.body) for node in handlers- ), "the restart handler must `continue` the outer iteration (#84733)"-- def test_restart_handler_clears_preflight_block(self):- """The single consumer of restart_with_rebuilt_messages must clear- _preflight_compression_blocked, so every retry-loop failover gets a- fresh preflight against the fallback's context window (#84733)."""- from agent import turn_iteration_prep-- tree = ast.parse(inspect.getsource(turn_iteration_prep.apply_retry_restarts))- handlers = [- node- for node in ast.walk(tree)- if isinstance(node, ast.If)- and isinstance(node.test, ast.Attribute)- and node.test.attr == "restart_with_rebuilt_messages"- ]- assert handlers, "expected the restart_with_rebuilt_messages handler"- consumer = [- node- for node in handlers- if any(- isinstance(stmt, ast.Assign)- and any(- isinstance(t, ast.Attribute)- and t.attr == "restart_with_rebuilt_messages"- for t in stmt.targets- )- for stmt in node.body- )- ]- assert consumer, "expected the flag-consuming handler"- for node in consumer:- assert any(- isinstance(stmt, ast.Assign)- and any(- isinstance(t, ast.Name)- and t.id == "_preflight_compression_blocked"- for t in stmt.targets- )- and isinstance(stmt.value, ast.Constant)- and stmt.value.value is False- for stmt in node.body- ), (- "the restart handler must clear _preflight_compression_blocked "- "so the re-run preflight isn't skipped (#84733)"- )--class TestAuxFallbackReplanThreadsTtl:"""#84733 follow-up: the auxiliary fallback replan path threads theconfigured tier too — it has no live agent, so it reads the samediff --git a/tests/agent/test_prompt_caching.py b/tests/agent/test_prompt_caching.pyindex 99ca76245dc..ea317196339 100644--- a/tests/agent/test_prompt_caching.py+++ b/tests/agent/test_prompt_caching.py@@ -202,10 +202,6 @@ class TestApplyCacheMarker:assert "cache_control" not in msg----def test_string_content_wrapped_in_list(self):msg = {"role": "user", "content": "Hello"}_apply_cache_marker(msg, MARKER)@@ -216,8 +212,6 @@ class TestApplyCacheMarker:assert msg["content"][0]["cache_control"] == MARKER--class TestCanCarryMarker:@@ -372,8 +366,6 @@ class TestApplyAnthropicCacheControl:assert result[3]["content"][0]["cache_control"] == {"type": "ephemeral"}--def test_1h_ttl(self):msgs = [{"role": "system", "content": "System prompt"}]result = apply_anthropic_cache_control(msgs, cache_ttl="1h")@@ -382,9 +374,6 @@ class TestApplyAnthropicCacheControl:assert sys_content[0]["cache_control"]["ttl"] == "1h"---class TestNormalizationOrdering:"""The conversation loop normalizes message text for prefix stability andinjects cache breakpoints. Marking must happen AFTER normalization.@@ -422,26 +411,6 @@ class TestNormalizationOrdering:assert in_window == out_of_window- def test_cache_marking_runs_after_every_message_mutation(self):- """Ordering invariant, locked against regression."""- import inspect-- from agent import turn_request_assembly-- src = inspect.getsource(turn_request_assembly)- # Anchor on the call-block request plan, not the retry helper.- anchor = src.index("Build the request-local cache sections")- mark = src.index("build_prompt_cache_plan(\n", anchor)- for earlier in (- 'am["content"].strip()', # whitespace normalization- "_sanitize_api_messages(api_messages)", # orphan sweep- "_drop_thinking_only_and_merge_users(", # drop / merge- "_sanitize_messages_surrogates(api_messages)",- ):- assert src.index(earlier) < mark, (- f"{earlier!r} must run before cache breakpoints are injected"- )-class TestStripAnthropicCacheControl:"""strip must undo decoration so failover can re-render for a new policy."""@@ -555,21 +524,6 @@ class TestEffectiveCacheTtl:assert effective_cache_ttl("1h", provider="opencode", model="qwen3.6-plus") == "5m"assert effective_cache_ttl("1h", provider="opencode-zen", model="qwen3.6-plus") == "5m"- def test_ttl_allowlist_is_separate_from_cache_layout_optin(self):- """Regression guard for the trap in the original shared-set design.-- ALIBABA_FAMILY_PROVIDERS drives the cache-marker-layout OPT-IN. Reusing- it for the TTL clamp means narrowing the clamp DISABLES caching instead- of extending its TTL.- """- from agent.prompt_caching import (- ALIBABA_FAMILY_PROVIDERS,- MEASURED_1H_PROVIDERS,- )-- assert "opencode-go" in ALIBABA_FAMILY_PROVIDERS- assert "opencode-go" in MEASURED_1H_PROVIDERS- assert not (MEASURED_1H_PROVIDERS & {"alibaba"})def test_marker_built_from_clamped_ttl_has_no_1h_key(self):marker = _build_marker(effective_cache_ttl("1h", provider="opencode", model="qwen3.6-plus"))@@ -652,8 +606,6 @@ class TestApplyIdempotency:assert _count_cache_markers(result, []) <= 4--class TestOpenCodeGoOneHourPrecedence:"""Precedence + eligibility guards for the opencode-go 1h allowance.@@ -685,10 +637,6 @@ class TestOpenCodeGoOneHourPrecedence:# -- the deployed case ---------------------------------------------------- def test_deployed_qwen37_plus_keeps_configured_1h(self):- assert effective_cache_ttl(- "1h", provider="opencode-go", model=self.DEPLOYED_MODEL- ) == "1h"def test_deployed_qwen37_plus_marker_carries_ttl_1h(self):"""M2/M6: the emitted marker must actually say ``ttl: "1h"``.@@ -746,9 +694,6 @@ class TestOpenCodeGoOneHourPrecedence:assert effective_cache_ttl("1h", provider="openrouter", model=model) == "5m", modelassert effective_cache_ttl("1h", provider="opencode-go", model=model) == "1h", model- def test_measured_no_1h_model_still_beats_route_allowance(self):- """Model-level denial wins inside the allowed route."""- assert effective_cache_ttl("1h", provider="opencode-go", model="minimax-m2.5") == "5m"def test_no_1h_denial_does_not_leak_off_the_measured_route(self):"""The denial is scoped to the route it was measured on.@@ -765,37 +710,9 @@ class TestOpenCodeGoOneHourPrecedence:for provider in ("minimax", "minimax-cn", "anthropic", "openrouter"):assert effective_cache_ttl("1h", provider=provider, model="MiniMax-M2.5") == "1h", provider- def test_route_allowance_is_not_restricted_to_the_measured_models(self):- """Records a real consequence of a route-keyed rule.-- Before this change ``opencode-go`` + a Claude model clamped to ``5m``- via the family branch; it now keeps ``1h`` like everything else on the- route. That is deliberate — the allowance is keyed on the route, not- on the two models the delayed-read run happened to cover — but it is a- behaviour change outside the measurement set, so it is pinned here- rather than left as an uncovered side effect. opencode-go serves- Claude over ``anthropic_messages``, so this route is reachable.- """- assert effective_cache_ttl("1h", provider="opencode-go", model="claude-sonnet-5") == "1h"- assert effective_cache_ttl("1h", provider="OPENCODE-GO", model="claude-x") == "1h"# -- negative controls ---------------------------------------------------- def test_generic_qwen_clamp_negative_control(self):- """§9: 1h must NOT become global. Off-route Qwen stays at 5m."""- for provider in ("openrouter", "anthropic", "together", ""):- assert effective_cache_ttl("1h", provider=provider, model="qwen3.7-plus") == "5m", provider- assert _build_marker(- effective_cache_ttl("1h", provider="openrouter", model="qwen3.7-plus")- ) == {"type": "ephemeral"}-- def test_1h_not_granted_to_the_rest_of_the_alibaba_family(self):- """M3: the allowance is one measured route, not the whole family."""- from agent.prompt_caching import ALIBABA_FAMILY_PROVIDERS, MEASURED_1H_PROVIDERS-- assert MEASURED_1H_PROVIDERS == frozenset({"opencode-go"})- for provider in sorted(ALIBABA_FAMILY_PROVIDERS - MEASURED_1H_PROVIDERS):- assert effective_cache_ttl("1h", provider=provider, model="qwen3.7-plus") == "5m", providerdef test_allowance_is_provider_wide_not_pinned_to_one_model(self):"""M5: repairing only the deployed model would leave siblings clamped."""@@ -807,9 +724,6 @@ class TestOpenCodeGoOneHourPrecedence:for spelling in ("opencode-go", "OpenCode-Go", "OPENCODE-GO"):assert effective_cache_ttl("1h", provider=spelling, model=self.DEPLOYED_MODEL) == "1h", spelling- def test_lower_tiers_are_untouched_by_the_allowance(self):- assert effective_cache_ttl("5m", provider="opencode-go", model=self.DEPLOYED_MODEL) == "5m"- assert effective_cache_ttl(None, provider="opencode-go", model=self.DEPLOYED_MODEL) == "5m"# -- call-site coverage --------------------------------------------------diff --git a/tests/agent/test_provider_attribution_headers.py b/tests/agent/test_provider_attribution_headers.pyindex becb63fab83..09831c84525 100644--- a/tests/agent/test_provider_attribution_headers.py+++ b/tests/agent/test_provider_attribution_headers.py@@ -9,25 +9,6 @@ from unittest.mock import MagicMock, patchfrom run_agent import AIAgent-@patch("agent.process_bootstrap.OpenAI")-def test_openrouter_base_url_applies_or_headers(mock_openai):- mock_openai.return_value = MagicMock()- 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,- )-- agent._apply_client_headers_for_base_url("https://openrouter.ai/api/v1")-- headers = agent._client_kwargs["default_headers"]- assert headers["HTTP-Referer"] == "https://hermes-agent.nousresearch.com"- assert headers["X-Title"] == "Hermes Agent"--@patch("agent.process_bootstrap.OpenAI")def test_ai_gateway_base_url_applies_attribution_headers(mock_openai):mock_openai.return_value = MagicMock()@@ -48,24 +29,6 @@ def test_ai_gateway_base_url_applies_attribution_headers(mock_openai):assert headers["User-Agent"].startswith("HermesAgent/")-@patch("agent.process_bootstrap.OpenAI")-def test_routermint_base_url_applies_user_agent_header(mock_openai):- mock_openai.return_value = MagicMock()- agent = AIAgent(- api_key="test-key",- base_url="https://api.routermint.com/v1",- model="test/model",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )-- agent._apply_client_headers_for_base_url("https://api.routermint.com/v1")-- headers = agent._client_kwargs["default_headers"]- assert headers["User-Agent"].startswith("HermesAgent/")--@patch("agent.process_bootstrap.OpenAI")def test_nvidia_cloud_base_url_applies_billing_origin_header(mock_openai):mock_openai.return_value = MagicMock()@@ -87,30 +50,6 @@ def test_nvidia_cloud_base_url_applies_billing_origin_header(mock_openai):assert headers["X-BILLING-INVOKE-ORIGIN"] == "HermesAgent"-@patch("agent.process_bootstrap.OpenAI")-def test_fireworks_applies_attribution_via_profile_fallback(mock_openai):- """Fireworks has no host-specific branch — its attribution headers come- from the profile.default_headers fallback, the path a model switch- re-runs."""- mock_openai.return_value = MagicMock()- agent = AIAgent(- api_key="test-key",- base_url="https://api.fireworks.ai/inference/v1",- model="accounts/fireworks/models/kimi-k2p6",- provider="fireworks",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )-- agent._apply_client_headers_for_base_url("https://api.fireworks.ai/inference/v1")-- headers = agent._client_kwargs["default_headers"]- assert headers["HTTP-Referer"] == "https://hermes-agent.nousresearch.com"- assert headers["X-Title"] == "Hermes Agent"- assert headers["User-Agent"].startswith("HermesAgent/")--@patch("agent.process_bootstrap.OpenAI")def test_opencode_go_applies_attribution_via_profile_fallback(mock_openai):"""OpenCode (Zen/Go) attributes traffic by header like OpenRouter does.@@ -135,27 +74,6 @@ def test_opencode_go_applies_attribution_via_profile_fallback(mock_openai):assert headers["User-Agent"].startswith("HermesAgent/")-@patch("agent.process_bootstrap.OpenAI")-def test_opencode_zen_applies_attribution_via_profile_fallback(mock_openai):- mock_openai.return_value = MagicMock()- agent = AIAgent(- api_key="test-key",- base_url="https://opencode.ai/zen/v1",- model="claude-sonnet-4-5",- provider="opencode-zen",- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )-- agent._apply_client_headers_for_base_url("https://opencode.ai/zen/v1")-- headers = agent._client_kwargs["default_headers"]- assert headers["HTTP-Referer"] == "https://hermes-agent.nousresearch.com"- assert headers["X-Title"] == "Hermes Agent"- assert headers["User-Agent"].startswith("HermesAgent/")--@patch("agent.process_bootstrap.OpenAI")def test_routed_client_preserves_openai_sdk_custom_headers(mock_openai):mock_openai.return_value = MagicMock()@@ -181,16 +99,6 @@ def test_routed_client_preserves_openai_sdk_custom_headers(mock_openai):assert headers["X-BILLING-INVOKE-ORIGIN"] == "HermesAgent"----------@patch("agent.process_bootstrap.OpenAI")def test_openrouter_headers_include_response_cache_when_enabled(mock_openai):"""When openrouter.response_cache is True, the cache header is injected."""@@ -249,12 +157,6 @@ def test_user_default_headers_override_sdk_user_agent(mock_openai):assert headers["X-Extra"] == "1"------@patch("agent.process_bootstrap.OpenAI")def test_openrouter_headers_no_cache_when_disabled(mock_openai):"""When openrouter.response_cache is False, no cache headers are sent."""@@ -279,5 +181,3 @@ def test_openrouter_headers_no_cache_when_disabled(mock_openai):assert headers["HTTP-Referer"] == "https://hermes-agent.nousresearch.com"assert "X-OpenRouter-Cache" not in headersassert "X-OpenRouter-Cache-TTL" not in headers--diff --git a/tests/agent/test_provider_fallback.py b/tests/agent/test_provider_fallback.pyindex bec324eeaa5..88ee9336302 100644--- a/tests/agent/test_provider_fallback.py+++ b/tests/agent/test_provider_fallback.py@@ -7,11 +7,9 @@ advancement through multiple providers.from unittest.mock import MagicMock, patch-import pytest-from agent import chat_completion_helpersfrom agent.error_classifier import FailoverReason-from run_agent import AIAgent, _pool_may_recover_from_rate_limit+from run_agent import AIAgentdef _make_agent(fallback_model=None):@@ -44,11 +42,6 @@ def _mock_client(base_url="https://openrouter.ai/api/v1", api_key="fb-key"):class TestFallbackChainInit:- def test_no_fallback(self):- agent = _make_agent(fallback_model=None)- assert agent._fallback_chain == []- assert agent._fallback_index == 0- assert agent._fallback_model is None@@ -72,26 +65,8 @@ class TestFallbackChainInit:# ── Chain advancement ─────────────────────────────────────────────────────- ("reason", "expected"),- [- (FailoverReason.auth, "authentication failed"),- (FailoverReason.billing, "billing or quota exhausted"),- (FailoverReason.rate_limit, "rate limit"),- (FailoverReason.upstream_rate_limit, "upstream model rate limit"),- (FailoverReason.overloaded, "provider overloaded"),- (FailoverReason.server_error, "provider server error"),- (FailoverReason.timeout, "request timeout"),- (FailoverReason.model_not_found, "model not found"),- (FailoverReason.unknown, "provider failure"),- ],-)-def test_fallback_reason_text_is_operator_friendly(reason, expected):- assert chat_completion_helpers._fallback_reason_text(reason) == expected-def test_fallback_reason_text_defaults_when_reason_is_missing():- assert chat_completion_helpers._fallback_reason_text(None) == "provider failure"class TestFallbackChainAdvancement:@@ -112,26 +87,6 @@ class TestFallbackChainAdvancement:assert agent.model == "gpt-4o"assert agent._fallback_activated is True- @patch("time.monotonic", return_value=1000.0)- def test_records_user_visible_switch_with_reason(self, _clock):- agent = _make_agent(- fallback_model={"provider": "zai", "model": "glm-5.2"},- )- agent.model = "gpt-5.6-sol"- agent.provider = "openai-codex"- with patch(- "agent.auxiliary_client.resolve_provider_client",- return_value=(_mock_client(base_url="https://api.z.ai/v1"), "glm-5.2"),- ):- assert agent._try_activate_fallback(FailoverReason.rate_limit) is True-- expected = (- "⚠️ Model fallback: gpt-5.6-sol via openai-codex unavailable "- "(rate limit); using glm-5.2 via zai. "- "Primary retry eligible in ~60 s; recovery is not guaranteed."- )- assert agent._pending_fallback_notice == [expected]- assert agent._retry_status_buffer[-1] == ("status", expected)@patch("time.monotonic", return_value=1000.0)def test_records_sequential_switches_in_order(self, _clock):@@ -154,13 +109,13 @@ class TestFallbackChainAdvancement:assert agent._try_activate_fallback(FailoverReason.rate_limit) is Trueassert agent._try_activate_fallback(FailoverReason.overloaded) is True- assert agent._pending_fallback_notice == [- "⚠️ Model fallback: gpt-5.6-sol via openai-codex unavailable "- "(rate limit); using glm-5.2 via zai. "- "Primary retry eligible in ~60 s; recovery is not guaranteed.",- "⚠️ Model fallback: glm-5.2 via zai unavailable "- "(provider overloaded); using deepseek-v4-flash via deepseek.",- ]+ # One user-visible notice per switch, in order, each naming from/to.+ notices = agent._pending_fallback_notice+ assert len(notices) == 2+ assert "gpt-5.6-sol" in notices[0] and "glm-5.2" in notices[0]+ assert "glm-5.2" in notices[1] and "deepseek-v4-flash" in notices[1]+ assert agent._retry_status_buffer[-1] == ("status", notices[1])+def test_skips_unconfigured_provider_to_next(self):"""If resolve_provider_client returns None, skip to next in chain."""fbs = [@@ -320,9 +275,6 @@ def _pool(n_entries: int, has_available: bool = True):return pool-class TestPoolRotationRoom:- def test_none_pool_returns_false(self):- assert _pool_may_recover_from_rate_limit(None) is Falsediff --git a/tests/agent/test_provider_parity.py b/tests/agent/test_provider_parity.pyindex 5d89af1500d..adedf7c2573 100644--- a/tests/agent/test_provider_parity.py+++ b/tests/agent/test_provider_parity.py@@ -83,22 +83,12 @@ def _make_agent(monkeypatch, provider, api_mode="chat_completions", base_url="htkwargs["model"] = modelelif provider == "nous":kwargs["model"] = "gpt-5"- base_url="https://openrouter.ai/api/v1",- api_key="test-key",- base_url="https://openrouter.ai/api/v1",return AIAgent(**kwargs)# ── _build_api_kwargs tests ─────────────────────────────────────────────────class TestBuildApiKwargsOpenRouter:- def test_uses_chat_completions_format(self, monkeypatch):- agent = _make_agent(monkeypatch, "openrouter")- messages = [{"role": "user", "content": "hi"}]- kwargs = agent._build_api_kwargs(messages)- assert "messages" in kwargs- assert "model" in kwargs- assert kwargs["messages"][-1]["content"] == "hi"def test_includes_reasoning_in_extra_body(self, monkeypatch):agent = _make_agent(monkeypatch, "openrouter")@@ -280,43 +270,8 @@ class TestBuildApiKwargsOpenRouter:assert "extra_body" not in kwargs["extra_body"]- def test_should_sanitize_tool_calls_codex_vs_chat(self, monkeypatch):- """Codex API should NOT sanitize, all other APIs should sanitize."""- # Codex mode should NOT need sanitization- codex_agent = _make_agent(monkeypatch, "openrouter")- codex_agent.api_mode = "codex_responses"- assert codex_agent._should_sanitize_tool_calls() is False- # Chat completions mode should need sanitization- chat_agent = _make_agent(monkeypatch, "openrouter")- chat_agent.api_mode = "chat_completions"- assert chat_agent._should_sanitize_tool_calls() is True- # Anthropic mode should need sanitization- anthropic_agent = _make_agent(monkeypatch, "openrouter")- anthropic_agent.api_mode = "anthropic_messages"- assert anthropic_agent._should_sanitize_tool_calls() is True-- def _api_msg_with_extra_content(self):- return {- "role": "assistant",- "content": None,- "tool_calls": [- {"id": "call_1", "call_id": "call_1", "type": "function",- "extra_content": {"google": {"thought_signature": "SIG_123"}},- "function": {"name": "t", "arguments": "{}"}},- ],- }-- def test_sanitize_tool_calls_strips_extra_content_for_strict_model(self, monkeypatch):- """Strict providers reject extra_content; strip it for non-Gemini models."""- agent = _make_agent(monkeypatch, "openrouter")- api_msg = self._api_msg_with_extra_content()- result = agent._sanitize_tool_calls_for_strict_api(- api_msg, model="accounts/fireworks/models/llama-v3p1-70b"- )- assert "extra_content" not in result["tool_calls"][0]- assert "call_id" not in result["tool_calls"][0]@@ -326,12 +281,7 @@ class TestDeveloperRoleSwap:@pytest.mark.parametrize("model", ["openai/gpt-5",- "openai/gpt-5-turbo",- "openai/gpt-5.4",- "gpt-5-mini","openai/codex-mini",- "codex-mini-latest",- "openai/codex-pro",])def test_gpt5_codex_get_developer_role(self, monkeypatch, model):agent = _make_agent(monkeypatch, "openrouter")@@ -382,21 +332,7 @@ class TestBuildApiKwargsKimiNoTemperatureOverride:class TestBuildApiKwargsAIGateway:- def test_uses_chat_completions_format(self, monkeypatch):- agent = _make_agent(monkeypatch, "ai-gateway", base_url="https://ai-gateway.vercel.sh/v1", model="gpt-4o")- messages = [{"role": "user", "content": "hi"}]- kwargs = agent._build_api_kwargs(messages)- assert "messages" in kwargs- assert "model" in kwargs- assert kwargs["messages"][-1]["content"] == "hi"- def test_no_responses_api_fields(self, monkeypatch):- agent = _make_agent(monkeypatch, "ai-gateway", base_url="https://ai-gateway.vercel.sh/v1", model="gpt-4o")- messages = [{"role": "user", "content": "hi"}]- kwargs = agent._build_api_kwargs(messages)- assert "input" not in kwargs- assert "instructions" not in kwargs- assert "store" not in kwargsdef test_includes_reasoning_in_extra_body(self, monkeypatch):agent = _make_agent(monkeypatch, "ai-gateway", base_url="https://ai-gateway.vercel.sh/v1", model="gpt-4o")@@ -406,13 +342,6 @@ class TestBuildApiKwargsAIGateway:assert "reasoning" in extraassert extra["reasoning"]["enabled"] is True- def test_includes_tools(self, monkeypatch):- agent = _make_agent(monkeypatch, "ai-gateway", base_url="https://ai-gateway.vercel.sh/v1", model="gpt-4o")- messages = [{"role": "user", "content": "hi"}]- kwargs = agent._build_api_kwargs(messages)- assert "tools" in kwargs- tool_names = [t["function"]["name"] for t in kwargs["tools"]]- assert "web_search" in tool_namesclass TestBuildApiKwargsNousPortal:@@ -429,26 +358,9 @@ class TestBuildApiKwargsNousPortal:extra = kwargs.get("extra_body", {})assert extra.get("tags") == nous_portal_tags(session_id=agent.session_id)- def test_uses_chat_completions_format(self, monkeypatch):- agent = _make_agent(- monkeypatch,- "nous",- base_url="https://inference-api.nousresearch.com/v1",- model="gpt-5",- )- messages = [{"role": "user", "content": "hi"}]- kwargs = agent._build_api_kwargs(messages)- assert "messages" in kwargs- assert "input" not in kwargsclass TestBuildApiKwargsCustomEndpoint:- def test_uses_chat_completions_format(self, monkeypatch):- agent = _make_agent(monkeypatch, "custom", base_url="http://localhost:1234/v1")- messages = [{"role": "user", "content": "hi"}]- kwargs = agent._build_api_kwargs(messages)- assert "messages" in kwargs- assert "input" not in kwargsdef test_fireworks_tool_call_payload_strips_codex_only_fields(self, monkeypatch):@@ -540,15 +452,11 @@ class TestChatMessagesToResponsesInput:"""Verify _chat_messages_to_responses_input for Codex mode."""def test_user_message_passes_through(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "user", "content": "hello"}]items = _chat_messages_to_responses_input(messages)assert items == [{"role": "user", "content": "hello"}]def test_system_messages_filtered(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "system", "content": "be helpful"},{"role": "user", "content": "hello"},@@ -558,8 +466,6 @@ class TestChatMessagesToResponsesInput:assert items[0]["role"] == "user"def test_assistant_tool_calls_become_function_call_items(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "assistant","content": "",@@ -582,8 +488,6 @@ class TestChatMessagesToResponsesInput:def test_preflight_preserves_assistant_output_text(self, monkeypatch):"""_preflight_codex_input_items must preserve output_text for assistant."""- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")raw_input = [{"role": "user", "content": [{"type": "input_text", "text": "hi"}]},{"role": "assistant", "content": [{"type": "output_text", "text": "hello"}]},@@ -596,8 +500,6 @@ class TestChatMessagesToResponsesInput:def test_full_round_trip_with_list_content(self, monkeypatch):"""End-to-end: user + assistant with list content through both stages."""- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "user", "content": [{"type": "text", "text": "hello"}]},{"role": "assistant", "content": [{"type": "text", "text": "hi there"}]},@@ -616,10 +518,6 @@ class TestChatMessagesToResponsesInput:class TestChatContentToResponsesParts:"""Unit tests for _chat_content_to_responses_parts role parameter (#15687)."""- def test_default_role_emits_input_text(self):- """Default (user) role emits input_text."""- result = _chat_content_to_responses_parts([{"type": "text", "text": "hello"}])- assert result[0]["type"] == "input_text"@@ -642,12 +540,7 @@ class TestChatContentToResponsesParts:class TestNormalizeCodexResponse:"""Verify _normalize_codex_response extracts all fields correctly."""- def _make_codex_agent(self, monkeypatch):- return _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")-def test_text_response(self, monkeypatch):- agent = self._make_codex_agent(monkeypatch)response = SimpleNamespace(output=[SimpleNamespace(type="message", status="completed",@@ -662,7 +555,6 @@ class TestNormalizeCodexResponse:def test_encrypted_content_captured(self, monkeypatch):- agent = self._make_codex_agent(monkeypatch)response = SimpleNamespace(output=[SimpleNamespace(type="reasoning",@@ -685,7 +577,6 @@ class TestNormalizeCodexResponse:def test_message_items_captured_with_id_and_phase(self, monkeypatch):"""Exact message items (with id/phase) must be captured for cache replay."""- agent = self._make_codex_agent(monkeypatch)response = SimpleNamespace(output=[SimpleNamespace(@@ -717,8 +608,6 @@ class TestChatMessagesToResponsesInputMessageItems:"""Verify codex_message_items are replayed verbatim instead of reconstructed."""def test_replays_exact_message_items(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "assistant",@@ -744,8 +633,6 @@ class TestChatMessagesToResponsesInputMessageItems:assert msg_items[0]["content"][0]["text"] == "Hello world"def test_fallback_to_plain_when_no_message_items(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "assistant", "content": "Hello world"}]items = _chat_messages_to_responses_input(messages)assert items == [{"role": "assistant", "content": "Hello world"}]@@ -897,12 +784,6 @@ class TestProviderRouting:- def test_no_routing_when_unset(self, monkeypatch):- agent = _make_agent(monkeypatch, "openrouter")- kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}])- assert "provider" not in kwargs.get("extra_body", {}).get("provider", {}) or \- kwargs.get("extra_body", {}).get("provider") is None or \- "only" not in kwargs.get("extra_body", {}).get("provider", {})@@ -913,8 +794,6 @@ class TestCodexReasoningPreflight:"""Verify reasoning items pass through preflight normalization."""def test_reasoning_item_passes_through(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")raw_input = [{"role": "user", "content": "hello"},{"type": "reasoning", "encrypted_content": "abc123encrypted", "id": "r_001",@@ -932,8 +811,6 @@ class TestCodexReasoningPreflight:assert reasoning_items[0]["summary"] == [{"type": "summary_text", "text": "Thinking about it"}]def test_reasoning_item_without_id(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")raw_input = [{"type": "reasoning", "encrypted_content": "abc123"},]@@ -945,8 +822,6 @@ class TestCodexReasoningPreflight:def test_reasoning_items_replayed_from_history(self, monkeypatch):"""Reasoning items stored in codex_reasoning_items get replayed."""- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")messages = [{"role": "user", "content": "hello"},{@@ -962,24 +837,3 @@ class TestCodexReasoningPreflight:reasoning_items = [i for i in items if isinstance(i, dict) and i.get("type") == "reasoning"]assert len(reasoning_items) == 1assert reasoning_items[0]["encrypted_content"] == "enc123"---# ── Reasoning effort consistency tests ───────────────────────────────────────--class TestReasoningEffortDefaults:- """Verify reasoning effort defaults to medium across all provider paths."""-- def test_openrouter_default_medium(self, monkeypatch):- agent = _make_agent(monkeypatch, "openrouter")- agent.model = "anthropic/claude-sonnet-4-20250514"- kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}])- reasoning = kwargs["extra_body"]["reasoning"]- assert reasoning["effort"] == "medium"-- def test_codex_default_medium(self, monkeypatch):- agent = _make_agent(monkeypatch, "openai-codex", api_mode="codex_responses",- base_url="https://chatgpt.com/backend-api/codex")- kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}])- assert kwargs["reasoning"]["effort"] == "medium"--diff --git a/tests/agent/test_provider_reset_cooldown.py b/tests/agent/test_provider_reset_cooldown.pyindex c46bf46ce0d..275fd43e216 100644--- a/tests/agent/test_provider_reset_cooldown.py+++ b/tests/agent/test_provider_reset_cooldown.py@@ -1,12 +1,11 @@"""Provider-declared reset windows govern primary fallback cooldowns (#117484)."""from types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport pytestfrom agent.error_classifier import FailoverReason-from agent.turn_recovery import route_classified_errorfrom run_agent import AIAgent@@ -73,52 +72,3 @@ def test_min_switch_reset_seconds_keeps_primary_when_reset_is_imminent(thresholdassert (getattr(agent, "_rate_limited_until", None) is not None) is switched-def test_eager_rate_limit_fallback_forwards_extracted_reset_time():- reset_at = 1_900_000_000- agent = MagicMock()- agent.compression_enabled = True- agent.provider = "openrouter"- agent._fallback_index = 0- agent._fallback_chain = [{"provider": "anthropic", "model": "claude"}]- agent._credential_pool = None- agent._try_activate_fallback.return_value = True- classified = SimpleNamespace(reason=FailoverReason.rate_limit)- retry = SimpleNamespace()- api_error = SimpleNamespace(status_code=429)-- with (- patch(- "agent.conversation_loop._ra",- return_value=SimpleNamespace(- _pool_may_recover_from_rate_limit=lambda _pool: False,- ),- ),- patch("agent.conversation_loop._arm_fallback_restart", return_value="fallback prompt"),- ):- verdict = route_classified_error(- agent,- api_error,- classified,- retry,- error_msg="rate limited",- error_context={"reset_at": reset_at},- recovered_with_pool=False,- base_url="https://openrouter.ai/api/v1",- model="primary",- messages=[],- api_messages=[],- system_message="system",- active_system_prompt="system",- conversation_history=[],- retry_count=1,- max_retries=3,- compression_attempts=0,- max_compression_attempts=2,- api_call_count=1,- effective_task_id=None,- )-- assert verdict.action == "break"- agent._try_activate_fallback.assert_called_once_with(- reason=FailoverReason.rate_limit, reset_at=reset_at,- )diff --git a/tests/agent/test_pydantic_dump_warning_leak.py b/tests/agent/test_pydantic_dump_warning_leak.pyindex d17794bedc6..2514607d404 100644--- a/tests/agent/test_pydantic_dump_warning_leak.py+++ b/tests/agent/test_pydantic_dump_warning_leak.py@@ -62,20 +62,6 @@ def _pydantic_warnings(recorded):return [w for w in recorded if "Pydantic serializer warnings" in str(w.message)]-def test_stop_event_dump_actually_warns_without_suppression():- """Precondition: the fixture really trips the SDK/pydantic warning.-- If a future SDK/pydantic release stops warning here, the other tests- pass vacuously — this test tells us the guard can be simplified.- """- stop_event, _ = _accumulated_stop_event()- with warnings.catch_warnings(record=True) as recorded:- warnings.simplefilter("always")- stop_event.model_dump()- assert _pydantic_warnings(recorded), (- "fixture no longer reproduces the pydantic serializer warning; "- "the warnings=False guards may be removable"- )def test_relay_llm_jsonable_no_warning_leak():diff --git a/tests/agent/test_rate_limit_reset_hint.py b/tests/agent/test_rate_limit_reset_hint.pyindex 754297ded20..94253a7b7e5 100644--- a/tests/agent/test_rate_limit_reset_hint.py+++ b/tests/agent/test_rate_limit_reset_hint.py@@ -46,7 +46,7 @@ def test_rate_limit_retry_status_names_the_reset_window():)text = agent._buffer_status.call_args.args[0]- assert text.startswith("⏱️ Rate limited. Resets in ~13m. Waiting ")+ assert "~13m" in textdef test_live_wait_line_names_the_reset_window_too():@@ -66,9 +66,9 @@ def test_live_wait_line_names_the_reset_window_too():return agent._emit_wait_notice.call_args.args[0]live = run(_codex_429(resets_in_seconds=756))- assert live.startswith("⏳ rate limited — resets in ~13m, retrying in ") and "(attempt 1/3)" in live- # No reset known → the existing anonymous-wait wording is unchanged.- assert run(Exception("HTTP 429")).startswith("⏳ waiting on provider — retrying in ")+ assert "~13m" in live+ # No reset known → no reset window is claimed.+ assert "resets in" not in run(Exception("HTTP 429")).lower()@pytest.mark.parametrize("headers, expected_seconds", [diff --git a/tests/agent/test_rate_limit_tracker.py b/tests/agent/test_rate_limit_tracker.pyindex 6743a9a1f3a..d72616ddb88 100644--- a/tests/agent/test_rate_limit_tracker.py+++ b/tests/agent/test_rate_limit_tracker.py@@ -4,13 +4,7 @@ import timeimport pytestfrom agent.rate_limit_tracker import (RateLimitBucket,- RateLimitState,parse_rate_limit_headers,- format_rate_limit_display,- format_rate_limit_compact,- _fmt_count,- _fmt_seconds,- _bar,)@@ -76,56 +70,6 @@ class TestBucket:-class TestFormatting:- def test_fmt_seconds_short(self):- assert _fmt_seconds(45) == "45s"- assert _fmt_seconds(0) == "0s"---- def test_bar(self):- bar = _bar(50.0, width=10)- assert bar == "[█████░░░░░]"- assert _bar(0.0, width=10) == "[░░░░░░░░░░]"- assert _bar(100.0, width=10) == "[██████████]"----- def test_format_compact(self):- state = parse_rate_limit_headers(NOUS_HEADERS, provider="nous")- result = format_rate_limit_compact(state)- assert "RPM:" in result- assert "RPH:" in result- assert "TPM:" in result- assert "TPH:" in result- assert "resets" in result----class TestAgentIntegration:- """Test that AIAgent captures rate limit state correctly."""-- def test_capture_rate_limits_from_headers(self):- """Simulate the header capture path without a real API call."""- # Use a mock httpx-like response- class MockResponse:- headers = NOUS_HEADERS-- # Import AIAgent minimally-- # Test the parsing directly- state = parse_rate_limit_headers(MockResponse.headers, provider="nous")- assert state is not None- assert state.requests_min.limit == 800- assert state.tokens_hour.limit == 336000000-- def test_capture_rate_limits_none_response(self):- """_capture_rate_limits should handle None gracefully."""- from agent.rate_limit_tracker import parse_rate_limit_headers- # None should not crash- result = parse_rate_limit_headers({})- assert result is Nonediff --git a/tests/agent/test_reactions.py b/tests/agent/test_reactions.pyindex 3b29b1facf5..3e08321c648 100644--- a/tests/agent/test_reactions.py+++ b/tests/agent/test_reactions.py@@ -8,25 +8,12 @@ from agent.reactions import VIBE, detect_reaction@pytest.mark.parametrize("text",[- "good bot","Good Bot!","ily",- "ilysm",- "i love you",- "love you",- "love u",- "luv ya",- "thanks","thank you",- "thx","ty",- "tysm","you're the best <3",- "here you go <33","❤️",- "🥰 amazing",- "sending 💖",- "great job, thank you so much!",],)def test_affection_fires_vibe(text):diff --git a/tests/agent/test_reasoning_effort_labels.py b/tests/agent/test_reasoning_effort_labels.pyindex 913e0ef439e..6136d91dbb8 100644--- a/tests/agent/test_reasoning_effort_labels.py+++ b/tests/agent/test_reasoning_effort_labels.py@@ -3,10 +3,6 @@ effort pickers and ``/reasoning`` status must say what the route really sends.""from agent.reasoning_effort import effort_display_label-def test_clamped_level_label_names_the_wire_level():- assert effort_display_label("ultra", "openai-codex", "gpt-5.6-sol") == "ultra (sends max on this route)"- assert effort_display_label("ultra", "openai-codex", "gpt-5.5") == "ultra (sends xhigh on this route)"- assert effort_display_label("ultra", "openrouter", "anthropic/claude-opus-4.5") == "ultra (sends max on this route)"def test_supported_level_label_is_the_level_itself():diff --git a/tests/agent/test_reasoning_effort_wire_translation.py b/tests/agent/test_reasoning_effort_wire_translation.pyindex d126b57412e..33b1a2ba611 100644--- a/tests/agent/test_reasoning_effort_wire_translation.py+++ b/tests/agent/test_reasoning_effort_wire_translation.py@@ -36,13 +36,6 @@ class TestUltraEffortWireTranslation:)assert out == {"enabled": True, "effort": "max"}, model- def test_gpt_56_ultra_still_maps(self):- """The original pre-existing mapping (gpt-5.6 + ultra → max) is- preserved by the generalized one."""- out = _reasoning_config_for_model(- "gpt-5.6", {"enabled": True, "effort": "ultra"}- )- assert out == {"enabled": True, "effort": "max"}def test_wire_native_levels_pass_through_untouched(self):for level in ("none", "minimal", "low", "medium", "high", "xhigh", "max"):diff --git a/tests/agent/test_reasoning_only_stop_persistence.py b/tests/agent/test_reasoning_only_stop_persistence.pyindex 20e619b588f..063fcab0f60 100644--- a/tests/agent/test_reasoning_only_stop_persistence.py+++ b/tests/agent/test_reasoning_only_stop_persistence.py@@ -10,7 +10,6 @@ sidecar, so the next request still replays the answer byte-identically.from __future__ import annotations-import loggingfrom unittest.mock import MagicMock, patchimport pytest@@ -107,20 +106,6 @@ def test_stall_guard_interim_row_carries_promoted_text_as_sidecar(loop_agent):assert "api_content" not in interim_wire-def test_reasoning_only_clean_stop_logs_warning_with_route(loop_agent, caplog):- from tests.agent.test_run_agent import _mock_response-- with caplog.at_level(logging.WARNING, logger="agent.conversation_loop"):- _run(loop_agent, [_mock_response(content=None, finish_reason="stop", reasoning_content=REASONING)])-- hits = [r for r in caplog.records if r.getMessage().startswith("Reasoning-only clean stop")]- assert len(hits) == 1- assert hits[0].levelno == logging.WARNING- assert f"model={loop_agent.model}" in hits[0].getMessage()- assert "provider=deepseek" in hits[0].getMessage()- assert "tool_turns=0" in hits[0].getMessage()--# ── planning-monologue stall: promoted reasoning must not fake a completion ──────────────────PLAN_TAILS = [diff --git a/tests/agent/test_reasoning_stale_timeout_floor.py b/tests/agent/test_reasoning_stale_timeout_floor.pyindex 8abfbaea932..1496d6cd111 100644--- a/tests/agent/test_reasoning_stale_timeout_floor.py+++ b/tests/agent/test_reasoning_stale_timeout_floor.py@@ -35,81 +35,11 @@ from __future__ import annotationsfrom pathlib import Path-import pytest# ── pure-function resolver ────────────────────────────────────────────────[email protected]("model,expected", [- # NVIDIA Nemotron reasoning family (longest keys first).- ("nvidia/nemotron-3.5-lightning-30b-a3b", 300.0),- ("nvidia/nemotron-3-ultra-550b-a55b", 600.0),- ("nvidia/nemotron-3-super-120b-a12b", 600.0),- ("nvidia/nemotron-3-nano-30b-a3b", 300.0),- # DeepSeek R1 + DeepSeek reasoner + V4 reasoning series.- # V4 emits reasoning_content in a separate delta before final- # content (same shape as R1), so it needs the same 600s floor.- ("deepseek/deepseek-r1", 600.0),- ("deepseek/deepseek-r1-distill-llama-70b", 600.0),- ("deepseek/deepseek-reasoner", 600.0),- ("deepseek/deepseek-v4-flash", 600.0),- ("deepseek/deepseek-v4-pro", 600.0),- ("deepseek-v4-flash-free", 600.0), # catalog -free variant inherits via separator anchor- # Version-less canonical Flash id from the 2026-09 Flash refresh —- # ``deepseek-v4-flash`` still aliases onto it server-side.- ("deepseek/deepseek-flash", 600.0),- ("deepseek-flash", 600.0),- # Qwen QwQ + Qwen3 thinking variants (qwen3 family entry matches all).- ("qwen/qwq-32b-preview", 300.0),- ("qwen/qwen3-235b-a22b-thinking", 180.0),- ("qwen/qwen3-32b", 180.0),- # OpenAI o-series — each variant enumerated explicitly.- # Longest match wins (o3-mini beats o3 on shared prefix).- ("openai/o1", 600.0),- ("openai/o1-mini", 600.0),- ("openai/o1-pro", 600.0),- ("openai/o1-preview", 600.0),- ("openai/o3", 600.0),- ("openai/o3-pro", 600.0),- ("openai/o3-mini", 300.0),- ("openai/o4-mini", 300.0),- # OpenAI named reasoning lines (#103802); vendor prefixes and named/-pro/-900k variants- # inherit via the separator anchor.- ("openai/gpt-5.6-sol", 600.0),- ("gpt-5.6-terra", 600.0),- ("gpt-5.6-sol-900k", 600.0),- ("gpt-6-astra", 600.0),- ("gpt-6-astra-900k", 600.0),- # Anthropic Claude 4.x thinking variants.- ("anthropic/claude-opus-4-6", 240.0),- ("anthropic/claude-opus-4-20250514", 240.0),- ("anthropic/claude-sonnet-4.5", 180.0),- ("anthropic/claude-sonnet-4.6", 180.0),- # Anthropic Mythos-class named reasoning models — deep-reasoning tier.- ("anthropic/claude-fable-5", 600.0),- ("claude-fable-5", 600.0),- ("claude-fable", 600.0),- # xAI Grok reasoning variants — explicit, not bare `grok`.- ("x-ai/grok-4-fast-reasoning", 300.0),- ("x-ai/grok-4.20-reasoning", 300.0),- ("x-ai/grok-4.5", 300.0),- ("x-ai/grok-4.6", 300.0),- ("x-ai/grok-4-fast-non-reasoning", 180.0),- # Thinking Machines Inkling — family entry covers -small and the- # OpenRouter :free / :batch SKU suffixes (":" is a slug separator- # in the right anchor, same as "-").- ("thinkingmachines/inkling", 300.0),- ("thinkingmachines/inkling:free", 300.0),- ("thinkingmachines/inkling-small:free", 300.0),-])-def test_reasoning_stale_timeout_floor_positive_cases(model, expected):- from agent.reasoning_timeouts import get_reasoning_stale_timeout_floor- assert get_reasoning_stale_timeout_floor(model) == expected, (- f"get_reasoning_stale_timeout_floor({model!r}) should return "- f"{expected}; bare substrings and shared prefixes must not "- f"over-match community derivatives."- )@@ -117,6 +47,17 @@ def test_reasoning_stale_timeout_floor_positive_cases(model, expected):+def test_floor_matching_is_vendor_prefix_and_variant_suffix_transparent():+ """A routed/vendor-prefixed or -variant/:sku slug resolves to its family's floor,+ while a look-alike community derivative does not match at all."""+ from agent.reasoning_timeouts import get_reasoning_stale_timeout_floor as floor++ assert floor("openai/o3-mini") == floor("o3-mini") is not None+ assert floor("gpt-5.6-sol-900k") == floor("gpt-5.6-sol") is not None+ assert floor("thinkingmachines/inkling:free") == floor("thinkingmachines/inkling") is not None+ assert floor("openai/gpt-4o") is None++# ── integration: _resolved_api_call_stale_timeout_base ─────────────────────@@ -197,59 +138,6 @@ def test_gpt_5_6_floor_reaches_non_stream_and_stream_resolvers(monkeypatch, tmp_assert _cloud_stale_timeout(900.0, {"model": "gpt-5.6-sol", "input": "small"}) == 900.0-# ── stream-side mirror (the real builder lives in a worker thread) ────────---def _resolve_stream_stale_timeout(- model: str | None,- base_url: str,- est_tokens: int,- stale_base: float = 180.0,-) -> float:- """Mirror of the stale-stream resolution in agent/chat_completion_helpers.py.-- Kept in lockstep with the production code at lines 2539-2575 of- agent/chat_completion_helpers.py. When that block changes, this- mirror must change too — the failing-test signal is the divergence.- """- from agent.model_metadata import is_local_endpoint- from agent.reasoning_timeouts import get_reasoning_stale_timeout_floor-- # Provider-configured stale timeout wins (mirrors get_provider_stale_timeout).- if stale_base != 180.0:- pass # In production this is sourced from config; here we parameterize.-- if stale_base == 180.0 and base_url and is_local_endpoint(base_url):- return float("inf")-- if est_tokens > 100_000:- timeout = max(stale_base, 300.0)- elif est_tokens > 50_000:- timeout = max(stale_base, 240.0)- else:- timeout = stale_base-- # Reasoning-model floor (the new branch this PR adds).- floor = get_reasoning_stale_timeout_floor(model)- if floor is not None:- timeout = max(timeout, floor)- return timeout---def test_stream_stale_timeout_floor_for_nemotron_3_ultra():- """Small-context Nemotron 3 Ultra without explicit config -> 600s floor.-- Without the floor, this would be 180s (the default), which is shorter- than NVIDIA NIM's ~120s upstream idle kill — guaranteeing broken pipe.- """- timeout = _resolve_stream_stale_timeout(- model="nvidia/nemotron-3-ultra-550b-a55b",- base_url="https://integrate.api.nvidia.com/v1",- est_tokens=10_000,- )- assert timeout == 600.0--def test_explicit_provider_stale_timeout_wins_over_context_tier_and_reasoning_floor(monkeypatch, tmp_path):"""``providers.<id>.stale_timeout_seconds`` must be able to SHORTEN patience (#115024):a 60s explicit value on a >50k-token request for a reasoning model stays 60s, while thediff --git a/tests/agent/test_redaction_registry.py b/tests/agent/test_redaction_registry.pyindex 8203cbceeca..22339ac35e0 100644--- a/tests/agent/test_redaction_registry.py+++ b/tests/agent/test_redaction_registry.py@@ -55,26 +55,8 @@ def test_registered_pattern_masks_token():assert "nvapi-" in out and "..." in out-def test_prescreen_tuple_rebuilt_not_bypassed():- # The cheap pre-screen gate (_has_known_prefix_substring) consults- # _PREFIX_SUBSTRINGS. Registration after module load must REBUILD that- # tuple so plugin patterns flow through the same fast path as built-ins- # — never around it.- assert "nvapi-" not in redact_mod._PREFIX_SUBSTRINGS- assert not redact_mod._has_known_prefix_substring(f"x {NVAPI_KEY}")- register_redaction_patterns([NVAPI_PATTERN], source="test")- assert "nvapi-" in redact_mod._PREFIX_SUBSTRINGS- assert redact_mod._has_known_prefix_substring(f"x {NVAPI_KEY}")---def test_patterns_attributed_per_source():- # Patterns are stored keyed by registration source — the seam the- # #64229 lifecycle/ledger path needs to drop one plugin's patterns on- # unload. No public removal API exists; additive-only stands.- register_redaction_patterns([NVAPI_PATTERN], source="plugin:alpha")- register_redaction_patterns([r"zk-[A-Za-z0-9]{24,}"], source="plugin:beta")- assert redact_mod._PLUGIN_PREFIX_PATTERNS["plugin:alpha"] == [NVAPI_PATTERN]- assert redact_mod._PLUGIN_PREFIX_PATTERNS["plugin:beta"] == [r"zk-[A-Za-z0-9]{24,}"]++def test_builtins_unaffected_by_registration():diff --git a/tests/agent/test_refine_focus.py b/tests/agent/test_refine_focus.pyindex 49c7ff52dff..f05f4bc248d 100644--- a/tests/agent/test_refine_focus.py+++ b/tests/agent/test_refine_focus.py@@ -44,7 +44,6 @@ def test_focus_is_appended_to_prompt():)assert prompt.startswith(_COMBINED_REVIEW_PROMPT)assert "save the deploy workflow as a skill" in prompt- assert "explicitly requested" in promptdef test_focus_works_with_memory_only_prompt():diff --git a/tests/agent/test_refine_snapshot_isolation.py b/tests/agent/test_refine_snapshot_isolation.pyindex 29b2db960bd..dd4e7c0fdd6 100644--- a/tests/agent/test_refine_snapshot_isolation.py+++ b/tests/agent/test_refine_snapshot_isolation.py@@ -110,9 +110,8 @@ async def test_gateway_refine_snapshot_does_not_alias_live_history():event.source = object()event.get_command_args.return_value = ""- out = await runner._handle_refine_command(event)+ await runner._handle_refine_command(event)- assert out.startswith("⚗")agent._spawn_background_review_now.assert_called_once()snapshot = agent._spawn_background_review_now.call_args.kwargs["messages_snapshot"]_assert_isolated(agent._session_messages, snapshot)diff --git a/tests/agent/test_relay_llm.py b/tests/agent/test_relay_llm.pyindex 38347adacc0..3c008ecf341 100644--- a/tests/agent/test_relay_llm.py+++ b/tests/agent/test_relay_llm.py@@ -170,13 +170,6 @@ def test_stream_execution_uses_canonical_relay_operation_name(relay_turn, monkeyassert observed_names == ["anthropic.messages"]-def test_unknown_api_mode_preserves_provider_name():- assert (- relay_llm._relay_operation_name("custom-provider", {"api_mode": "future_api"})- == "custom-provider"- )--@pytest.mark.parametrize(("api_mode", "operation", "codec_class"),[@@ -197,16 +190,6 @@ def test_relay_protocol_drives_operation_and_codec(assert isinstance(relay_llm._codec(relay, metadata), codec_type)-def test_relay_metadata_preserves_provider_name():- metadata = {"api_mode": "chat_completions", "hermes.provider": "explicit"}-- assert relay_llm._relay_metadata("openrouter", metadata) == metadata- assert relay_llm._relay_metadata("openrouter", {"api_mode": "chat_completions"}) == {- "api_mode": "chat_completions",- "hermes.provider": "openrouter",- }--def test_provider_request_overlays_interceptor_added_codex_field():"""Relay rewrites may introduce provider fields absent from the original."""original = {"model": "gpt-5.6-sol", "input": "hello"}@@ -537,16 +520,6 @@ def test_live_stream_defers_runtime_shutdown_until_exhaustion(relay_runtime._reset_for_tests()----------def test_anthropic_stream_accumulator_merges_plain_provider_object():accumulator = relay_llm.AnthropicStreamAccumulator()accumulator.observe({@@ -593,10 +566,6 @@ def test_jsonable_does_not_probe_dynamic_attributes():assert relay_llm._jsonable(DynamicProviderObject()) == "opaque-provider-object"----@pytest.mark.asyncioasync def test_async_provider_callback_preserves_caller_context(relay_turn):del relay_turn@@ -625,8 +594,6 @@ async def test_async_provider_callback_preserves_caller_context(relay_turn):assert result == {"caller_value": "caller"}--def test_anthropic_stream_callbacks_do_not_reenter_captured_context(relay_turn,monkeypatch,@@ -758,8 +725,6 @@ def test_explicit_stream_close_surfaces_provider_close_failure(relay_turn):stream.close()--def test_non_stream_defers_logical_success_and_reuses_scope_for_retry(relay_turn):_relay, turn = relay_turnmetadata = {"api_mode": "custom", "api_request_id": "request-retry"}@@ -826,20 +791,6 @@ def test_non_stream_result_survives_logical_scope_close_failure(assert turn.logical_llm_calls == {}--------------def test_stream_flushes_buffered_provider_chunks_after_relay_failure(relay_turn, monkeypatch):@@ -1008,20 +959,6 @@ def test_wedged_relay_aclose_does_not_block_provider_fallback(assert stream._runtime_lease is None--------------def test_stream_refuses_replay_after_transformed_relay_output(relay_turn, monkeypatch):@@ -1225,10 +1162,6 @@ def test_anthropic_codec_preserves_tool_history_and_cached_system_blocks(relay_tassert observed_body_wire == original_wire----@pytest.mark.asyncioasync def test_async_non_stream_returns_namespaced_interceptor_result(relay_turn,@@ -1297,17 +1230,7 @@ def test_non_stream_preserves_provider_error_from_relay_wrapper_suffix(assert "request-error" in turn.logical_llm_calls-----------def test_codec_baseline_failure_is_explicit(relay_turn, monkeypatch, caplog):+def test_codec_baseline_failure_is_explicit(relay_turn, monkeypatch):relay, _turn = relay_turnrequest_body = {"model": "test-model", "messages": []}request = relay.LLMRequest({}, request_body)@@ -1318,16 +1241,14 @@ def test_codec_baseline_failure_is_explicit(relay_turn, monkeypatch, caplog):monkeypatch.setattr(relay_llm, "_codec", lambda *_args, **_kwargs: FailingCodec())- with caplog.at_level("WARNING", logger="agent.relay_llm"):- baseline = relay_llm._codec_round_trip_request_body(- relay,- request,- relay_request_body=request_body,- metadata={"api_mode": "chat_completions"},- )+ baseline = relay_llm._codec_round_trip_request_body(+ relay,+ request,+ relay_request_body=request_body,+ metadata={"api_mode": "chat_completions"},+ )assert baseline is None- assert "ignoring request rewrites" in caplog.textdef test_stream_current_unwraps_completed_response(tmp_path, monkeypatch):diff --git a/tests/agent/test_relay_runtime_bounded_scope_ops.py b/tests/agent/test_relay_runtime_bounded_scope_ops.pyindex e1374bd3738..a13ad0d9653 100644--- a/tests/agent/test_relay_runtime_bounded_scope_ops.py+++ b/tests/agent/test_relay_runtime_bounded_scope_ops.py@@ -23,8 +23,6 @@ helper's internal shape.from __future__ import annotationsimport threading-import time-import typesfrom typing import Anyimport pytest@@ -279,13 +277,3 @@ class TestHealthyPathUnchanged:# the final flush after tracked operations drain.assert fake.subscribers.flushed == 0- def test_healthy_pop_result_propagates_synchronously(self, coordinator):- """A healthy pop completes and is observed before end_turn returns."""- runtime = _make_runtime(_FakeRelay())- lease = _acquire(coordinator, runtime)- turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task1")- coordinator.end_turn(turn, outcome="success")- assert relay_runtime.TURN_SCOPE in runtime.relay.scope.popped, (- "healthy-path pop must complete before end_turn returns "- "(no fire-and-forget on the default lane)"- )diff --git a/tests/agent/test_relay_runtime_plugins.py b/tests/agent/test_relay_runtime_plugins.pyindex 214d80d24d9..bbe199e41ab 100644--- a/tests/agent/test_relay_runtime_plugins.py+++ b/tests/agent/test_relay_runtime_plugins.py@@ -264,8 +264,7 @@ def test_foreign_active_plugin_configuration_is_left_unchanged()assert relay.active_report is foreign_reportassert relay.events == []- assert "already active outside Hermes native ownership" in caplog.text- assert "leaving it unchanged" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)finally:host.shutdown()@@ -286,7 +285,7 @@ def test_unreadable_foreign_plugin_state_fails_safe(is relay_runtime._RelayPluginConfigurationState.FAILED)assert relay.events == []- assert "refusing to replace it" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)finally:host.shutdown()@@ -310,7 +309,6 @@ def test_legacy_exporter_env_without_plugins_toml_warns_and_stays_disabled(is relay_runtime._RelayPluginConfigurationState.DISABLED)assert relay.events == []- assert "no HERMES_NEMO_RELAY_PLUGINS_TOML was provided" in caplog.textassert "HERMES_NEMO_RELAY_ATOF_ENABLED" in caplog.textassert "HERMES_NEMO_RELAY_ATIF_EXPORT_TIMEOUT_S" in caplog.textfinally:@@ -329,7 +327,7 @@ def test_initialization_failure_is_fail_open(explicit_static_config, caplog):host._plugin_configuration_stateis relay_runtime._RelayPluginConfigurationState.FAILED)- assert "Hermes Relay plugin initialization failed" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)finally:host.shutdown()@@ -393,7 +391,7 @@ def test_missing_explicit_config_is_failed_for_all_current_hosts(is relay_runtime._RelayPluginConfigurationState.FAILED)assert relay.events == []- assert "continuing without Relay plugins" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)finally:first_host.shutdown()later_host.shutdown()@@ -418,7 +416,7 @@ def test_malformed_explicit_config_does_not_fall_back_to_discovery(is relay_runtime._RelayPluginConfigurationState.FAILED)assert relay.events == []- assert "continuing without Relay plugins" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)finally:host.shutdown()@@ -448,7 +446,6 @@ def test_present_plugins_section_is_validated_even_when_falsey()assert relay.events == []assert "'plugins' must be a table" in caplog.text- assert "continuing without Relay plugins" in caplog.textfinally:host.shutdown()@@ -669,7 +666,7 @@ manifest = "relay-plugin.toml""plugin.load_dynamic_specs","plugin.initialize_dynamic",]- assert "dynamic plugin activation failed" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)assert "Relay plugins are active process-wide" not in caplog.textfinally:host.shutdown()@@ -855,7 +852,7 @@ manifest = "relay-plugin.toml"with caplog.at_level("WARNING"):host.shutdown()- assert "plugin configuration cleanup failed" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)activation = relay_runtime._PLUGIN_CONFIGURATION._activationassert activation is not None@@ -871,7 +868,7 @@ manifest = "relay-plugin.toml"("plugin.initialize_dynamic", {}, relay.dynamic_plugin_specs)) == 1assert relay.events.count(("plugin.activation.close",)) == 2- assert "refusing to replace" in caplog.text+ assert any(r.levelname == "WARNING" for r in caplog.records)finally:replacement.shutdown()# Relay treats a close failure as terminal; only reset the permissive@@ -945,7 +942,6 @@ manifest_ref = "relay-plugin.toml"assert relay.events == []assert "Hermes [[dynamic_plugins]] records are unsupported" in caplog.textassert "use Relay [[plugins.dynamic]] records" in caplog.text- assert "continuing without Relay plugins" in caplog.textfinally:host.shutdown()diff --git a/tests/agent/test_replay_budget_accounting.py b/tests/agent/test_replay_budget_accounting.pyindex 01694234913..49f48be5470 100644--- a/tests/agent/test_replay_budget_accounting.py+++ b/tests/agent/test_replay_budget_accounting.py@@ -19,7 +19,6 @@ from agent.context_compressor import (_NEWEST_TURN_ONLY_BUDGET_KEYS,_REPLAY_BUDGET_KEYS,_estimate_msg_budget_tokens,- _last_assistant_index,)from agent.model_metadata import estimate_tokens_roughfrom agent.turn_context import substitute_api_content@@ -127,22 +126,6 @@ class TestKeyPartition:assert "codex_message_items" in _ALWAYS_REPLAYED_BUDGET_KEYS-class TestLastAssistantIndex:- def test_finds_newest_assistant(self):- msgs = [- {"role": "user", "content": "u"},- {"role": "assistant", "content": "a1"},- {"role": "user", "content": "u2"},- {"role": "assistant", "content": "a2"},- {"role": "tool", "content": "t"},- ]- assert _last_assistant_index(msgs) == 3-- def test_no_assistant_returns_minus_one(self):- assert _last_assistant_index([{"role": "user", "content": "u"}]) == -1- assert _last_assistant_index([]) == -1--class TestTailCutBehavior:"""The tail cut must protect MORE real transcript when stale turns carryheavy thinking — the #73624 symptom was the cut landing early."""diff --git a/tests/agent/test_replay_cleanup.py b/tests/agent/test_replay_cleanup.pyindex f97acaff9eb..adb0a640b80 100644--- a/tests/agent/test_replay_cleanup.py+++ b/tests/agent/test_replay_cleanup.py@@ -7,9 +7,7 @@ because the dangling tool-call tail was replayed on every resume)."""from agent.replay_cleanup import (- is_interrupted_tool_result,strip_dangling_tool_call_tail,- strip_interrupted_tool_tails,sanitize_replay_history,)@@ -91,8 +89,6 @@ def test_sanitize_replay_history_noop_on_clean_history():assert sanitize_replay_history(history) == history-def test_sanitize_replay_history_empty():- assert sanitize_replay_history([]) == []# --- Send/replay canonicalization parity (#105236 §6, salvage of #105308) ---