chore: prune unused imports and duplicate import redefinitions

Remove unused imports (F401) and duplicate/shadowed import
redefinitions (F811) across the codebase using ruff's safe
autofixes. No behavioral changes -- imports only.

- ~1400 safe autofixes applied across 644 files (net -1072 lines)
- __init__.py re-exports preserved (excluded from F401 removal so
  public re-export surfaces stay intact)
- Re-exports that are imported or monkeypatched by tests but look
  unused in their defining module are kept with explicit # noqa:
  F401 (gateway/run.py load_dotenv; run_agent re-exports from
  agent.message_sanitization, agent.context_compressor,
  agent.retry_utils, agent.prompt_builder, agent.process_bootstrap,
  agent.codex_responses_adapter)
- Unsafe F841 (unused-variable) fixes deliberately skipped -- those
  can change behavior when the RHS has side effects
- ruff lints remain disabled in pyproject.toml (only PLW1514 is
  selected); this is a one-time cleanup, not a config change

Verification:
- python -m compileall: clean
- pytest --collect-only: all 27161 tests collect (zero import errors)
- core entry points import clean (run_agent, model_tools, cli,
  toolsets, hermes_state, batch_runner, gateway)
- static scan: every name any test imports directly from an edited
  module still resolves
This commit is contained in:
kshitijk4poor 2026-05-29 02:04:58 +05:30 committed by Teknium
parent a4d8f0f62a
commit 66827f8947
644 changed files with 254 additions and 1326 deletions

View file

@ -8,8 +8,6 @@ syntax check exactly as if LSP were disabled.
"""
from __future__ import annotations
import os
import sys
from unittest.mock import MagicMock
import pytest

View file

@ -14,15 +14,12 @@ This module verifies:
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
from agent.lsp.manager import LSPService
from agent.lsp.servers import SERVERS, ServerContext, ServerDef, SpawnSpec
from agent.lsp.workspace import clear_cache

View file

@ -6,12 +6,8 @@ having LSP output prepended to the lint string.
"""
from __future__ import annotations
import os
import sys
import tempfile
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
from tools.environments.local import LocalEnvironment
from tools.file_operations import (

View file

@ -7,7 +7,7 @@ pyright/gopls/etc. are still alive on the host.
from __future__ import annotations
import atexit
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
import pytest

View file

@ -2,7 +2,6 @@
from __future__ import annotations
from agent.lsp.reporter import (
DEFAULT_SEVERITIES,
MAX_PER_FILE,
format_diagnostic,
report_for_file,

View file

@ -7,7 +7,6 @@ on.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
@ -19,7 +18,6 @@ from agent.lsp.servers import (
ServerContext,
ServerDef,
SpawnSpec,
find_server_for_file,
)

View file

@ -1,10 +1,8 @@
"""Tests for Bug #12905 fixes in agent/anthropic_adapter.py — macOS Keychain support."""
import json
import platform
from unittest.mock import patch, MagicMock
import pytest
from agent.anthropic_adapter import (
_read_claude_code_credentials_from_keychain,

View file

@ -8,11 +8,9 @@ name in the tool registry.
from __future__ import annotations
import json
from types import SimpleNamespace
from unittest.mock import patch
import pytest
# ---------------------------------------------------------------------------

View file

@ -15,7 +15,6 @@ History:
from __future__ import annotations
import io
import json
from typing import Any, Dict
from urllib.parse import parse_qs, urlparse

View file

@ -8,7 +8,6 @@ import warnings
from concurrent.futures import Future
from unittest.mock import patch
import pytest
from agent.async_utils import safe_schedule_threadsafe

View file

@ -2,9 +2,7 @@
import json
import logging
import os
import time
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch, MagicMock, AsyncMock
@ -609,7 +607,7 @@ class TestExpiredCodexFallback:
monkeypatch.setenv("ANTHROPIC_TOKEN", "sk-ant-oat01-test-fallback")
with patch("agent.anthropic_adapter.build_anthropic_client") as mock_build:
mock_build.return_value = MagicMock()
from agent.auxiliary_client import _resolve_auto, AnthropicAuxiliaryClient
from agent.auxiliary_client import _resolve_auto
client, model = _resolve_auto()
# Should NOT be Codex, should be Anthropic (or another available provider)
assert not isinstance(client, type(None)), "Should find a provider after expired Codex"
@ -696,7 +694,7 @@ class TestExpiredCodexFallback:
patch("agent.anthropic_adapter.build_anthropic_client") as mock_build, \
patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)):
mock_build.return_value = MagicMock()
from agent.auxiliary_client import _try_anthropic, AnthropicAuxiliaryClient
from agent.auxiliary_client import _try_anthropic
client, model = _try_anthropic()
assert client is not None, "Should resolve token"
adapter = client.chat.completions
@ -751,7 +749,7 @@ class TestExpiredCodexFallback:
monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)
with patch("agent.anthropic_adapter.build_anthropic_client") as mock_build:
mock_build.return_value = MagicMock()
from agent.auxiliary_client import _try_anthropic, AnthropicAuxiliaryClient
from agent.auxiliary_client import _try_anthropic
client, model = _try_anthropic()
assert client is not None
adapter = client.chat.completions

