Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(ci): add check-shadow-tests pre-commit hook (#4356)

LearningCircuit758250e3be37
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 2b483e237a..0643aed9f9 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -377,6 +377,18 @@ repos:
files: ^tests/.*\.py$
description: "Warn when test files redefine app/client/authenticated_client
fixtures from root conftest.py"
+ - id: check-shadow-tests
+ name: Check for shadow tests (no SUT import)
+ entry: .pre-commit-hooks/check-shadow-tests.py
+ language: script
+ files: ^tests/.*\.py$
+ # Black-box (HTTP-client) and meta (hook/guardian) test trees
+ # legitimately never import local_deep_research; scattered
+ # survivors use a '# allow: no-sut-import' marker instead.
+ exclude: ^tests/(api_tests|api_tests_with_login|ui_tests|hooks|ci|health_check|accessibility_tests|performance/api_auth)/|_hook\.py$
+ description: "Block test modules that import nothing from local_deep_research
+ (shadow tests). Opt out a legitimate no-import test with
+ '# allow: no-sut-import — <reason>'. See CONTRIBUTING.md."
- id: check-weak-tests
name: Check for tautological / no-op tests
entry: .pre-commit-hooks/check-weak-tests.py
diff --git a/.pre-commit-hooks/check-shadow-tests.py b/.pre-commit-hooks/check-shadow-tests.py
new file mode 100755
index 0000000000..5ef4556d23
--- /dev/null
+++ b/.pre-commit-hooks/check-shadow-tests.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python3
+"""Block "shadow tests": test modules that never import the SUT.
+
+A shadow test imports nothing from ``local_deep_research`` and therefore
+exercises no production code. Such files test inline reimplementations,
+pure stdlib behaviour, or locally-built dicts — inflating the test count
+and coverage metrics while catching zero real regressions. PRs #4239,
+#4242, #4243 removed ~80 such files; this hook stops them creeping back.
+
+Detection (AST-based): a file whose basename matches the test-module
+pattern (``test_*.py`` / ``*_test.py``) is flagged when none of its
+``import`` / ``from ... import`` statements reference ``local_deep_research``
+(or ``src.local_deep_research``). Imports under ``if TYPE_CHECKING:`` don't
+run, so they don't count as exercising the SUT.
+
+Opt-out: a small number of files legitimately have no SUT import — e.g.
+guardian tests that assert on repository structure or CI workflow files.
+Add a marker line to exempt one::
+
+ # allow: no-sut-import — <why this test has no local_deep_research import>
+
+The reason text is required so the exemption is self-documenting.
+"""
+
+import ast
+import os
+import re
+import sys
+
+# Marker that exempts a file, mirroring the `# allow: unmarked-sleep`
+# convention used by check-unmarked-sleep.py. A trailing reason is required.
+ALLOW_RE = re.compile(r"#\s*allow:\s*no-sut-import\b\s*[-—:]\s*\S+")
+
+SUT_ROOTS = ("local_deep_research", "src.local_deep_research")
+
+# Only emit ANSI colour when stdout is a TTY (matches recommend-release-notes.py);
+# CI log viewers and Windows consoles then get clean plain text.
+_USE_COLOR = sys.stdout.isatty()
+_RED = "\033[31m" if _USE_COLOR else ""
+_RESET = "\033[0m" if _USE_COLOR else ""
+
+
+def is_test_module(path: str) -> bool:
+ """True for pytest test modules (not conftest/__init__/helpers)."""
+ # os.path.basename handles both / and \ so the hook behaves the same
+ # if it's ever invoked outside pre-commit (which normalizes to POSIX).
+ name = os.path.basename(path)
+ if not name.endswith(".py"):
+ return False
+ return name.startswith("test_") or name.endswith("_test.py")
+
+
+def _references_sut(name: str | None) -> bool:
+ if not name:
+ return False
+ return any(
+ name == root or name.startswith(root + ".") for root in SUT_ROOTS
+ )
+
+
+def _is_type_checking_guard(node: ast.If) -> bool:
+ """True for ``if TYPE_CHECKING:`` / ``if typing.TYPE_CHECKING:``."""
+ test = node.test
+ if isinstance(test, ast.Name):
+ return test.id == "TYPE_CHECKING"
+ if isinstance(test, ast.Attribute):
+ return test.attr == "TYPE_CHECKING"
+ return False
+
+
+def imports_sut(tree: ast.AST) -> bool:
+ """True if any *runtime* import statement pulls from the SUT package.
+
+ Imports under ``if TYPE_CHECKING:`` don't execute, so a test whose only
+ SUT reference is a type-hint import still exercises no production code —
+ those guard bodies are skipped (but the runtime ``else`` branch is not).
+ """
+ stack: list[ast.AST] = [tree]
+ while stack:
+ node = stack.pop()
+ if isinstance(node, ast.Import):
+ if any(_references_sut(alias.name) for alias in node.names):
+ return True
+ continue
+ if isinstance(node, ast.ImportFrom):
+ # Absolute import from the package (level 0); relative imports
+ # inside tests/ never reach the installed package, so ignore.
+ if node.level == 0 and _references_sut(node.module):
+ return True
+ continue
+ if isinstance(node, ast.If) and _is_type_checking_guard(node):
+ # Skip the type-only body; the else branch runs at runtime.
+ stack.extend(node.orelse)
+ continue
+ stack.extend(ast.iter_child_nodes(node))
+ return False
+
+
+def check_file(path: str) -> bool:
+ """Return True if `path` is an unmarked shadow test."""
+ if not is_test_module(path):
+ return False
+ try:
+ with open(path, encoding="utf-8") as fh:
+ source = fh.read()
+ except (OSError, UnicodeDecodeError):
+ return False
+ if ALLOW_RE.search(source):
+ return False
+ try:
+ tree = ast.parse(source, filename=path)
+ except SyntaxError:
+ # Let ruff / other hooks report syntax errors.
+ return False
+ return not imports_sut(tree)
+
+
+def main(argv: list[str]) -> int:
+ shadow = [p for p in argv if check_file(p)]
+ if not shadow:
+ return 0
+
+ print(f"{_RED}Shadow tests detected{_RESET}")
+ print("=" * 60)
+ print(
+ "These test modules import nothing from `local_deep_research`, so\n"
+ "they exercise no production code (see CONTRIBUTING.md → Testing):\n"
+ )
+ for path in shadow:
+ print(f" - {path}")
+ print()
+ print("Fix one of these ways:")
+ print(" 1. Import and exercise the real code under test, or")
+ print(" 2. If the file legitimately has no SUT import (e.g. a guardian")
+ print(" test), add a marker line stating why:")
+ print(" # allow: no-sut-import — <reason>")
+ print()
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3bfa5183e7..d6401a641c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -72,6 +72,26 @@ Run tests before submitting PRs:
pdm run python run_tests.py
```
+#### No shadow tests
+
+A test must exercise real production code. A **shadow test** imports nothing
+from `local_deep_research` and instead asserts on an inline reimplementation,
+pure stdlib behaviour, or a locally-built dict — it inflates the test count and
+coverage while catching zero regressions. The `check-shadow-tests` pre-commit
+hook blocks any `test_*.py` module that never imports the package.
+
+If a test legitimately has no SUT import — e.g. a black-box HTTP test driven
+through the Flask client, a meta-test for a pre-commit hook, or a guardian test
+that asserts on repository structure — exempt it with a self-documenting marker:
+
+```python
+# allow: no-sut-import — black-box API test, exercises the app via the Flask client
+```
+
+The reason after the marker is required. Whole black-box/meta test trees
+(`tests/api_tests/`, `tests/ui_tests/`, `tests/hooks/`, …) are excluded in
+`.pre-commit-config.yaml`.
+
### Code Quality
Pre-commit hooks will automatically:
diff --git a/tests/advanced_search_system/strategies/test_evidence_based_v2_extended.py b/tests/advanced_search_system/strategies/test_evidence_based_v2_extended.py
deleted file mode 100644
index f2da82bcb9..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_based_v2_extended.py
+++ /dev/null
@@ -1,651 +0,0 @@
-"""
-Extended Tests for Evidence-Based Strategy V2
-
-Phase 18: Advanced Search Strategies - Evidence-Based V2 Tests
-Tests evidence collection, claim verification, and synthesis.
-"""
-
-from datetime import datetime, UTC
-from unittest.mock import patch, MagicMock
-
-
-class TestEvidenceCollection:
- """Tests for evidence collection functionality"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_collect_evidence_from_search_results(self, mock_strategy_cls):
- """Test evidence is collected from search results"""
- mock_strategy = MagicMock()
- mock_strategy.analyze_topic.return_value = {
- "answer": "Test answer",
- "evidence": [{"source": "test", "text": "Evidence text"}],
- }
-
- result = mock_strategy.analyze_topic("test query")
-
- assert "evidence" in result
- assert len(result["evidence"]) > 0
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_quality_scoring(self, mock_strategy_cls):
- """Test evidence is scored for quality"""
- mock_strategy = MagicMock()
- mock_strategy._score_evidence.return_value = 0.85
-
- score = mock_strategy._score_evidence({"text": "Quality evidence"})
-
- assert score >= 0 and score <= 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_relevance_filtering(self, mock_strategy_cls):
- """Test irrelevant evidence is filtered out"""
- mock_strategy = MagicMock()
- mock_strategy._filter_relevant_evidence.return_value = [
- {"text": "Relevant evidence", "score": 0.9}
- ]
-
- evidence = [
- {"text": "Relevant evidence", "score": 0.9},
- {"text": "Irrelevant evidence", "score": 0.2},
- ]
-
- filtered = mock_strategy._filter_relevant_evidence(
- evidence, threshold=0.5
- )
-
- assert len(filtered) == 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_deduplication(self, mock_strategy_cls):
- """Test duplicate evidence is removed"""
- mock_strategy = MagicMock()
-
- evidence = [
- {"text": "Same evidence", "source": "source1"},
- {"text": "Same evidence", "source": "source2"},
- {"text": "Different evidence", "source": "source3"},
- ]
-
- mock_strategy._deduplicate_evidence.return_value = [
- {"text": "Same evidence", "source": "source1"},
- {"text": "Different evidence", "source": "source3"},
- ]
-
- deduped = mock_strategy._deduplicate_evidence(evidence)
-
- assert len(deduped) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_source_attribution(self, mock_strategy_cls):
- """Test evidence has proper source attribution"""
- mock_strategy = MagicMock()
- mock_strategy.analyze_topic.return_value = {
- "evidence": [
- {
- "text": "Evidence",
- "source": "https://example.com",
- "title": "Example",
- }
- ]
- }
-
- result = mock_strategy.analyze_topic("test")
-
- assert result["evidence"][0]["source"] == "https://example.com"
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_timestamp_extraction(self, mock_strategy_cls):
- """Test evidence timestamps are extracted"""
- mock_strategy = MagicMock()
- mock_strategy._extract_timestamp.return_value = datetime(
- 2024, 1, 15, tzinfo=UTC
- )
-
- timestamp = mock_strategy._extract_timestamp({"date": "2024-01-15"})
-
- assert timestamp.year == 2024
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_author_extraction(self, mock_strategy_cls):
- """Test evidence authors are extracted"""
- mock_strategy = MagicMock()
- mock_strategy._extract_author.return_value = "John Doe"
-
- author = mock_strategy._extract_author({"author": "John Doe"})
-
- assert author == "John Doe"
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_citation_parsing(self, mock_strategy_cls):
- """Test citation information is parsed"""
- mock_strategy = MagicMock()
- mock_strategy._parse_citation.return_value = {
- "author": "Smith, J.",
- "year": 2024,
- "title": "Research Paper",
- }
-
- citation = mock_strategy._parse_citation(
- "Smith, J. (2024). Research Paper."
- )
-
- assert citation["year"] == 2024
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_confidence_calculation(self, mock_strategy_cls):
- """Test evidence confidence is calculated"""
- mock_strategy = MagicMock()
- mock_strategy._calculate_confidence.return_value = 0.78
-
- confidence = mock_strategy._calculate_confidence(
- [{"score": 0.8}, {"score": 0.75}, {"score": 0.79}]
- )
-
- assert 0 <= confidence <= 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_conflicting_evidence_handling(self, mock_strategy_cls):
- """Test conflicting evidence is identified"""
- mock_strategy = MagicMock()
- mock_strategy._find_conflicts.return_value = [
- {"claim1": "A is true", "claim2": "A is false"}
- ]
-
- evidence = [{"claim": "A is true"}, {"claim": "A is false"}]
-
- conflicts = mock_strategy._find_conflicts(evidence)
-
- assert len(conflicts) == 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_synthesis_prompt(self, mock_strategy_cls):
- """Test synthesis prompt is generated"""
- mock_strategy = MagicMock()
- mock_strategy._create_synthesis_prompt.return_value = (
- "Synthesize the following evidence..."
- )
-
- prompt = mock_strategy._create_synthesis_prompt(
- [{"text": "Evidence 1"}]
- )
-
- assert "evidence" in prompt.lower() or "synthesize" in prompt.lower()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_ranking_algorithm(self, mock_strategy_cls):
- """Test evidence is ranked properly"""
- mock_strategy = MagicMock()
-
- evidence = [
- {"text": "Low quality", "score": 0.3},
- {"text": "High quality", "score": 0.9},
- {"text": "Medium quality", "score": 0.6},
- ]
-
- mock_strategy._rank_evidence.return_value = sorted(
- evidence, key=lambda x: x["score"], reverse=True
- )
-
- ranked = mock_strategy._rank_evidence(evidence)
-
- assert ranked[0]["score"] == 0.9
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_clustering(self, mock_strategy_cls):
- """Test evidence is clustered by topic"""
- mock_strategy = MagicMock()
- mock_strategy._cluster_evidence.return_value = {
- "topic1": [{"text": "Evidence about topic 1"}],
- "topic2": [{"text": "Evidence about topic 2"}],
- }
-
- clusters = mock_strategy._cluster_evidence(
- [
- {"text": "Evidence about topic 1"},
- {"text": "Evidence about topic 2"},
- ]
- )
-
- assert len(clusters) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_gap_identification(self, mock_strategy_cls):
- """Test evidence gaps are identified"""
- mock_strategy = MagicMock()
- mock_strategy._identify_gaps.return_value = [
- "No evidence found for aspect X",
- "Limited evidence for claim Y",
- ]
-
- gaps = mock_strategy._identify_gaps({"query": "test", "evidence": []})
-
- assert len(gaps) > 0
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_evidence_chain_building(self, mock_strategy_cls):
- """Test evidence chain is built"""
- mock_strategy = MagicMock()
- mock_strategy._build_evidence_chain.return_value = [
- {"step": 1, "evidence": "First point"},
- {"step": 2, "evidence": "Second point"},
- ]
-
- chain = mock_strategy._build_evidence_chain(
- [{"text": "First point"}, {"text": "Second point"}]
- )
-
- assert len(chain) == 2
-
-
-class TestClaimVerification:
- """Tests for claim verification functionality"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_extraction_from_text(self, mock_strategy_cls):
- """Test claims are extracted from text"""
- mock_strategy = MagicMock()
- mock_strategy._extract_claims.return_value = [
- "The sky is blue",
- "Water is wet",
- ]
-
- text = "The sky is blue. Water is wet. This is a fact."
- claims = mock_strategy._extract_claims(text)
-
- assert len(claims) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_classification(self, mock_strategy_cls):
- """Test claims are classified by type"""
- mock_strategy = MagicMock()
- mock_strategy._classify_claim.return_value = "factual"
-
- classification = mock_strategy._classify_claim("The earth is round")
-
- assert classification in ["factual", "opinion", "uncertain"]
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_evidence_matching(self, mock_strategy_cls):
- """Test claims are matched to supporting evidence"""
- mock_strategy = MagicMock()
- mock_strategy._match_evidence_to_claim.return_value = [
- {"evidence": "Supporting text", "relevance": 0.9}
- ]
-
- claim = "Climate change is real"
- evidence = [{"text": "Scientific consensus supports climate change"}]
-
- matches = mock_strategy._match_evidence_to_claim(claim, evidence)
-
- assert len(matches) > 0
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_confidence_scoring(self, mock_strategy_cls):
- """Test claim confidence is scored"""
- mock_strategy = MagicMock()
- mock_strategy._score_claim_confidence.return_value = 0.85
-
- score = mock_strategy._score_claim_confidence(
- claim="Test claim",
- supporting_evidence=[{"text": "Support 1"}, {"text": "Support 2"}],
- )
-
- assert 0 <= score <= 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_contradiction_detection(self, mock_strategy_cls):
- """Test contradicting claims are detected"""
- mock_strategy = MagicMock()
- mock_strategy._detect_contradictions.return_value = [
- {"claim1": "A is true", "claim2": "A is false", "type": "direct"}
- ]
-
- claims = ["A is true", "A is false"]
- contradictions = mock_strategy._detect_contradictions(claims)
-
- assert len(contradictions) == 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_support_counting(self, mock_strategy_cls):
- """Test number of supporting evidence is counted"""
- mock_strategy = MagicMock()
- mock_strategy._count_support.return_value = 5
-
- count = mock_strategy._count_support(
- "Test claim", [{"text": f"Support {i}"} for i in range(5)]
- )
-
- assert count == 5
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_source_diversity(self, mock_strategy_cls):
- """Test source diversity for claims"""
- mock_strategy = MagicMock()
- mock_strategy._calculate_source_diversity.return_value = 0.8
-
- evidence = [
- {"source": "source1.com"},
- {"source": "source2.com"},
- {"source": "source3.com"},
- ]
-
- diversity = mock_strategy._calculate_source_diversity(evidence)
-
- assert 0 <= diversity <= 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_recency_weighting(self, mock_strategy_cls):
- """Test recent claims are weighted higher"""
- mock_strategy = MagicMock()
- mock_strategy._apply_recency_weight.return_value = 0.95
-
- # Recent date should have higher weight
- weight = mock_strategy._apply_recency_weight(datetime.now(UTC))
-
- assert weight > 0.5
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_authority_scoring(self, mock_strategy_cls):
- """Test authority of sources is scored"""
- mock_strategy = MagicMock()
- mock_strategy._score_authority.return_value = 0.9
-
- score = mock_strategy._score_authority(
- {"source": "nature.com", "type": "academic"}
- )
-
- assert score > 0.7
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_consensus_calculation(self, mock_strategy_cls):
- """Test consensus level is calculated"""
- mock_strategy = MagicMock()
- mock_strategy._calculate_consensus.return_value = 0.85
-
- evidence = [{"supports": True} for _ in range(8)] + [
- {"supports": False} for _ in range(2)
- ]
-
- consensus = mock_strategy._calculate_consensus(evidence)
-
- assert consensus >= 0.8
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_multi_claim_synthesis(self, mock_strategy_cls):
- """Test multiple claims are synthesized"""
- mock_strategy = MagicMock()
- mock_strategy._synthesize_claims.return_value = (
- "Synthesized conclusion based on claims"
- )
-
- claims = ["Claim 1", "Claim 2", "Claim 3"]
- synthesis = mock_strategy._synthesize_claims(claims)
-
- assert len(synthesis) > 0
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_hierarchy_building(self, mock_strategy_cls):
- """Test claim hierarchy is built"""
- mock_strategy = MagicMock()
- mock_strategy._build_claim_hierarchy.return_value = {
- "main_claim": "Main point",
- "sub_claims": ["Sub point 1", "Sub point 2"],
- }
-
- hierarchy = mock_strategy._build_claim_hierarchy(
- ["Main point", "Sub point 1", "Sub point 2"]
- )
-
- assert "main_claim" in hierarchy
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_dependency_graph(self, mock_strategy_cls):
- """Test claim dependencies are mapped"""
- mock_strategy = MagicMock()
- mock_strategy._build_dependency_graph.return_value = {
- "A": ["B", "C"],
- "B": [],
- "C": ["D"],
- }
-
- graph = mock_strategy._build_dependency_graph(
- ["A depends on B and C", "C depends on D"]
- )
-
- assert "A" in graph
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_verification_prompt(self, mock_strategy_cls):
- """Test verification prompt is generated"""
- mock_strategy = MagicMock()
- mock_strategy._create_verification_prompt.return_value = (
- "Verify the following claim..."
- )
-
- prompt = mock_strategy._create_verification_prompt(
- "Test claim", [{"text": "Evidence"}]
- )
-
- assert "verify" in prompt.lower() or "claim" in prompt.lower()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_uncertainty_quantification(self, mock_strategy_cls):
- """Test uncertainty is quantified"""
- mock_strategy = MagicMock()
- mock_strategy._quantify_uncertainty.return_value = 0.15
-
- uncertainty = mock_strategy._quantify_uncertainty(
- "Test claim", [{"text": "Mixed evidence"}]
- )
-
- assert 0 <= uncertainty <= 1
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_revision_tracking(self, mock_strategy_cls):
- """Test claim revisions are tracked"""
- mock_strategy = MagicMock()
- mock_strategy._track_revision.return_value = {
- "original": "Initial claim",
- "revised": "Updated claim",
- "reason": "New evidence",
- }
-
- revision = mock_strategy._track_revision(
- "Initial claim", "Updated claim", "New evidence"
- )
-
- assert "original" in revision
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_merge_conflicting(self, mock_strategy_cls):
- """Test conflicting claims are merged"""
- mock_strategy = MagicMock()
- mock_strategy._merge_conflicting_claims.return_value = (
- "Merged claim acknowledging both perspectives"
- )
-
- merged = mock_strategy._merge_conflicting_claims(["View A", "View B"])
-
- assert len(merged) > 0
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_split_compound(self, mock_strategy_cls):
- """Test compound claims are split"""
- mock_strategy = MagicMock()
- mock_strategy._split_compound_claim.return_value = [
- "Claim part 1",
- "Claim part 2",
- ]
-
- compound = "Claim part 1 and claim part 2"
- parts = mock_strategy._split_compound_claim(compound)
-
- assert len(parts) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_normalize_text(self, mock_strategy_cls):
- """Test claim text is normalized"""
- mock_strategy = MagicMock()
- mock_strategy._normalize_claim.return_value = "normalized claim text"
-
- normalized = mock_strategy._normalize_claim(" Normalized CLAIM Text ")
-
- assert normalized == "normalized claim text"
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_claim_semantic_similarity(self, mock_strategy_cls):
- """Test semantic similarity between claims"""
- mock_strategy = MagicMock()
- mock_strategy._calculate_similarity.return_value = 0.92
-
- similarity = mock_strategy._calculate_similarity(
- "The cat sat on the mat", "A cat was sitting on a mat"
- )
-
- assert similarity > 0.8
-
-
-class TestStrategyIntegration:
- """Tests for strategy integration and orchestration"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_analyze_topic_returns_result(self, mock_strategy_cls):
- """Test analyze_topic returns proper result"""
- mock_strategy = MagicMock()
- mock_strategy.analyze_topic.return_value = {
- "answer": "Test answer",
- "confidence": 0.85,
- "sources": [],
- }
-
- result = mock_strategy.analyze_topic("test query")
-
- assert "answer" in result
- assert "confidence" in result
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_progress_callback_invoked(self, mock_strategy_cls):
- """Test progress callback is invoked during analysis"""
- mock_strategy = MagicMock()
- mock_callback = MagicMock()
-
- mock_strategy.set_progress_callback(mock_callback)
-
- # Should have callback set
- mock_strategy.set_progress_callback.assert_called_once()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_source_profile_tracking(self, mock_strategy_cls):
- """Test source profiles are tracked"""
- mock_strategy = MagicMock()
- mock_strategy.source_profiles = {
- "arxiv.org": {"success_rate": 0.9, "usage_count": 10},
- "pubmed.gov": {"success_rate": 0.85, "usage_count": 8},
- }
-
- assert mock_strategy.source_profiles["arxiv.org"]["success_rate"] == 0.9
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_query_pattern_learning(self, mock_strategy_cls):
- """Test query patterns are learned"""
- mock_strategy = MagicMock()
- mock_strategy.query_patterns = [
- {"pattern": "what is", "success_rate": 0.8},
- {"pattern": "how does", "success_rate": 0.75},
- ]
-
- assert len(mock_strategy.query_patterns) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
- )
- def test_multi_stage_discovery(self, mock_strategy_cls):
- """Test multi-stage discovery process"""
- mock_strategy = MagicMock()
- mock_strategy._enhanced_candidate_discovery.return_value = {
- "stage_1": ["candidate1"],
- "stage_2": ["candidate2"],
- "total": 2,
- }
-
- result = mock_strategy._enhanced_candidate_discovery("test query")
-
- assert result["total"] == 2
diff --git a/tests/chat/test_chat_api.py b/tests/chat/test_chat_api.py
index f6c58b941b..7af73293b6 100644
--- a/tests/chat/test_chat_api.py
+++ b/tests/chat/test_chat_api.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for Chat API endpoints and progress handling.
"""
diff --git a/tests/chat/test_chat_concurrency_guard.py b/tests/chat/test_chat_concurrency_guard.py
index d00f7c6e0a..5ad70165f2 100644
--- a/tests/chat/test_chat_concurrency_guard.py
+++ b/tests/chat/test_chat_concurrency_guard.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for the per-session concurrency guard on POST /api/chat/sessions/<id>/messages.
Chat is sequential by design: at most one in-flight research per session.
diff --git a/tests/chat/test_chat_csrf.py b/tests/chat/test_chat_csrf.py
index 7f7d8f5f85..5745c1089c 100644
--- a/tests/chat/test_chat_csrf.py
+++ b/tests/chat/test_chat_csrf.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
CSRF protection tests for chat API endpoints.
diff --git a/tests/chat/test_chat_e2e_flows.py b/tests/chat/test_chat_e2e_flows.py
index 6d4b285a0b..fd0c4ce554 100644
--- a/tests/chat/test_chat_e2e_flows.py
+++ b/tests/chat/test_chat_e2e_flows.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat end-to-end flows.
diff --git a/tests/chat/test_chat_error_handling.py b/tests/chat/test_chat_error_handling.py
index 3cb03bd264..300e397d01 100644
--- a/tests/chat/test_chat_error_handling.py
+++ b/tests/chat/test_chat_error_handling.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat error handling and edge cases.
diff --git a/tests/chat/test_chat_input_validation.py b/tests/chat/test_chat_input_validation.py
index 37cbdc8f14..3b8084ba11 100644
--- a/tests/chat/test_chat_input_validation.py
+++ b/tests/chat/test_chat_input_validation.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat API input validation.
diff --git a/tests/chat/test_chat_large_data.py b/tests/chat/test_chat_large_data.py
index 00f8b377a2..f884655478 100644
--- a/tests/chat/test_chat_large_data.py
+++ b/tests/chat/test_chat_large_data.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat large data handling.
diff --git a/tests/chat/test_chat_messages.py b/tests/chat/test_chat_messages.py
index 2aad7324a3..b6487858dc 100644
--- a/tests/chat/test_chat_messages.py
+++ b/tests/chat/test_chat_messages.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat message functionality.
diff --git a/tests/chat/test_chat_page_routes.py b/tests/chat/test_chat_page_routes.py
index 23840e1dba..b1aaf798b0 100644
--- a/tests/chat/test_chat_page_routes.py
+++ b/tests/chat/test_chat_page_routes.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat page routes (GET /chat/ and GET /chat/<session_id>).
diff --git a/tests/chat/test_chat_research_triggering.py b/tests/chat/test_chat_research_triggering.py
index 70640a6435..4e04a486d0 100644
--- a/tests/chat/test_chat_research_triggering.py
+++ b/tests/chat/test_chat_research_triggering.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat research triggering edge cases.
diff --git a/tests/chat/test_chat_route_validation.py b/tests/chat/test_chat_route_validation.py
index b895715a95..7b09da36ed 100644
--- a/tests/chat/test_chat_route_validation.py
+++ b/tests/chat/test_chat_route_validation.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Unit tests for Chat route input validation.
Tests verify request validation in chat API routes:
diff --git a/tests/chat/test_chat_security.py b/tests/chat/test_chat_security.py
index ad93d0fed6..8e975ab7e1 100644
--- a/tests/chat/test_chat_security.py
+++ b/tests/chat/test_chat_security.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Security tests for chat feature.
diff --git a/tests/chat/test_chat_service_unit.py b/tests/chat/test_chat_service_unit.py
index a051770d7b..bdc18528fd 100644
--- a/tests/chat/test_chat_service_unit.py
+++ b/tests/chat/test_chat_service_unit.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Unit tests for ChatService class.
diff --git a/tests/chat/test_chat_session_lifecycle.py b/tests/chat/test_chat_session_lifecycle.py
index 575f9c798d..485492cdbb 100644
--- a/tests/chat/test_chat_session_lifecycle.py
+++ b/tests/chat/test_chat_session_lifecycle.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for chat session lifecycle management.
diff --git a/tests/database/test_no_raw_sql.py b/tests/database/test_no_raw_sql.py
index 22a8e383ed..6cb0582941 100644
--- a/tests/database/test_no_raw_sql.py
+++ b/tests/database/test_no_raw_sql.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# allow: no-sut-import — guardian; scans the codebase for raw SQL outside allowed locations
"""Test to verify no raw SQL is used in the codebase (except in allowed locations)."""
import sys
diff --git a/tests/document_loaders/test_loader_registry_import_guards.py b/tests/document_loaders/test_loader_registry_import_guards.py
index a702d3e6d3..f2ef656730 100644
--- a/tests/document_loaders/test_loader_registry_import_guards.py
+++ b/tests/document_loaders/test_loader_registry_import_guards.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — exercises loader_registry via importlib reload with a patched import hook (dynamic import)
"""
Import-guard tests for loader_registry module.
diff --git a/tests/hooks/test_check_shadow_tests.py b/tests/hooks/test_check_shadow_tests.py
new file mode 100644
index 0000000000..494f41547e
--- /dev/null
+++ b/tests/hooks/test_check_shadow_tests.py
@@ -0,0 +1,130 @@
+"""Tests for the check-shadow-tests pre-commit hook.
+
+Verifies that the hook flags test modules with no ``local_deep_research``
+import (shadow tests) while allowing real tests, the ``# allow:
+no-sut-import`` opt-out, and non-test modules.
+"""
+
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+HOOK_SCRIPT = (
+ Path(__file__).parent.parent.parent
+ / ".pre-commit-hooks"
+ / "check-shadow-tests.py"
+)
+
+
+def _run_hook(content: str, filename: str = "test_sample.py"):
+ """Write content to a temp file named `filename` and run the hook."""
+ with tempfile.TemporaryDirectory() as d:
+ path = Path(d) / filename
+ path.write_text(content, encoding="utf-8")
+ return subprocess.run(
+ [sys.executable, str(HOOK_SCRIPT), str(path)],
+ capture_output=True,
+ text=True,
+ )
+
+
+class TestFlagsShadowTests:
+ """Test modules that exercise no SUT must be flagged."""
+
+ def test_inline_logic_no_sut_import(self):
+ result = _run_hook(
+ "import datetime\n\n"
+ "def test_year():\n"
+ " assert datetime.date(2020, 1, 1).year == 2020\n"
+ )
+ assert result.returncode == 1
+ assert "Shadow tests detected" in result.stdout
+
+ def test_only_stdlib_imports(self):
+ result = _run_hook(
+ "import json\n\ndef test_roundtrip():\n"
+ ' assert json.loads(json.dumps({"a": 1})) == {"a": 1}\n'
+ )
+ assert result.returncode == 1
+
+ def test_type_checking_only_import_flagged(self):
+ # SUT imported only for type hints never runs, so it's still a shadow.
+ result = _run_hook(
+ "from typing import TYPE_CHECKING\n\n"
+ "if TYPE_CHECKING:\n"
+ " from local_deep_research.config import Thing\n\n"
+ "def test_x():\n assert 1 == 1\n"
+ )
+ assert result.returncode == 1
+
+
+class TestAllowsRealTests:
+ """Files that import the SUT — or are exempt — must pass."""
+
+ def test_from_import_passes(self):
+ result = _run_hook(
+ "from local_deep_research.config import x\n\n"
+ "def test_x():\n assert x\n"
+ )
+ assert result.returncode == 0
+
+ def test_src_prefixed_import_passes(self):
+ result = _run_hook(
+ "from src.local_deep_research import app\n\n"
+ "def test_app():\n assert app\n"
+ )
+ assert result.returncode == 0
+
+ def test_plain_import_passes(self):
+ result = _run_hook(
+ "import local_deep_research\n\n"
+ "def test_pkg():\n assert local_deep_research\n"
+ )
+ assert result.returncode == 0
+
+ def test_type_checking_plus_runtime_import_passes(self):
+ # A type-only import under TYPE_CHECKING is ignored, but the runtime
+ # import at module level still counts.
+ result = _run_hook(
+ "from typing import TYPE_CHECKING\n\n"
+ "if TYPE_CHECKING:\n"
+ " from local_deep_research.config import Thing\n\n"
+ "from local_deep_research.config import run\n\n"
+ "def test_x():\n assert run\n"
+ )
+ assert result.returncode == 0
+
+ def test_allow_marker_exempts(self):
+ result = _run_hook(
+ "# allow: no-sut-import — guardian test asserting repo structure\n"
+ "import os\n\ndef test_repo():\n assert os.path.exists('.')\n"
+ )
+ assert result.returncode == 0
+
+ def test_marker_without_reason_does_not_exempt(self):
+ # The reason text after the marker is mandatory.
+ result = _run_hook(
+ "# allow: no-sut-import\n"
+ "import os\n\ndef test_repo():\n assert os.path.exists('.')\n"
+ )
+ assert result.returncode == 1
+
+
+class TestScope:
+ """Only pytest test modules are inspected."""
+
+ def test_non_test_module_ignored(self):
+ result = _run_hook("import datetime\n", filename="helpers.py")
+ assert result.returncode == 0
+
+ def test_conftest_ignored(self):
+ result = _run_hook("import datetime\n", filename="conftest.py")
+ assert result.returncode == 0
+
+ def test_underscore_test_suffix_inspected(self):
+ result = _run_hook(
+ "import datetime\n\ndef test_x():\n assert datetime\n",
+ filename="sample_test.py",
+ )
+ assert result.returncode == 1
diff --git a/tests/news/test_news_rate_limiting.py b/tests/news/test_news_rate_limiting.py
index 2c49db33c6..8fd59b72ac 100644
--- a/tests/news/test_news_rate_limiting.py
+++ b/tests/news/test_news_rate_limiting.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — guardian; AST-parses news_routes.py source to assert rate-limit decorators are present
"""
Tests for rate limiting decorators on news API routes.
diff --git a/tests/research_library/routes/test_rag_routes_indexing.py b/tests/research_library/routes/test_rag_routes_indexing.py
index 32ca69eee6..69cebd05f3 100644
--- a/tests/research_library/routes/test_rag_routes_indexing.py
+++ b/tests/research_library/routes/test_rag_routes_indexing.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for index_local_library and view_document_chunks in rag_routes.py."""
from unittest.mock import patch, MagicMock
diff --git a/tests/research_library/search/routes/test_search_routes.py b/tests/research_library/search/routes/test_search_routes.py
index c336a17e01..c52fb76597 100644
--- a/tests/research_library/search/routes/test_search_routes.py
+++ b/tests/research_library/search/routes/test_search_routes.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Tests for collection search and research history routes.
diff --git a/tests/security/test_api_v1_auth.py b/tests/security/test_api_v1_auth.py
index 51df8b4074..634ade1bef 100644
--- a/tests/security/test_api_v1_auth.py
+++ b/tests/security/test_api_v1_auth.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Test API v1 authentication guard."""
diff --git a/tests/security/test_csrf_e2e_flow.py b/tests/security/test_csrf_e2e_flow.py
index b7beb0afa7..2ad9c9e618 100644
--- a/tests/security/test_csrf_e2e_flow.py
+++ b/tests/security/test_csrf_e2e_flow.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
End-to-end CSRF flow test for browser-facing API endpoints.
diff --git a/tests/security/test_csrf_hardening.py b/tests/security/test_csrf_hardening.py
index 68a2e03f71..3633d3e20a 100644
--- a/tests/security/test_csrf_hardening.py
+++ b/tests/security/test_csrf_hardening.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — exercises the real app fixture; asserts CSRF exemptions on the live blueprint config
"""Test CSRF hardening configuration against the real app."""
diff --git a/tests/security/test_repo_guardrails.py b/tests/security/test_repo_guardrails.py
index 01711bffc1..7c99bbe2b3 100644
--- a/tests/security/test_repo_guardrails.py
+++ b/tests/security/test_repo_guardrails.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — guardian; asserts repo file-whitelist and CODEOWNERS structural invariants
"""Tests that repository integrity guardrails remain intact.
These tests verify structural invariants of the file whitelist and
diff --git a/tests/security/test_sensitive_data_logging.py b/tests/security/test_sensitive_data_logging.py
index 563f01faaf..dd2beea1f5 100644
--- a/tests/security/test_sensitive_data_logging.py
+++ b/tests/security/test_sensitive_data_logging.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — guardian; greps history_routes.py source to keep sensitive data out of logs
"""Tests for sensitive data logging changes in history_routes.
Verifies that PR #1896 changes are in place:
diff --git a/tests/settings/test_generate_config_docs.py b/tests/settings/test_generate_config_docs.py
index d68a7e1b04..f4ad08a1ed 100644
--- a/tests/settings/test_generate_config_docs.py
+++ b/tests/settings/test_generate_config_docs.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — tests scripts/generate_config_docs.py, repo tooling outside the local_deep_research package
"""
Tests for scripts/generate_config_docs.py
diff --git a/tests/settings/test_hidden_internal_settings.py b/tests/settings/test_hidden_internal_settings.py
index 11f1f67aed..f548dda8e0 100644
--- a/tests/settings/test_hidden_internal_settings.py
+++ b/tests/settings/test_hidden_internal_settings.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — guardian on defaults/default_settings.json; asserts engine internals stay out of user settings
import json
from pathlib import Path
diff --git a/tests/test_ci_config.py b/tests/test_ci_config.py
index ee0aa23771..74eca814b2 100644
--- a/tests/test_ci_config.py
+++ b/tests/test_ci_config.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — not a test module; CI env-setup helper that only sets os.environ, no SUT to import
"""
CI-specific test configuration for API tests.
Sets up environment for tests to run without external LLM services.
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 8762eed866..1395df7f0a 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — shared test-helper module (not a test); provides utilities imported by other tests
"""
Test utilities and helper functions - incorporating scottvr's patterns.
diff --git a/tests/utilities/test_loguru_placeholder_formatting.py b/tests/utilities/test_loguru_placeholder_formatting.py
index 70bcdbec26..099e045806 100644
--- a/tests/utilities/test_loguru_placeholder_formatting.py
+++ b/tests/utilities/test_loguru_placeholder_formatting.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — guardian; sweeps src/ to forbid printf-style placeholders in loguru calls
import ast
from pathlib import Path
import re
diff --git a/tests/utilities/test_sqlcipher_compat_coverage.py b/tests/utilities/test_sqlcipher_compat_coverage.py
index 9ace0909eb..8a9bae7bc3 100644
--- a/tests/utilities/test_sqlcipher_compat_coverage.py
+++ b/tests/utilities/test_sqlcipher_compat_coverage.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — exercises sqlcipher_compat via importlib reload to cover ImportError paths (dynamic import)
"""
Comprehensive tests for local_deep_research.database.sqlcipher_compat module.
diff --git a/tests/web/routes/test_api_routes.py b/tests/web/routes/test_api_routes.py
index 81d0aec54b..af6cafc979 100644
--- a/tests/web/routes/test_api_routes.py
+++ b/tests/web/routes/test_api_routes.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for api_routes module - API endpoints."""
from unittest.mock import patch, MagicMock
diff --git a/tests/web/routes/test_metrics_routes_rate_limits.py b/tests/web/routes/test_metrics_routes_rate_limits.py
index b60a5b2842..6248a0aafe 100644
--- a/tests/web/routes/test_metrics_routes_rate_limits.py
+++ b/tests/web/routes/test_metrics_routes_rate_limits.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for api_current_rate_limits and api_cost_calculation in metrics_routes.py."""
import time
diff --git a/tests/web/routes/test_ollama_status.py b/tests/web/routes/test_ollama_status.py
index d6ea36c831..12dbb52ab2 100644
--- a/tests/web/routes/test_ollama_status.py
+++ b/tests/web/routes/test_ollama_status.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for Ollama status/model check endpoints in api_routes.py."""
from unittest.mock import patch, MagicMock
diff --git a/tests/web/routes/test_research_routes.py b/tests/web/routes/test_research_routes.py
index 863625589a..62571d7aa9 100644
--- a/tests/web/routes/test_research_routes.py
+++ b/tests/web/routes/test_research_routes.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for research_routes module - Research page and API endpoints."""
from unittest.mock import patch, MagicMock
diff --git a/tests/web/routes/test_research_routes_config.py b/tests/web/routes/test_research_routes_config.py
index 86321550b9..cfcbfee1fc 100644
--- a/tests/web/routes/test_research_routes_config.py
+++ b/tests/web/routes/test_research_routes_config.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for save_raw_config and get_upload_limits in research_routes.py."""
from unittest.mock import patch
diff --git a/tests/web/routes/test_search_favorites.py b/tests/web/routes/test_search_favorites.py
index 0aa890b3df..941e298a0a 100644
--- a/tests/web/routes/test_search_favorites.py
+++ b/tests/web/routes/test_search_favorites.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for search favorites API endpoints in settings_routes.py."""
from unittest.mock import patch, MagicMock
diff --git a/tests/web/routes/test_settings_routes_rate_limiting.py b/tests/web/routes/test_settings_routes_rate_limiting.py
index 665d7c91cd..813602161a 100644
--- a/tests/web/routes/test_settings_routes_rate_limiting.py
+++ b/tests/web/routes/test_settings_routes_rate_limiting.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for rate limiting and notification endpoints in settings_routes.py."""
from unittest.mock import patch, MagicMock
diff --git a/tests/web/services/test_socket_service_extended.py b/tests/web/services/test_socket_service_extended.py
index b42c207bb5..b901a79c65 100644
--- a/tests/web/services/test_socket_service_extended.py
+++ b/tests/web/services/test_socket_service_extended.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""
Extended Tests for Socket Service
diff --git a/tests/web_search_engines/test_engine_user_agents.py b/tests/web_search_engines/test_engine_user_agents.py
index 0fefd757b9..0caf188d4d 100644
--- a/tests/web_search_engines/test_engine_user_agents.py
+++ b/tests/web_search_engines/test_engine_user_agents.py
@@ -1,3 +1,4 @@
+# allow: no-sut-import — guardian; sweeps engine source files to enforce the centralized USER_AGENT constant
"""Regression tests for the User-Agent invariant across search engines.
Follow-up to issue #4130: nine search-engine modules used to hand-roll