View file

@ -27,7 +27,6 @@ from __future__ import annotations
import sys
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest

View file

@ -4,14 +4,11 @@ are properly mapped to environment variables by both CLI and gateway loaders.
Also tests the vision_tools and browser_tool model override env vars.
"""
import json
import os
import sys
from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
import yaml
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

View file

@ -15,7 +15,6 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
# ── Text aux tasks — _resolve_auto ──────────────────────────────────────────

View file

@ -1,6 +1,5 @@
"""Tests for named custom provider and 'main' alias resolution in auxiliary_client."""
import os
from unittest.mock import patch, MagicMock
import pytest

View file

@ -23,7 +23,6 @@ import sys
from collections.abc import Callable
from types import SimpleNamespace
from typing import cast
from unittest.mock import MagicMock, patch
import pytest

View file

@ -10,11 +10,9 @@ Covers:
"""
import json
import os
import time
from contextlib import contextmanager
from types import ModuleType, SimpleNamespace
from unittest.mock import MagicMock, patch, PropertyMock
from types import ModuleType
from unittest.mock import MagicMock, patch
import pytest
@ -129,7 +127,7 @@ class TestResolveBedrocRegion:
def test_defaults_to_us_east_1(self):
from agent.bedrock_adapter import resolve_bedrock_region
from unittest.mock import patch, MagicMock
from unittest.mock import MagicMock
mock_session = MagicMock()
mock_session.get_config_variable.return_value = None
with _mock_botocore_session(return_value=mock_session):
@ -137,7 +135,7 @@ class TestResolveBedrocRegion:
def test_falls_back_to_botocore_profile_region(self):
from agent.bedrock_adapter import resolve_bedrock_region
from unittest.mock import patch, MagicMock
from unittest.mock import MagicMock
mock_session = MagicMock()
mock_session.get_config_variable.return_value = "eu-central-1"
with _mock_botocore_session(return_value=mock_session):
@ -145,7 +143,6 @@ class TestResolveBedrocRegion:
def test_botocore_failure_falls_back_to_us_east_1(self):
from agent.bedrock_adapter import resolve_bedrock_region
from unittest.mock import patch
with _mock_botocore_session(side_effect=Exception("no botocore")):
assert resolve_bedrock_region({}) == "us-east-1"

View file

@ -9,7 +9,6 @@ Note: Tests that import ``hermes_cli.auth`` or ``hermes_cli.runtime_provider``
require Python 3.10+ due to ``str | None`` type syntax in the import chain.
"""
import os
from unittest.mock import MagicMock, patch
import pytest
@ -93,7 +92,6 @@ class TestResolveProvider:
def test_explicit_bedrock_resolves(self, monkeypatch):
"""When user explicitly requests 'bedrock', it should resolve."""
from hermes_cli.auth import PROVIDER_REGISTRY
# bedrock is in the registry, so resolve_provider should return it
from hermes_cli.auth import resolve_provider
result = resolve_provider("bedrock")

View file

@ -29,7 +29,6 @@ import base64
import json
from unittest.mock import MagicMock, patch
import pytest
# ---------------------------------------------------------------------------

View file

@ -8,7 +8,6 @@ creative workflows that iterate on images across many turns.
from __future__ import annotations
import pytest
from agent.context_compressor import (
_CHARS_PER_TOKEN,

View file

@ -232,7 +232,7 @@ class TestPluginContextEngineSlot:
assert mgr._context_engine is None
def test_get_plugin_context_engine(self):
from hermes_cli.plugins import PluginManager, PluginContext, PluginManifest, get_plugin_context_engine, _plugin_manager
from hermes_cli.plugins import PluginManager, get_plugin_context_engine
import hermes_cli.plugins as plugins_mod
# Inject a test manager

View file

@ -28,7 +28,6 @@ from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from run_agent import AIAgent

View file

@ -10,9 +10,7 @@ so it can run without optional dependencies like firecrawl.
import asyncio
import threading
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import patch, MagicMock
from types import SimpleNamespace
import pytest
@ -32,7 +30,6 @@ def _stub_resolve_provider_client(provider, model, async_mode, **kw):
@pytest.fixture(autouse=True)
def _clean_client_cache():
"""Clear the client cache before each test."""
import importlib
# We need to patch before importing
with patch.dict("sys.modules", {}):
pass
@ -48,7 +45,7 @@ class TestCrossLoopCacheIsolation:
def test_same_loop_reuses_client(self):
"""Within a single event loop, the same client should be returned."""
from agent.auxiliary_client import _get_cached_client, _client_cache
from agent.auxiliary_client import _get_cached_client
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

View file

@ -7,7 +7,6 @@ tests run fully offline and the curator module doesn't need real credentials.
from __future__ import annotations
import importlib
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

View file

@ -7,8 +7,7 @@ the standard log dir, not inside the user's ``skills/`` data directory.
from __future__ import annotations
import json
import os
from datetime import datetime, timezone, timedelta
from datetime import datetime, timezone
from pathlib import Path
import pytest

View file

@ -1,9 +1,8 @@
"""Tests for agent/display.py — build_tool_preview() and inline diff previews."""
import os
import json
import pytest
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
from agent.display import (
build_tool_preview,

View file

@ -5,7 +5,6 @@ todo tool call paths: read, create (merge=False), update (merge=True).
"""
import json
import pytest
from agent.display import get_cute_tool_message

View file

@ -7,7 +7,6 @@ not a generic "[error]".
"""
import json
import pytest
from agent.display import (
_detect_tool_failure,

View file

@ -2,7 +2,6 @@
import json
import os
from pathlib import Path
from unittest.mock import patch
import pytest

View file

@ -11,7 +11,6 @@ cache invalidates when config.yaml's mtime changes.
from __future__ import annotations
import os
import time
from pathlib import Path
from unittest.mock import patch

View file

@ -4,8 +4,6 @@ Run with: python -m pytest tests/agent/test_file_safety.py -v
"""
import os
import tempfile
from pathlib import Path
from unittest.mock import patch
import pytest

View file

@ -12,7 +12,6 @@ afterwards that the second path belonged to a different profile.
"""
from __future__ import annotations
import os
from pathlib import Path
import pytest

View file

@ -18,8 +18,6 @@ import json
import stat
import time
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest

View file

@ -3,7 +3,6 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from agent.gemini_native_adapter import (
gemini_http_error,

View file

@ -6,7 +6,6 @@ import base64
from pathlib import Path
from unittest.mock import patch
import pytest
from agent.image_routing import (
_coerce_capability_bool,

View file

@ -2,7 +2,6 @@
import time
import pytest
from pathlib import Path
from hermes_state import SessionDB
from agent.insights import (
@ -11,7 +10,6 @@ from agent.insights import (
_format_duration,
_bar_chart,
_has_known_pricing,
_DEFAULT_PRICING,
)
@ -596,7 +594,6 @@ class TestEdgeCases:
def test_tool_usage_from_tool_calls_json(self, db):
"""Tool usage should be extracted from tool_calls JSON when tool_name is NULL."""
import json as _json
db.create_session(session_id="s1", source="cli", model="test")
# Assistant message with tool_calls (this is what CLI produces)
db.append_message("s1", role="assistant", content="Let me search",

View file

@ -2,7 +2,7 @@
import json
import pytest
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
from agent.memory_provider import MemoryProvider
from agent.memory_manager import MemoryManager
@ -462,7 +462,7 @@ class TestUserInstalledProviderDiscovery:
def test_discover_finds_user_plugins(self, tmp_path, monkeypatch):
"""discover_memory_providers() includes user-installed plugins."""
from plugins.memory import discover_memory_providers, _get_user_plugins_dir
from plugins.memory import discover_memory_providers
self._make_user_memory_plugin(tmp_path, "myexternal")
monkeypatch.setattr(
"plugins.memory._get_user_plugins_dir",

View file

@ -7,7 +7,6 @@ state in initialize() (Hindsight, and any plugin that stores session_id
for scoped writes) keep writing into the old session's record.
"""
import json
import pytest

View file

@ -6,7 +6,6 @@ so each gateway user gets their own memory bucket instead of sharing a static on
import json
import os
import pytest
from unittest.mock import MagicMock, patch
from agent.memory_provider import MemoryProvider

View file

@ -10,13 +10,9 @@ Coverage levels:
Persistent cache save/load, corruption, update, provider isolation
"""
import os
import time
import tempfile
import pytest
import yaml
from pathlib import Path
from unittest.mock import patch, MagicMock
from agent.model_metadata import (

View file

@ -6,12 +6,10 @@ All tests use synthetic inputs — no filesystem or live server required.
import sys
import os
import json
from unittest.mock import MagicMock, patch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import pytest
# ---------------------------------------------------------------------------
@ -562,7 +560,7 @@ class TestGetModelContextLengthLocalFallback:
def test_non_local_endpoint_does_not_query_local_server(self):
"""For non-local endpoints, _query_local_context_length is not called."""
from agent.model_metadata import get_model_context_length, CONTEXT_PROBE_TIERS
from agent.model_metadata import get_model_context_length
with patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.fetch_endpoint_model_metadata", return_value={}), \

View file

@ -1,8 +1,6 @@
"""Tests for agent.models_dev — models.dev registry integration."""
import json
from unittest.mock import patch, MagicMock
import pytest
from agent.models_dev import (
PROVIDER_TO_MODELS_DEV,
_extract_context,

View file

@ -11,10 +11,8 @@ Covers:
from __future__ import annotations
import os
from pathlib import Path
import pytest
def _write_config(tmp_path: Path, body: str) -> None:

View file

@ -3,7 +3,6 @@
from __future__ import annotations
import yaml
import pytest
from agent.onboarding import (
BUSY_INPUT_FLAG,

View file

@ -10,7 +10,6 @@ from __future__ import annotations
import asyncio
import base64
import json
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock

View file

@ -18,7 +18,6 @@ from agent.prompt_builder import (
build_skills_system_prompt,
build_nous_subscription_prompt,
build_context_files_prompt,
build_environment_hints,
CONTEXT_FILE_MAX_CHARS,
DEFAULT_AGENT_IDENTITY,
TOOL_USE_ENFORCEMENT_GUIDANCE,

View file

@ -1,7 +1,5 @@
"""Tests for agent/prompt_caching.py — Anthropic cache control injection."""
import copy
import pytest
from agent.prompt_caching import (
_apply_cache_marker,

View file

@ -189,14 +189,11 @@ class TestAgentIntegration:
def test_capture_rate_limits_from_headers(self):
"""Simulate the header capture path without a real API call."""
import sys
import os
# Use a mock httpx-like response
class MockResponse:
headers = NOUS_HEADERS
# Import AIAgent minimally
from unittest.mock import MagicMock, patch
# Test the parsing directly
state = parse_rate_limit_headers(MockResponse.headers, provider="nous")

View file

@ -1,7 +1,6 @@
"""Tests for agent.redact -- secret masking in logs and output."""
import logging
import os
import pytest

View file

@ -9,10 +9,7 @@ covered in ``test_shell_hooks_consent.py``.
from __future__ import annotations
import json
import os
import stat
from pathlib import Path
from typing import Any, Dict
import pytest

View file

@ -7,7 +7,6 @@ hooks_auto_accept: config key).
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch

View file

@ -2,7 +2,6 @@
import os
from pathlib import Path
from unittest.mock import patch
import pytest

View file

@ -10,10 +10,8 @@ Verifies that:
import io
import sys
import time
import threading
import pytest
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
from agent.display import KawaiiSpinner
from tools.delegate_tool import _build_child_progress_callback

View file

@ -1,6 +1,5 @@
"""Tests for progressive subdirectory hint discovery."""
import os
import pytest
from pathlib import Path
from unittest.mock import patch

View file

@ -1,9 +1,7 @@
"""Tests for agent.title_generator — auto-generated session titles."""
import threading
from unittest.mock import MagicMock, patch
import pytest
from agent.title_generator import (
generate_title,

View file

@ -1,11 +1,10 @@
"""Tests for the BedrockTransport."""
import json
import pytest
from types import SimpleNamespace
from agent.transports import get_transport
from agent.transports.types import NormalizedResponse, ToolCall
from agent.transports.types import NormalizedResponse
@pytest.fixture

View file

@ -7,7 +7,6 @@ deadline timeouts. These tests pin all of that without spawning real codex.
from __future__ import annotations
import threading
import time
from unittest.mock import patch
from typing import Any, Optional
@ -17,7 +16,6 @@ import pytest
import agent.transports.codex_app_server_session as session_mod
from agent.transports.codex_app_server_session import (
CodexAppServerSession,
TurnResult,
_ServerRequestRouting,
_approval_choice_to_codex_decision,
_coerce_turn_input_text,

View file

@ -11,7 +11,6 @@ import pytest
from agent.transports.codex_event_projector import (
CodexEventProjector,
ProjectionResult,
_deterministic_call_id,
_format_tool_args,
)

View file

@ -5,7 +5,7 @@ import pytest
from types import SimpleNamespace
from agent.transports import get_transport
from agent.transports.types import NormalizedResponse, ToolCall
from agent.transports.types import NormalizedResponse
@pytest.fixture

View file

@ -8,9 +8,7 @@ build helper assembles a server when the SDK is present.
from __future__ import annotations
from unittest.mock import patch
import pytest
class TestModuleSurface:

View file

@ -2,10 +2,9 @@
import pytest
from types import SimpleNamespace
from unittest.mock import MagicMock
from agent.transports.base import ProviderTransport
from agent.transports.types import NormalizedResponse, ToolCall, Usage
from agent.transports.types import NormalizedResponse
from agent.transports import get_transport, register_transport, _REGISTRY

View file

@ -1,7 +1,6 @@
"""Tests for agent/transports/types.py — dataclass construction + helpers."""
import json
import pytest
from agent.transports.types import (
NormalizedResponse,